@runtypelabs/persona 3.10.0 → 3.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import{Marked as Bd}from"marked";var Dd=e=>{if(e)return e},Qo=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new Bd({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=Dd(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},Yr=e=>e?Qo({markedOptions:e.options,renderer:e.renderer}):Qo(),Nd=Qo(),Ql=e=>Nd(e),So=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ec=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Zl=e=>`%%FORM_PLACEHOLDER_${e}%%`,tc=(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=Zl(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=Zl(r.length);return r.push({token:o,type:s}),o}),t},Fd=e=>{let r=Yr(e);return t=>{let n=[],s=tc(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let u=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ec(i)}"></div>`;o=o.replace(u,d)}),o}},Od=e=>{let r=[],t=tc(e,r),n=Ql(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${ec(o)}"></div>`;n=n.replace(a,u)}),n};import $d from"dompurify";var _d={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"]},jd=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,nc=()=>{let e=$d(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:")&&!jd.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,_d)},Ao=e=>e===!1?null:typeof e=="function"?e:nc();import{parse as rc,STR as oc,OBJ as sc}from"partial-json";var es=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Gr=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},zd=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`},ac=e=>e.status==="complete"?zd(e):e.status==="pending"?"Waiting":"",qd=e=>{var s,o,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var ic=e=>e.status==="complete"?qd(e):"Using tool...",Ud=()=>{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 Kd=e=>{if(e)return e},ts=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=Kd(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},Gr=e=>e?ts({markedOptions:e.options,renderer:e.renderer}):ts(),Zd=ts(),mc=e=>Zd(e),Eo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),gc=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),uc=e=>`%%FORM_PLACEHOLDER_${e}%%`,fc=(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=uc(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=uc(r.length);return r.push({token:o,type:s}),o}),t},Qd=e=>{let r=Gr(e);return t=>{let n=[],s=fc(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let u=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${gc(i)}"></div>`;o=o.replace(u,d)}),o}},ep=e=>{let r=[],t=fc(e,r),n=mc(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${gc(o)}"></div>`;n=n.replace(a,u)}),n};import tp from"dompurify";var np={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"]},rp=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,hc=()=>{let e=tp(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:")&&!rp.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,np)},To=e=>e===!1?null:typeof e=="function"?e:hc();import{parse as yc,STR as bc,OBJ as xc}from"partial-json";var ns=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Xr=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)}},op=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`},vc=e=>e.status==="complete"?op(e):e.status==="pending"?"Waiting":"",sp=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 Cc=e=>e.status==="complete"?sp(e):"Using tool...",ap=()=>{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()=>{}}},Hr=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},Ps=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ws=()=>{var r;let e=Ud();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)}},Rs=()=>{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=rc(t,oc|sc);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?es(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=es(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Vd=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?es(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?es(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=rc(o,oc|sc),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Hs=()=>{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 Jd="https://api.runtype.com/v1/dispatch",Bs="https://api.runtype.com",Ds=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 Yd(e){switch(e){case"json":return Rs;case"regex-json":return Ws;case"xml":return Hs;default:return Ps}}var lc=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gd(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=lc(t);if(!lc(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=Hr(e);return Hr(r)!==null&&a===null?r:e}var Xr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:Jd,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Yd(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$/,""))||Bs;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$/,""))||Bs}/v1/client/feedback`}async sendFeedback(r){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let f=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:f}),f}let c=await this.buildPayload(r.messages),d=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,p={sessionId:u.sessionId,messages:r.messages.filter(Ds).map(f=>{var v,A,x;return{id:f.id,role:f.role,content:(x=(A=(v=f.contentParts)!=null?v:f.llmContent)!=null?A:f.rawContent)!=null?x:f.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!m.ok){let f=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:A}),A}if(m.status===429){let A=new Error(f.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let v=new Error(f.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!m.body){let f=new Error("No response body received");throw t({type:"error",error:f}),f}t({type:"status",status:"connected"});try{await this.streamResponse(m.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Bs}/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(Ds).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(Ds).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=d=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...d!==void 0&&{partId:d}};return n.current=p,s(p),p},c=d=>n.current?n.current:u(d);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(i.partId)),i.partId!==void 0&&(a.current=i.partId);let d=c(i.partId);i.partId!==void 0&&!d.partId&&(d.partId=i.partId),d.content+=i.text,s(d)}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 U,re,_e,Z,ee,kt,ct,Dt,Jt,je,le,De,It,Pt,rt,ot,en,Qt,tn,_,We,de,ft,$e,te,he,Fe,Ct,_t,dt,jt,ht,Ze,yt,Ue,zt,Jn,Qn,Nn,et,Sr,Yn,Ar,In,Fr,lr,er,st,Cn,Fn,cn,cr,wn,St,dn,Pn,dr,tr,pr,Gn,Sn,Xn,At,Ft,Ot,An,ur,On,En,D,$n,Wn,gr,gn,Tn,oe,_n,Or,lo,$r,Qe,co,Rn,mn,$o,_o,po,nr,jo,_r,jr,rr,uo,mr,fr,zo,qo,ks,Er,Tr,Wt,zr,qr,go,mo,fo,ho,pn,Mn,or,Ve,yo,Mr,jn,Uo,Ur,Vr,kr,hr,Vo;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,d=X=>{let Be=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,Ge=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,Rt=X.tools?X.tools.map(bt=>({...bt,chunks:bt.chunks?[...bt.chunks]:void 0})):void 0;return{...X,reasoning:Be,toolCall:Ge,tools:Rt}},p=X=>{t({type:"message",message:d(X)})},m=null,f={current:null},v={current:null},A=!1,x=new Map,C=new Map,k={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}},M=X=>{var Be,Ge,Rt,bt,it;return w((it=(bt=(Rt=(Ge=(Be=X.stepId)!=null?Be:X.step_id)!=null?Ge:X.step)!=null?Rt:X.parentId)!=null?bt:X.flowStepId)!=null?it:X.flow_step_id)},W=X=>{var Be,Ge,Rt,bt,it,ke,y;return w((y=(ke=(it=(bt=(Rt=(Ge=(Be=X.callId)!=null?Be:X.call_id)!=null?Ge:X.requestId)!=null?Rt:X.request_id)!=null?bt:X.toolCallId)!=null?it:X.tool_call_id)!=null?ke:X.stepId)!=null?y:X.step_id)},E=n,G=!1,K=()=>{if(m)return m;let X;return!G&&E?(X=E,G=!0):E&&v.current?X=`${E}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(m),m},J=(X,Be)=>{k.lastId=Be,X&&k.byStep.set(X,Be)},L=(X,Be)=>{var it;let Ge=(it=X.reasoningId)!=null?it:X.id,Rt=M(X);if(Ge){let ke=String(Ge);return J(Rt,ke),ke}if(Rt){let ke=k.byStep.get(Rt);if(ke)return k.lastId=ke,ke}if(k.lastId&&!Be)return k.lastId;if(!Be)return null;let bt=`reason-${c()}`;return J(Rt,bt),bt},Q=X=>{let Be=x.get(X);if(Be)return Be;let Ge={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return x.set(X,Ge),p(Ge),Ge},we=(X,Be)=>{R.lastId=Be,X&&R.byCall.set(X,Be)},ne=new Set,Ee=new Map,Oe=new Set,fe=new Map,Ie=X=>{if(!X)return!1;let Be=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Be==="emit_artifact_markdown"||Be==="emit_artifact_component"},Pe=(X,Be)=>{var it;let Ge=(it=X.toolId)!=null?it:X.id,Rt=W(X);if(Ge){let ke=String(Ge);return we(Rt,ke),ke}if(Rt){let ke=R.byCall.get(Rt);if(ke)return R.lastId=ke,ke}if(R.lastId&&!Be)return R.lastId;if(!Be)return null;let bt=`tool-${c()}`;return we(Rt,bt),bt},se=X=>{let Be=C.get(X);if(Be)return Be;let Ge={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,Ge),p(Ge),Ge},be=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Be=Number(X);if(!Number.isNaN(Be)&&Number.isFinite(Be))return Be;let Ge=Date.parse(X);if(!Number.isNaN(Ge))return Ge}return Date.now()},ze=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},ce=new Map,ae=new Map,Te=new Map,Ne=new Map;function lt(X,Be,Ge,Rt){let bt=X.get(Be);bt||(bt=[],X.set(Be,bt));let it=0,ke=bt.length;for(;it<ke;){let ve=it+ke>>>1;bt[ve].seq<Ge?it=ve+1:ke=ve}bt.splice(it,0,{seq:Ge,text:Rt});let y="";for(let ve=0;ve<bt.length;ve++)y+=bt[ve].text;return y}let Tt=null,q=(X,Be)=>{let Ge=ze(Be),Rt=ae.get(X.id),bt=Gd(Rt,Ge);X.rawContent=bt;let it=ce.get(X.id),ke=Y=>{var pe;let N=(pe=X.content)!=null?pe:"";Y.trim()!==""&&(N.trim().length===0||Y.startsWith(N)||Y.trimStart().startsWith(N.trim()))&&(X.content=Y)},y=()=>{var Y;if(it){let N=(Y=it.close)==null?void 0:Y.call(it);N instanceof Promise&&N.catch(()=>{})}ce.delete(X.id),ae.delete(X.id),X.streaming=!1,p(X)};if(!it){ke(Ge),y();return}let ve=Hr(bt);if(ve!==null&&ve.trim()!==""){ke(ve),y();return}let P=Y=>{var xe;let N=typeof Y=="string"?Y:(xe=Y==null?void 0:Y.text)!=null?xe:null;if(N!==null&&N.trim()!=="")return N;let pe=it.getExtractedText();return pe!==null&&pe.trim()!==""?pe:Ge},S;try{S=it.processChunk(bt)}catch{ke(Ge),y();return}if(S instanceof Promise){S.then(Y=>{ke(P(Y)),y()}).catch(()=>{ke(Ge),y()});return}ke(P(S)),y()},F=null,ie=new Map,j=(U=this.config.iterationDisplay)!=null?U:"separate";for(;;){let{done:X,value:Be}=await s.read();if(X)break;a+=o.decode(Be,{stream:!0});let Ge=a.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Nr=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},Bs=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ds=()=>{var r;let e=ap();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)}},Ns=()=>{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=yc(t,bc|xc);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?ns(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=ns(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},ip=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?ns(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?ns(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=yc(o,bc|xc),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Fs=()=>{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 lp="https://api.runtype.com/v1/dispatch",Os="https://api.runtype.com",$s=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 cp(e){switch(e){case"json":return Ns;case"regex-json":return Ds;case"xml":return Fs;default:return Bs}}var wc=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function dp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=wc(t);if(!wc(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=Nr(e);return Nr(r)!==null&&a===null?r:e}var Kr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:lp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:cp(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$/,""))||Os;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$/,""))||Os}/v1/client/feedback`}async sendFeedback(r){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let f=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:f}),f}let c=await this.buildPayload(r.messages),d=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,p={sessionId:u.sessionId,messages:r.messages.filter($s).map(f=>{var v,E,x;return{id:f.id,role:f.role,content:(x=(E=(v=f.contentParts)!=null?v:f.llmContent)!=null?E:f.rawContent)!=null?x:f.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let g=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!g.ok){let f=await g.json().catch(()=>({error:"Chat request failed"}));if(g.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let E=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:E}),E}if(g.status===429){let E=new Error(f.hint||"Message limit reached for this session.");throw t({type:"error",error:E}),E}let v=new Error(f.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!g.body){let f=new Error("No response body received");throw t({type:"error",error:f}),f}t({type:"status",status:"connected"});try{await this.streamResponse(g.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Os}/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($s).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($s).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=d=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...d!==void 0&&{partId:d}};return n.current=p,s(p),p},c=d=>n.current?n.current:u(d);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(i.partId)),i.partId!==void 0&&(a.current=i.partId);let d=c(i.partId);i.partId!==void 0&&!d.partId&&(d.partId=i.partId),d.content+=i.text,s(d)}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 V,oe,Oe,Z,te,kt,lt,Nt,Xt,$e,ce,He,Pt,Wt,ot,st,rn,tn,on,j,Ie,ue,gt,Fe,ne,ye,De,xt,zt,ct,qt,ft,Ke,ht,We,Vt,Gn,tr,On,Qe,Tr,Xn,Mr,Pn,_r,pr,nr,at,wn,$n,dn,ur,Sn,wt,pn,Wn,mr,rr,gr,Kn,An,Zn,vt,$t,_t,En,fr,_n,Tn,D,jn,Rn,hr,gn,Mn,ee,zn,or,jo,co,jr,Ze,po,Hn,fn,zo,qo,uo,sr,Vo,zr,mo,ar,go,yr,br,Uo,Jo,Ws,kr,Lr,Rt,qr,Vr,fo,ho,yo,bo,un,kn,ir,qe,xo,Ir,qn,Yo,Ur,Jr,Pr,xr;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,d=X=>{let Ve=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,_e=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,Tt=X.tools?X.tools.map(yt=>({...yt,chunks:yt.chunks?[...yt.chunks]:void 0})):void 0;return{...X,reasoning:Ve,toolCall:_e,tools:Tt}},p=X=>{t({type:"message",message:d(X)})},g=null,f={current:null},v={current:null},E=!1,x=new Map,C=new Map,k={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=X=>{if(X==null)return null;try{return String(X)}catch{return null}},M=X=>{var Ve,_e,Tt,yt,St;return w((St=(yt=(Tt=(_e=(Ve=X.stepId)!=null?Ve:X.step_id)!=null?_e:X.step)!=null?Tt:X.parentId)!=null?yt:X.flowStepId)!=null?St:X.flow_step_id)},W=X=>{var Ve,_e,Tt,yt,St,et,y;return w((y=(et=(St=(yt=(Tt=(_e=(Ve=X.callId)!=null?Ve:X.call_id)!=null?_e:X.requestId)!=null?Tt:X.request_id)!=null?yt:X.toolCallId)!=null?St:X.tool_call_id)!=null?et:X.stepId)!=null?y:X.step_id)},T=n,G=!1,K=()=>{if(g)return g;let X;return!G&&T?(X=T,G=!0):T&&v.current?X=`${T}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(g),g},J=(X,Ve)=>{k.lastId=Ve,X&&k.byStep.set(X,Ve)},I=(X,Ve)=>{var St;let _e=(St=X.reasoningId)!=null?St:X.id,Tt=M(X);if(_e){let et=String(_e);return J(Tt,et),et}if(Tt){let et=k.byStep.get(Tt);if(et)return k.lastId=et,et}if(k.lastId&&!Ve)return k.lastId;if(!Ve)return null;let yt=`reason-${c()}`;return J(Tt,yt),yt},Q=X=>{let Ve=x.get(X);if(Ve)return Ve;let _e={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return x.set(X,_e),p(_e),_e},Ce=(X,Ve)=>{H.lastId=Ve,X&&H.byCall.set(X,Ve)},re=new Set,Ae=new Map,Ne=new Set,he=new Map,ke=X=>{if(!X)return!1;let Ve=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ve==="emit_artifact_markdown"||Ve==="emit_artifact_component"},Le=(X,Ve)=>{var St;let _e=(St=X.toolId)!=null?St:X.id,Tt=W(X);if(_e){let et=String(_e);return Ce(Tt,et),et}if(Tt){let et=H.byCall.get(Tt);if(et)return H.lastId=et,et}if(H.lastId&&!Ve)return H.lastId;if(!Ve)return null;let yt=`tool-${c()}`;return Ce(Tt,yt),yt},ae=X=>{let Ve=C.get(X);if(Ve)return Ve;let _e={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,_e),p(_e),_e},xe=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ve=Number(X);if(!Number.isNaN(Ve)&&Number.isFinite(Ve))return Ve;let _e=Date.parse(X);if(!Number.isNaN(_e))return _e}return Date.now()},je=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},de=new Map,ie=new Map,Ee=new Map,Be=new Map;function it(X,Ve,_e,Tt){let yt=X.get(Ve);yt||(yt=[],X.set(Ve,yt));let St=0,et=yt.length;for(;St<et;){let se=St+et>>>1;yt[se].seq<_e?St=se+1:et=se}yt.splice(St,0,{seq:_e,text:Tt});let y="";for(let se=0;se<yt.length;se++)y+=yt[se].text;return y}let Et=null,q=(X,Ve)=>{let _e=je(Ve),Tt=ie.get(X.id),yt=dp(Tt,_e);X.rawContent=yt;let St=de.get(X.id),et=Y=>{var pe;let N=(pe=X.content)!=null?pe:"";Y.trim()!==""&&(N.trim().length===0||Y.startsWith(N)||Y.trimStart().startsWith(N.trim()))&&(X.content=Y)},y=()=>{var Y;if(St){let N=(Y=St.close)==null?void 0:Y.call(St);N instanceof Promise&&N.catch(()=>{})}de.delete(X.id),ie.delete(X.id),X.streaming=!1,p(X)};if(!St){et(_e),y();return}let se=Nr(yt);if(se!==null&&se.trim()!==""){et(se),y();return}let P=Y=>{var Ye;let N=typeof Y=="string"?Y:(Ye=Y==null?void 0:Y.text)!=null?Ye:null;if(N!==null&&N.trim()!=="")return N;let pe=St.getExtractedText();return pe!==null&&pe.trim()!==""?pe:_e},S;try{S=St.processChunk(yt)}catch{et(_e),y();return}if(S instanceof Promise){S.then(Y=>{et(P(Y)),y()}).catch(()=>{et(_e),y()});return}et(P(S)),y()},F=null,le=new Map,_=(V=this.config.iterationDisplay)!=null?V:"separate";for(;;){let{done:X,value:Ve}=await s.read();if(X)break;a+=o.decode(Ve,{stream:!0});let _e=a.split(`
5
5
 
6
- `);a=(re=Ge.pop())!=null?re:"";for(let Rt of Ge){let bt=Rt.split(`
7
- `),it="message",ke="";for(let P of bt)P.startsWith("event:")?it=P.replace("event:","").trim():P.startsWith("data:")&&(ke+=P.replace("data:","").trim());if(!ke)continue;let y;try{y=JSON.parse(ke)}catch(P){t({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let ve=it!=="message"?it:(_e=y.type)!=null?_e:"message";if((Z=this.onSSEEvent)==null||Z.call(this,ve,y),this.parseSSEEvent){f.current=m;let P=await this.handleCustomSSEEvent(y,t,f,p,c,v);if(f.current&&f.current!==m&&(m=f.current),P)continue}if(ve==="reason_start"){let P=(ee=L(y,!0))!=null?ee:`reason-${c()}`,S=Q(P);S.reasoning=(kt=S.reasoning)!=null?kt:{id:P,status:"streaming",chunks:[]},S.reasoning.startedAt=(Dt=S.reasoning.startedAt)!=null?Dt:be((ct=y.startedAt)!=null?ct:y.timestamp),S.reasoning.completedAt=void 0,S.reasoning.durationMs=void 0,S.streaming=!0,S.reasoning.status="streaming",p(S)}else if(ve==="reason_delta"||ve==="reason_chunk"){let P=(je=(Jt=L(y,!1))!=null?Jt:L(y,!0))!=null?je:`reason-${c()}`,S=Q(P);S.reasoning=(le=S.reasoning)!=null?le:{id:P,status:"streaming",chunks:[]},S.reasoning.startedAt=(It=S.reasoning.startedAt)!=null?It:be((De=y.startedAt)!=null?De:y.timestamp);let Y=(ot=(rt=(Pt=y.reasoningText)!=null?Pt:y.text)!=null?rt:y.delta)!=null?ot:"";if(Y&&y.hidden!==!0){let N=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(N!==void 0){let pe=lt(Ne,P,N,String(Y));S.reasoning.chunks=[pe]}else S.reasoning.chunks.push(String(Y))}if(S.reasoning.status=y.done?"complete":"streaming",y.done){S.reasoning.completedAt=be((en=y.completedAt)!=null?en:y.timestamp);let N=(Qt=S.reasoning.startedAt)!=null?Qt:Date.now();S.reasoning.durationMs=Math.max(0,((tn=S.reasoning.completedAt)!=null?tn:Date.now())-N),Ne.delete(P)}S.streaming=S.reasoning.status!=="complete",p(S)}else if(ve==="reason_complete"){let P=(We=(_=L(y,!1))!=null?_:L(y,!0))!=null?We:`reason-${c()}`,S=x.get(P);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=be((de=y.completedAt)!=null?de:y.timestamp);let N=(ft=S.reasoning.startedAt)!=null?ft:Date.now();S.reasoning.durationMs=Math.max(0,(($e=S.reasoning.completedAt)!=null?$e:Date.now())-N),S.streaming=!1,Ne.delete(P),p(S)}let Y=M(y);Y&&k.byStep.delete(Y)}else if(ve==="tool_start"){let P=(te=Pe(y,!0))!=null?te:`tool-${c()}`,S=(he=y.toolName)!=null?he:y.name;if(Ie(S)){ne.add(P);continue}let Y=se(P),N=(Fe=Y.toolCall)!=null?Fe:{id:P,status:"pending"};N.name=S!=null?S:N.name,N.status="running",y.args!==void 0?N.args=y.args:y.parameters!==void 0&&(N.args=y.parameters),N.startedAt=(_t=N.startedAt)!=null?_t:be((Ct=y.startedAt)!=null?Ct:y.timestamp),N.completedAt=void 0,N.durationMs=void 0,Y.toolCall=N,Y.streaming=!0;let pe=y.agentContext;(pe||y.executionId)&&(Y.agentMetadata={executionId:(dt=pe==null?void 0:pe.executionId)!=null?dt:y.executionId,iteration:(jt=pe==null?void 0:pe.iteration)!=null?jt:y.iteration}),p(Y)}else if(ve==="tool_chunk"||ve==="tool_delta"){let P=(Ze=(ht=Pe(y,!1))!=null?ht:Pe(y,!0))!=null?Ze:`tool-${c()}`;if(ne.has(P))continue;let S=se(P),Y=(yt=S.toolCall)!=null?yt:{id:P,status:"running"};Y.startedAt=(zt=Y.startedAt)!=null?zt:be((Ue=y.startedAt)!=null?Ue:y.timestamp);let N=(Nn=(Qn=(Jn=y.text)!=null?Jn:y.delta)!=null?Qn:y.message)!=null?Nn:"";N&&(Y.chunks=(et=Y.chunks)!=null?et:[],Y.chunks.push(String(N))),Y.status="running",S.toolCall=Y,S.streaming=!0;let pe=y.agentContext;(pe||y.executionId)&&(S.agentMetadata=(Ar=S.agentMetadata)!=null?Ar:{executionId:(Sr=pe==null?void 0:pe.executionId)!=null?Sr:y.executionId,iteration:(Yn=pe==null?void 0:pe.iteration)!=null?Yn:y.iteration}),p(S)}else if(ve==="tool_complete"){let P=(Fr=(In=Pe(y,!1))!=null?In:Pe(y,!0))!=null?Fr:`tool-${c()}`;if(ne.has(P)){ne.delete(P);continue}let S=se(P),Y=(lr=S.toolCall)!=null?lr:{id:P,status:"running"};Y.status="complete",y.result!==void 0&&(Y.result=y.result),typeof y.duration=="number"&&(Y.duration=y.duration),Y.completedAt=be((er=y.completedAt)!=null?er:y.timestamp);let N=(st=y.duration)!=null?st:y.executionTime;if(typeof N=="number")Y.durationMs=N;else{let at=(Cn=Y.startedAt)!=null?Cn:Date.now();Y.durationMs=Math.max(0,((Fn=Y.completedAt)!=null?Fn:Date.now())-at)}S.toolCall=Y,S.streaming=!1;let pe=y.agentContext;(pe||y.executionId)&&(S.agentMetadata=(wn=S.agentMetadata)!=null?wn:{executionId:(cn=pe==null?void 0:pe.executionId)!=null?cn:y.executionId,iteration:(cr=pe==null?void 0:pe.iteration)!=null?cr:y.iteration}),p(S);let xe=W(y);xe&&R.byCall.delete(xe)}else if(ve==="text_start"){let P=y.partId;if(P!==void 0&&v.current!==null&&P!==v.current){let S=m;S&&(S.streaming=!1,p(S),Tt=S,m=null,A=!0)}P!==void 0&&(v.current=P)}else if(ve==="text_end"){let P=m;P&&(P.streaming=!1,p(P),Tt=P,m=null,A=!0)}else if(ve==="step_chunk"||ve==="step_delta"){let P=y.stepType,S=y.executionType;if(P==="tool"||S==="context")continue;let Y=y.partId;if(Y!==void 0&&v.current!==null&&Y!==v.current){let xe=m;xe&&(xe.streaming=!1,p(xe),Tt=xe,m=null,A=!0)}Y!==void 0&&(v.current=Y);let N=K();Y!==void 0&&!N.partId&&(N.partId=Y);let pe=(dr=(Pn=(dn=(St=y.text)!=null?St:y.delta)!=null?dn:y.content)!=null?Pn:y.chunk)!=null?dr:"";if(pe){let xe=typeof y.seq=="number"?y.seq:void 0,at;xe!==void 0?at=lt(Te,N.id,xe,pe):at=((tr=ae.get(N.id))!=null?tr:"")+pe,N.rawContent=at,ce.has(N.id)||ce.set(N.id,this.createStreamParser());let xt=ce.get(N.id),nn=at.trim().startsWith("{")||at.trim().startsWith("[");if(nn&&ae.set(N.id,at),xt.__isPlainTextParser===!0){xe!==void 0?N.content=at:N.content+=pe,ae.delete(N.id),ce.delete(N.id),N.rawContent=void 0,p(N);continue}let Gt=xt.processChunk(at);if(Gt instanceof Promise)Gt.then(Xe=>{var Xt;let Mt=typeof Xe=="string"?Xe:(Xt=Xe==null?void 0:Xe.text)!=null?Xt:null;if(Mt!==null&&Mt.trim()!=="")N.content=Mt,p(N);else if(!nn&&!at.trim().startsWith("<")){let rn=m;rn&&rn.id===N.id&&(xe!==void 0?rn.content=at:rn.content+=pe,ae.delete(rn.id),ce.delete(rn.id),rn.rawContent=void 0,p(rn))}}).catch(()=>{xe!==void 0?N.content=at:N.content+=pe,ae.delete(N.id),ce.delete(N.id),N.rawContent=void 0,p(N)});else{let Xe=typeof Gt=="string"?Gt:(pr=Gt==null?void 0:Gt.text)!=null?pr:null;Xe!==null&&Xe.trim()!==""?(N.content=Xe,p(N)):!nn&&!at.trim().startsWith("<")&&(xe!==void 0?N.content=at:N.content+=pe,ae.delete(N.id),ce.delete(N.id),N.rawContent=void 0,p(N))}}if(y.isComplete){let xe=(Sn=(Gn=y.result)==null?void 0:Gn.response)!=null?Sn:N.content;if(xe){let at=ae.get(N.id),xt=at!=null?at:ze(xe);N.rawContent=xt;let nn=ce.get(N.id),Yt=null,Gt=!1;if(nn&&(Yt=nn.getExtractedText(),Yt===null&&(Yt=Hr(xt)),Yt===null)){let Xe=nn.processChunk(xt);Xe instanceof Promise?(Gt=!0,Xe.then(Mt=>{var rn;let Xt=typeof Mt=="string"?Mt:(rn=Mt==null?void 0:Mt.text)!=null?rn:null;if(Xt!==null){let Nt=m;Nt&&Nt.id===N.id&&(Nt.content=Xt,Nt.streaming=!1,ce.delete(Nt.id),ae.delete(Nt.id),Te.delete(Nt.id),p(Nt))}})):Yt=typeof Xe=="string"?Xe:(Xn=Xe==null?void 0:Xe.text)!=null?Xn:null}if(!Gt){Yt!==null&&Yt.trim()!==""?N.content=Yt:ae.has(N.id)||(N.content=ze(xe));let Xe=ce.get(N.id);if(Xe){let Mt=(At=Xe.close)==null?void 0:At.call(Xe);Mt instanceof Promise&&Mt.catch(()=>{}),ce.delete(N.id)}ae.delete(N.id),Te.delete(N.id),N.streaming=!1,p(N)}}}}else if(ve==="step_complete"){let P=y.stepType,S=y.executionType;if(P==="tool"||S==="context")continue;if(A){if(m!==null){let at=m;ce.delete(at.id),ae.delete(at.id),Te.delete(at.id),at.streaming!==!1&&(at.streaming=!1,p(at))}let pe=(Ft=y.result)==null?void 0:Ft.response,xe=Tt;xe&&(pe!=null?q(xe,pe):(ce.delete(xe.id),ae.delete(xe.id))),Tt=null;continue}let Y=(Ot=y.result)==null?void 0:Ot.response,N=K();if(Y!=null){let pe=ce.get(N.id),xe=!1,at=!1;if(pe){let xt=pe.getExtractedText(),nn=ae.get(N.id),Yt=nn!=null?nn:ze(Y);if(N.rawContent=Yt,xt!==null&&xt.trim()!=="")N.content=xt,xe=!0;else{let Gt=Hr(Yt);if(Gt!==null)N.content=Gt,xe=!0;else{let Xe=pe.processChunk(Yt);if(Xe instanceof Promise)at=!0,Xe.then(Mt=>{var rn;let Xt=typeof Mt=="string"?Mt:(rn=Mt==null?void 0:Mt.text)!=null?rn:null;if(Xt!==null&&Xt.trim()!==""){let Nt=m;Nt&&Nt.id===N.id&&(Nt.content=Xt,Nt.streaming=!1,ce.delete(Nt.id),ae.delete(Nt.id),Te.delete(Nt.id),p(Nt))}else{let Nt=pe.getExtractedText(),kn=m;kn&&kn.id===N.id&&(Nt!==null&&Nt.trim()!==""?kn.content=Nt:ae.has(kn.id)||(kn.content=ze(Y)),kn.streaming=!1,ce.delete(kn.id),ae.delete(kn.id),Te.delete(kn.id),p(kn))}});else{let Mt=typeof Xe=="string"?Xe:(An=Xe==null?void 0:Xe.text)!=null?An:null;if(Mt!==null&&Mt.trim()!=="")N.content=Mt,xe=!0;else{let Xt=pe.getExtractedText();Xt!==null&&Xt.trim()!==""&&(N.content=Xt,xe=!0)}}}}}if(!at){if(!N.rawContent){let xt=ae.get(N.id);N.rawContent=xt!=null?xt:ze(Y)}if(!xe&&!ae.has(N.id)&&(N.content=ze(Y)),pe){let xt=(ur=pe.close)==null?void 0:ur.call(pe);xt instanceof Promise&&xt.catch(()=>{})}ce.delete(N.id),ae.delete(N.id),Te.delete(N.id),N.streaming=!1,p(N)}}else ce.delete(N.id),ae.delete(N.id),Te.delete(N.id),N.streaming=!1,p(N)}else if(ve==="flow_complete"){let P=(On=y.result)==null?void 0:On.response;if(A){if(m!==null){let S=m;ce.delete(S.id),ae.delete(S.id),Te.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}}else if(P!=null){let S=K(),Y=ae.get(S.id),N=Y!=null?Y:ze(P);S.rawContent=N;let pe=ze(P),xe=ce.get(S.id);if(xe){let nn=Hr(N);if(nn!==null)pe=nn;else{let Yt=xe.processChunk(N);Yt instanceof Promise&&Yt.then(Xe=>{var Xt;let Mt=typeof Xe=="string"?Xe:(Xt=Xe==null?void 0:Xe.text)!=null?Xt:null;Mt!==null&&(S.content=Mt,S.streaming=!1,p(S))});let Gt=xe.getExtractedText();Gt!==null&&(pe=Gt)}}ce.delete(S.id),ae.delete(S.id),Te.delete(S.id);let at=pe!==S.content,xt=S.streaming!==!1;at&&(S.content=pe),S.streaming=!1,(at||xt)&&p(S)}else if(m!==null){let S=m;ce.delete(S.id),ae.delete(S.id),Te.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}t({type:"status",status:"idle"})}else if(ve==="agent_start")F={executionId:y.executionId,agentId:(En=y.agentId)!=null?En:"virtual",agentName:(D=y.agentName)!=null?D:"",status:"running",currentIteration:0,maxTurns:($n=y.maxTurns)!=null?$n:1,startedAt:be(y.startedAt)};else if(ve==="agent_iteration_start"){if(F&&(F.currentIteration=y.iteration),j==="separate"&&y.iteration>1){let P=m;P&&(P.streaming=!1,p(P),ie.set(y.iteration-1,P),m=null)}}else if(ve!=="agent_turn_start"){if(ve==="agent_turn_delta"){if(y.contentType==="text"){let P=K();P.content+=(Wn=y.delta)!=null?Wn:"",P.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId,agentName:F==null?void 0:F.agentName},p(P)}else if(y.contentType==="thinking"){let P=(gr=y.turnId)!=null?gr:`agent-think-${y.iteration}`,S=Q(P);S.reasoning=(gn=S.reasoning)!=null?gn:{id:P,status:"streaming",chunks:[]},S.reasoning.chunks.push((Tn=y.delta)!=null?Tn:""),S.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId},p(S)}else if(y.contentType==="tool_input"){let P=(oe=y.toolCallId)!=null?oe:R.lastId;if(P){let S=C.get(P);S!=null&&S.toolCall&&(S.toolCall.chunks=(_n=S.toolCall.chunks)!=null?_n:[],S.toolCall.chunks.push((Or=y.delta)!=null?Or:""),p(S))}}}else if(ve==="agent_turn_complete"){let P=y.turnId;if(P){let S=x.get(P);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=be(y.completedAt);let Y=(lo=S.reasoning.startedAt)!=null?lo:Date.now();S.reasoning.durationMs=Math.max(0,(($r=S.reasoning.completedAt)!=null?$r:Date.now())-Y),S.streaming=!1,p(S)}}}else if(ve==="agent_tool_start"){let P=(Qe=y.toolCallId)!=null?Qe:`agent-tool-${c()}`;we(W(y),P);let S=se(P),Y=(co=S.toolCall)!=null?co:{id:P,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};Y.name=(mn=(Rn=y.toolName)!=null?Rn:y.name)!=null?mn:Y.name,Y.status="running",y.parameters!==void 0&&(Y.args=y.parameters),Y.startedAt=be(($o=y.startedAt)!=null?$o:y.timestamp),S.toolCall=Y,S.streaming=!0,S.agentMetadata={executionId:y.executionId,iteration:y.iteration},p(S)}else if(ve==="agent_tool_delta"){let P=(_o=y.toolCallId)!=null?_o:R.lastId;if(P){let S=(po=C.get(P))!=null?po:se(P);S.toolCall&&(S.toolCall.chunks=(nr=S.toolCall.chunks)!=null?nr:[],S.toolCall.chunks.push((jo=y.delta)!=null?jo:""),S.toolCall.status="running",S.streaming=!0,p(S))}}else if(ve==="agent_tool_complete"){let P=(_r=y.toolCallId)!=null?_r:R.lastId;if(P){let S=(jr=C.get(P))!=null?jr:se(P);if(S.toolCall){S.toolCall.status="complete",y.result!==void 0&&(S.toolCall.result=y.result),typeof y.executionTime=="number"&&(S.toolCall.durationMs=y.executionTime),S.toolCall.completedAt=be((rr=y.completedAt)!=null?rr:y.timestamp),S.streaming=!1,p(S);let Y=W(y);Y&&R.byCall.delete(Y)}}}else if(ve!=="agent_iteration_complete"){if(ve==="agent_reflection"||ve==="agent_reflect"){let P=`agent-reflection-${y.executionId}-${y.iteration}`,S={id:P,role:"assistant",content:(uo=y.reflection)!=null?uo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:P,status:"complete",chunks:[(mr=y.reflection)!=null?mr:""]},agentMetadata:{executionId:y.executionId,iteration:y.iteration}};p(S)}else if(ve==="agent_complete"){F&&(F.status=y.success?"complete":"error",F.completedAt=be(y.completedAt),F.stopReason=y.stopReason);let P=m;P&&(P.streaming=!1,p(P)),t({type:"status",status:"idle"})}else if(ve==="agent_error"){let P=typeof y.error=="string"?y.error:(zo=(fr=y.error)==null?void 0:fr.message)!=null?zo:"Agent execution error";y.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",P):t({type:"error",error:new Error(P)})}else if(ve!=="agent_ping")if(ve==="agent_approval_start"){let P=(qo=y.approvalId)!=null?qo:`approval-${c()}`,S={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:(ks=F==null?void 0:F.agentId)!=null?ks:"virtual",executionId:(Tr=(Er=y.executionId)!=null?Er:F==null?void 0:F.executionId)!=null?Tr:"",toolName:(Wt=y.toolName)!=null?Wt:"",toolType:y.toolType,description:(qr=y.description)!=null?qr:`Execute ${(zr=y.toolName)!=null?zr:"tool"}`,parameters:y.parameters}};p(S)}else if(ve==="step_await"&&y.awaitReason==="approval_required"){let P=(go=y.approvalId)!=null?go:`approval-${c()}`,S={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:(mo=F==null?void 0:F.agentId)!=null?mo:"virtual",executionId:(ho=(fo=y.executionId)!=null?fo:F==null?void 0:F.executionId)!=null?ho:"",toolName:(pn=y.toolName)!=null?pn:"",toolType:y.toolType,description:(or=y.description)!=null?or:`Execute ${(Mn=y.toolName)!=null?Mn:"tool"}`,parameters:y.parameters}};p(S)}else if(ve==="agent_approval_complete"){let P=y.approvalId;if(P){let Y={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:(Ve=y.decision)!=null?Ve:"approved",agentId:(yo=F==null?void 0:F.agentId)!=null?yo:"virtual",executionId:(jn=(Mr=y.executionId)!=null?Mr:F==null?void 0:F.executionId)!=null?jn:"",toolName:(Uo=y.toolName)!=null?Uo:"",description:(Ur=y.description)!=null?Ur:"",resolvedAt:Date.now()}};p(Y)}}else if(ve==="artifact_start"||ve==="artifact_delta"||ve==="artifact_update"||ve==="artifact_complete"){if(ve==="artifact_start"){let P=y.artifactType,S=String(y.id),Y=typeof y.title=="string"?y.title:void 0;if(t({type:"artifact_start",id:S,artifactType:P,title:Y,component:typeof y.component=="string"?y.component:void 0}),fe.set(S,{markdown:"",title:Y}),!Oe.has(S)){Oe.add(S);let N={id:`artifact-ref-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:S,title:Y,artifactType:P,status:"streaming"}})};Ee.set(S,N),p(N)}}else if(ve==="artifact_delta"){let P=String(y.id),S=typeof y.delta=="string"?y.delta:String((Vr=y.delta)!=null?Vr:"");t({type:"artifact_delta",id:P,artDelta:S});let Y=fe.get(P);Y&&(Y.markdown+=S)}else if(ve==="artifact_update"){let P=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};t({type:"artifact_update",id:String(y.id),props:P,component:typeof y.component=="string"?y.component:void 0})}else if(ve==="artifact_complete"){let P=String(y.id);t({type:"artifact_complete",id:P});let S=Ee.get(P);if(S){S.streaming=!1;try{let Y=JSON.parse((kr=S.rawContent)!=null?kr:"{}");if(Y.props){Y.props.status="complete";let N=fe.get(P);N!=null&&N.markdown&&(Y.props.markdown=N.markdown)}S.rawContent=JSON.stringify(Y)}catch{}fe.delete(P),p(S),Ee.delete(P)}}}else if(ve==="transcript_insert"){let P=y.message;if(!P||typeof P!="object")continue;let S=String((hr=P.id)!=null?hr:`msg-${c()}`),Y=P.role,pe={id:S,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(p(pe),pe.rawContent)try{let xe=JSON.parse(pe.rawContent),at=(Vo=xe==null?void 0:xe.props)==null?void 0:Vo.artifactId;typeof at=="string"&&Oe.add(at)}catch{}m=null,f.current=null,ce.delete(S),ae.delete(S),Te.delete(S)}else ve==="error"&&y.error&&t({type:"error",error:y.error instanceof Error?y.error:new Error(String(y.error))})}}}}}};function Xd(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Eo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Kr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var ts="[Image]";function Kd(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Zd(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Qd(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function ep(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function Ns(e){return{type:"text",text:e}}function tp(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 np(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 rp(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 cc=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],op=["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"],ar=[...cc,...op];function sp(e){return cc.includes(e)||e.startsWith("image/")}function ns(e){return sp(e.type)}async function dc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;ns(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 pc(e,r=ar,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 ap(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function uc(e,r){let t=ap(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 rs=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var os=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 d=0;d<a.length;d++)i+=a[d]*a[d];let u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var To=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 os;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let d=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((m,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let v=!1,A=C=>{v||(v=!0,clearTimeout(x),f(new Error(C)))},x=setTimeout(()=>A("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(x),m())},{once:!0}),this.ws.addEventListener("error",()=>{A("WebSocket connection failed to "+d+"."+p)},{once:!0}),this.ws.addEventListener("close",C=>{if(!C.wasClean&&!v){let k=C.code!==1006?` (code ${C.code})`:"";A("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new rs(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(m=>m("processing")),this.processingStartCallbacks.forEach(m=>m());let d=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:d});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Br=class{constructor(r={}){this.config=r;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Zr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new To(e.runtype);case"browser":if(!Br.isSupported())throw new Error("Browser speech recognition not supported");return new Br(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Fs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Zr({type:"runtype",runtype:e.runtype});if(Br.isSupported())return Zr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ss(e){try{return Fs(e),!0}catch{return!1}}var Mo=class e{constructor(r={},t){this.config=r;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Xr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return ss((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=Zr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var d,p,m,f,v,A;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((d=c.transcript)!=null&&d.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((m=c.text)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=c.text)!=null&&f.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let x=(A=this.pendingVoiceAssistantMessageId)!=null?A:(v=[...this.messages].reverse().find(C=>C.role==="assistant"))==null?void 0:v.id;x&&this.ttsSpokenMessageIds.add(x)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var d,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(d=this.callbacks).onVoiceStatusChanged)==null||p.call(d,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,d;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(d=r.browser)==null?void 0:d.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Xr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:d}=r,m={id:a!=null?a:t==="user"?Eo():t==="assistant"?Kr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...d!==void 0&&{voiceProcessing:d}};return this.upsertMessage(m),m}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:d,streaming:p=!1}=n,f={id:u!=null?u:s==="user"?Eo():s==="assistant"?Kr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(f)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,d,p,m,f;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=Eo(),o=Kr(),a={id:s,role:"user",content:n||ts,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let A=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!A){let x={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(x)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,A||(v instanceof Error?(p=(d=this.callbacks).onError)==null||p.call(d,v):(f=(m=this.callbacks).onError)==null||f.call(m,new Error(String(v))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Kr();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 d={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(d),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,d;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let m=null;if(p instanceof Response){if(!p.ok){let f=await p.json().catch(()=>null);throw new Error((u=f==null?void 0:f.error)!=null?u:`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(d=(c=this.callbacks).onError)==null||d.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Kn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as ip from"lucide";var ge=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=ip[s];return o?lp(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 lp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,d])=>{c!=="stroke"&&u.setAttribute(c,String(d))}),s.appendChild(u)}}}),s}var as={allowedTypes:ar,maxFileSize:10*1024*1024,maxFiles:4};function cp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function dp(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 Qr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:as.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:as.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:as.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:as.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let d=pc(c,this.config.allowedTypes,this.config.maxFileSize);if(!d.valid){let p=(s=d.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await dc(c),m=ns(c)?URL.createObjectURL(c):null,f={id:cp(),file:c,previewUrl:m,contentPart:p};this.attachments.push(f),this.renderPreview(f)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=ns(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=dp(r.file.type),u=ge(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=uc(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=ge("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var gc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ko(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];gc(o)&&gc(s)?t[n]=ko(o,s):t[n]=s}return t}var Bn="min(440px, calc(100vw - 24px))",Os="440px",Lt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Bn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function mc(e,r){if(!(!e&&!r))return e?r?ko(e,r):e:r}function $s(e){var r,t,n,s,o,a,i,u,c,d,p,m,f,v,A,x,C,k,R,w,M;return e?{...Lt,...e,theme:mc(Lt.theme,e.theme),darkTheme:mc(Lt.darkTheme,e.darkTheme),launcher:{...Lt.launcher,...e.launcher,dock:{...(r=Lt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Lt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Lt.copy,...e.copy},sendButton:{...Lt.sendButton,...e.sendButton},statusIndicator:{...Lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Lt.voiceRecognition,...e.voiceRecognition},features:(()=>{var Q,we,ne,Ee;let W=(Q=Lt.features)==null?void 0:Q.artifacts,E=(we=e.features)==null?void 0:we.artifacts,G=(ne=Lt.features)==null?void 0:ne.scrollToBottom,K=(Ee=e.features)==null?void 0:Ee.scrollToBottom,J=W===void 0&&E===void 0?void 0:{...W,...E,layout:{...W==null?void 0:W.layout,...E==null?void 0:E.layout}},L=G===void 0&&K===void 0?void 0:{...G,...K};return{...Lt.features,...e.features,...L!==void 0?{scrollToBottom:L}:{},...J!==void 0?{artifacts:J}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Lt.suggestionChips,suggestionChipsConfig:{...Lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Lt.layout,...e.layout,header:{...(a=Lt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=Lt.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(d=Lt.layout)==null?void 0:d.messages)==null?void 0:p.avatar,...(f=(m=e.layout)==null?void 0:m.messages)==null?void 0:f.avatar},timestamp:{...(A=(v=Lt.layout)==null?void 0:v.messages)==null?void 0:A.timestamp,...(C=(x=e.layout)==null?void 0:x.messages)==null?void 0:C.timestamp}},slots:{...(k=Lt.layout)==null?void 0:k.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...Lt.markdown,...e.markdown,options:{...(w=Lt.markdown)==null?void 0:w.options,...(M=e.markdown)==null?void 0:M.options}},messageActions:{...Lt.messageActions,...e.messageActions}}:Lt}var fc={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"}},hc={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"}},yc={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:Bn,maxWidth:Os,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 Lo(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."))?Lo(e,n):n}function _s(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=Lo(e,a);u!==void 0&&(r[i]={path:i,value:u,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function bc(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 xc(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]=xc(o,s):t[n]=s}return t}function pp(e,r){return r?xc(e,r):e}function Io(e,r={}){var s,o,a,i,u,c,d,p,m,f,v,A,x;let t={palette:fc,semantic:hc,components:yc},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(d=e==null?void 0:e.semantic)==null?void 0:d.colors,interactive:{...t.semantic.colors.interactive,...(m=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:m.interactive},feedback:{...t.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(A=e==null?void 0:e.semantic)==null?void 0:A.spacing},typography:{...t.semantic.typography,...(x=e==null?void 0:e.semantic)==null?void 0:x.typography}},components:pp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let C=bc(n);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(k=>k.message).join(", ")}`)}if(r.plugins)for(let C of r.plugins)n=C.transform(n);return n}function js(e){var v,A,x,C,k,R,w,M,W,E,G,K,J,L,Q,we,ne,Ee,Oe,fe,Ie,Pe,se,be,ze,ce,ae,Te,Ne,lt,Tt,q,F,ie,j,U,re,_e,Z,ee,kt,ct,Dt,Jt,je,le,De,It,Pt,rt,ot,en,Qt,tn,_,We,de,ft,$e,te,he,Fe,Ct,_t,dt,jt,ht,Ze,yt,Ue,zt,Jn,Qn,Nn,et,Sr,Yn,Ar,In,Fr,lr,er,st,Cn,Fn,cn,cr,wn,St,dn,Pn,dr,tr,pr,Gn,Sn,Xn,At,Ft,Ot,An,ur,On,En,D,$n,Wn,gr,gn,Tn;let r=_s(e),t={};for(let[oe,_n]of Object.entries(r)){let Or=oe.replace(/\./g,"-");t[`--persona-${Or}`]=_n.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(A=t["--persona-semantic-colors-secondary"])!=null?A:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(x=t["--persona-semantic-colors-accent"])!=null?x: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"]=(k=t["--persona-semantic-colors-background"])!=null?k: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"]=(M=t["--persona-semantic-colors-text-muted"])!=null?M:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(E=t["--persona-semantic-colors-border"])!=null?E:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(G=t["--persona-semantic-colors-divider"])!=null?G:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(K=t["--persona-components-voice-recording-indicator"])!=null?K:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(J=t["--persona-components-voice-recording-background"])!=null?J:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(L=t["--persona-components-voice-processing-icon"])!=null?L:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(Q=t["--persona-components-voice-speaking-icon"])!=null?Q:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(we=t["--persona-components-approval-requested-background"])!=null?we:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ne=t["--persona-components-approval-requested-border"])!=null?ne:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ee=t["--persona-components-approval-requested-text"])!=null?Ee:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(Oe=t["--persona-components-approval-approve-background"])!=null?Oe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(fe=t["--persona-components-approval-deny-background"])!=null?fe:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Ie=t["--persona-components-attachment-image-background"])!=null?Ie:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Pe=t["--persona-components-attachment-image-border"])!=null?Pe:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(se=t["--persona-semantic-typography-fontFamily"])!=null?se:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(be=t["--persona-semantic-typography-fontSize"])!=null?be:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ze=t["--persona-semantic-typography-fontWeight"])!=null?ze:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ce=t["--persona-semantic-typography-lineHeight"])!=null?ce: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"]=(ae=t["--persona-palette-radius-sm"])!=null?ae:"0.125rem",t["--persona-radius-md"]=(Te=t["--persona-palette-radius-md"])!=null?Te:"0.375rem",t["--persona-radius-lg"]=(Ne=t["--persona-palette-radius-lg"])!=null?Ne:"0.5rem",t["--persona-radius-xl"]=(lt=t["--persona-palette-radius-xl"])!=null?lt:"0.75rem",t["--persona-radius-full"]=(Tt=t["--persona-palette-radius-full"])!=null?Tt:"9999px",t["--persona-launcher-radius"]=(F=(q=t["--persona-components-launcher-borderRadius"])!=null?q:t["--persona-palette-radius-full"])!=null?F:"9999px",t["--persona-launcher-bg"]=(ie=t["--persona-components-launcher-background"])!=null?ie:t["--persona-primary"],t["--persona-launcher-fg"]=(j=t["--persona-components-launcher-foreground"])!=null?j:t["--persona-text-inverse"],t["--persona-launcher-border"]=(U=t["--persona-components-launcher-border"])!=null?U:t["--persona-border"],t["--persona-button-primary-bg"]=(re=t["--persona-components-button-primary-background"])!=null?re:t["--persona-primary"],t["--persona-button-primary-fg"]=(_e=t["--persona-components-button-primary-foreground"])!=null?_e:t["--persona-text-inverse"],t["--persona-button-radius"]=(ee=(Z=t["--persona-components-button-primary-borderRadius"])!=null?Z:t["--persona-palette-radius-full"])!=null?ee:"9999px",t["--persona-panel-radius"]=(ct=(kt=t["--persona-components-panel-borderRadius"])!=null?kt:t["--persona-radius-xl"])!=null?ct:"0.75rem",t["--persona-panel-border"]=(Dt=t["--persona-components-panel-border"])!=null?Dt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(je=(Jt=t["--persona-components-panel-shadow"])!=null?Jt:t["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(De=(le=t["--persona-components-input-borderRadius"])!=null?le:t["--persona-radius-lg"])!=null?De:"0.5rem",t["--persona-message-user-radius"]=(Pt=(It=t["--persona-components-message-user-borderRadius"])!=null?It:t["--persona-radius-lg"])!=null?Pt:"0.5rem",t["--persona-message-assistant-radius"]=(ot=(rt=t["--persona-components-message-assistant-borderRadius"])!=null?rt:t["--persona-radius-lg"])!=null?ot:"0.5rem",t["--persona-header-bg"]=(en=t["--persona-components-header-background"])!=null?en:t["--persona-surface"],t["--persona-header-border"]=(Qt=t["--persona-components-header-border"])!=null?Qt:t["--persona-divider"],t["--persona-header-icon-bg"]=(tn=t["--persona-components-header-iconBackground"])!=null?tn:t["--persona-primary"],t["--persona-header-icon-fg"]=(_=t["--persona-components-header-iconForeground"])!=null?_:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(We=t["--persona-components-header-titleForeground"])!=null?We:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(de=t["--persona-components-header-subtitleForeground"])!=null?de:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ft=t["--persona-components-header-actionIconForeground"])!=null?ft:t["--persona-muted"];let n=($e=e.components)==null?void 0:$e.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(te=t["--persona-components-input-background"])!=null?te:t["--persona-surface"],t["--persona-input-placeholder"]=(he=t["--persona-components-input-placeholder"])!=null?he:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Fe=t["--persona-components-message-user-background"])!=null?Fe:t["--persona-accent"],t["--persona-message-user-text"]=(Ct=t["--persona-components-message-user-text"])!=null?Ct:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(_t=t["--persona-components-message-user-shadow"])!=null?_t:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(dt=t["--persona-components-message-assistant-background"])!=null?dt:t["--persona-surface"],t["--persona-message-assistant-text"]=(jt=t["--persona-components-message-assistant-text"])!=null?jt:t["--persona-text"],t["--persona-message-assistant-border"]=(ht=t["--persona-components-message-assistant-border"])!=null?ht:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Ze=t["--persona-components-message-assistant-shadow"])!=null?Ze:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Ue=(yt=t["--persona-components-scrollToBottom-background"])!=null?yt:t["--persona-button-primary-bg"])!=null?Ue:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Jn=(zt=t["--persona-components-scrollToBottom-foreground"])!=null?zt:t["--persona-button-primary-fg"])!=null?Jn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Qn=t["--persona-components-scrollToBottom-border"])!=null?Qn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Nn=t["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",t["--persona-scroll-to-bottom-radius"]=(Yn=(Sr=(et=t["--persona-components-scrollToBottom-borderRadius"])!=null?et:t["--persona-button-radius"])!=null?Sr:t["--persona-radius-full"])!=null?Yn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(In=(Ar=t["--persona-components-scrollToBottom-shadow"])!=null?Ar:t["--persona-palette-shadows-sm"])!=null?In:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Fr=t["--persona-components-scrollToBottom-padding"])!=null?Fr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(lr=t["--persona-components-scrollToBottom-gap"])!=null?lr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(st=(er=t["--persona-components-scrollToBottom-fontSize"])!=null?er:t["--persona-palette-typography-fontSize-sm"])!=null?st:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Cn=t["--persona-components-scrollToBottom-iconSize"])!=null?Cn:"14px",t["--persona-tool-bubble-shadow"]=(Fn=t["--persona-components-toolBubble-shadow"])!=null?Fn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(cn=t["--persona-components-reasoningBubble-shadow"])!=null?cn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(cr=t["--persona-components-composer-shadow"])!=null?cr:"none",t["--persona-md-inline-code-bg"]=(wn=t["--persona-components-markdown-inlineCode-background"])!=null?wn:t["--persona-container"],t["--persona-md-inline-code-color"]=(St=t["--persona-components-markdown-inlineCode-foreground"])!=null?St:t["--persona-text"],t["--persona-md-link-color"]=(Pn=(dn=t["--persona-components-markdown-link-foreground"])!=null?dn:t["--persona-accent"])!=null?Pn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(dr=t["--persona-components-markdown-codeBlock-background"])!=null?dr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(tr=t["--persona-components-markdown-codeBlock-borderColor"])!=null?tr:t["--persona-border"],t["--persona-md-code-block-text-color"]=(pr=t["--persona-components-markdown-codeBlock-textColor"])!=null?pr:"inherit",t["--persona-md-table-header-bg"]=(Gn=t["--persona-components-markdown-table-headerBackground"])!=null?Gn:t["--persona-container"],t["--persona-md-table-border-color"]=(Sn=t["--persona-components-markdown-table-borderColor"])!=null?Sn:t["--persona-border"],t["--persona-md-hr-color"]=(Xn=t["--persona-components-markdown-hr-color"])!=null?Xn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(At=t["--persona-components-markdown-blockquote-borderColor"])!=null?At:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Ft=t["--persona-components-markdown-blockquote-background"])!=null?Ft:"transparent",t["--persona-md-blockquote-text-color"]=(Ot=t["--persona-components-markdown-blockquote-textColor"])!=null?Ot:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(An=t["--persona-components-collapsibleWidget-container"])!=null?An:t["--persona-surface"],t["--cw-surface"]=(ur=t["--persona-components-collapsibleWidget-surface"])!=null?ur:t["--persona-surface"],t["--cw-border"]=(On=t["--persona-components-collapsibleWidget-border"])!=null?On:t["--persona-border"],t["--persona-message-border"]=(En=t["--persona-components-message-border"])!=null?En:t["--persona-border"];let c=e.components,d=c==null?void 0:c.iconButton;d&&(d.background&&(t["--persona-icon-btn-bg"]=d.background),d.border&&(t["--persona-icon-btn-border"]=d.border),d.color&&(t["--persona-icon-btn-color"]=d.color),d.padding&&(t["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(t["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(t["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(t["--persona-icon-btn-active-border"]=d.activeBorder));let p=c==null?void 0:c.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.gap));let m=c==null?void 0:c.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let f=c==null?void 0:c.artifact;if(f!=null&&f.toolbar){let oe=f.toolbar;oe.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=oe.iconHoverColor),oe.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=oe.iconHoverBackground),oe.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=oe.iconPadding),oe.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=oe.iconBorderRadius),oe.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=oe.iconBorder),oe.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=oe.toggleGroupGap),oe.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=oe.toggleBorderRadius),oe.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=oe.copyBackground),oe.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=oe.copyBorder),oe.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=oe.copyColor),oe.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=oe.copyBorderRadius),oe.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=oe.copyPadding),oe.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=oe.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:oe.copyMenuBackground),oe.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=oe.copyMenuBorder,t["--persona-dropdown-border"]=($n=t["--persona-dropdown-border"])!=null?$n:oe.copyMenuBorder),oe.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=oe.copyMenuShadow,t["--persona-dropdown-shadow"]=(Wn=t["--persona-dropdown-shadow"])!=null?Wn:oe.copyMenuShadow),oe.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=oe.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(gr=t["--persona-dropdown-radius"])!=null?gr:oe.copyMenuBorderRadius),oe.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=oe.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:oe.copyMenuItemHoverBackground),oe.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=oe.iconBackground),oe.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=oe.toolbarBorder)}if(f!=null&&f.tab){let oe=f.tab;oe.background&&(t["--persona-artifact-tab-bg"]=oe.background),oe.activeBackground&&(t["--persona-artifact-tab-active-bg"]=oe.activeBackground),oe.activeBorder&&(t["--persona-artifact-tab-active-border"]=oe.activeBorder),oe.borderRadius&&(t["--persona-artifact-tab-radius"]=oe.borderRadius),oe.textColor&&(t["--persona-artifact-tab-color"]=oe.textColor),oe.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=oe.hoverBackground),oe.listBackground&&(t["--persona-artifact-tab-list-bg"]=oe.listBackground),oe.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=oe.listBorderColor),oe.listPadding&&(t["--persona-artifact-tab-list-padding"]=oe.listPadding)}if(f!=null&&f.pane){let oe=f.pane;if(oe.toolbarBackground){let _n=(Tn=Lo(e,oe.toolbarBackground))!=null?Tn:oe.toolbarBackground;t["--persona-artifact-toolbar-bg"]=_n}}return t}var up={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 gp={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"}}},vc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},is=()=>{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"},mp=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":is()},Cc=e=>mp(e),fp=e=>Io(e),hp=e=>{var t;let r=Io(void 0,{validate:!1});return Io({...e,palette:{...r.palette,colors:{...gp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},ls=e=>{let r=Cc(e),t=vc(e==null?void 0:e.theme),n=vc(e==null?void 0:e.darkTheme);return r==="dark"?hp(ko(t!=null?t:{},n!=null?n:{})):fp(t)},yp=e=>js(e),Dr=(e,r)=>{var o;let t=ls(r),n=yp(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)},zs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(is())});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(is());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 bp}from"idiomorph";var wc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;bp.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 Sc(e,r){var t,n,s,o,a,i,u,c,d,p,m,f,v,A,x,C,k,R,w,M,W,E,G,K,J,L,Q;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(d=(c=e.llmContent)==null?void 0:c.length)!=null?d:0,(m=(p=e.approval)==null?void 0:p.status)!=null?m:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(C=(x=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:x.length)!=null?C:0,(M=(w=(R=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?M:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(E=e.toolCall)!=null&&E.args?JSON.stringify(e.toolCall.args).length:0,(J=(K=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:K.length)!=null?J:0,(Q=(L=e.contentParts)==null?void 0:L.length)!=null?Q:0,r].join("\0")}function Ac(){return new Map}function Ec(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Tc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Mc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function cs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Po(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wo(e,r){return Po(e)-e.scrollTop<=r}function ds(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,d=t-n;return a||Math.abs(d)<o?{action:"none",delta:d,nextLastScrollTop:t}:!r&&s&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:t}:r&&i&&d<0?{action:"pause",delta:d,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:d,nextLastScrollTop:t}:{action:"none",delta:d,nextLastScrollTop:t}}function ps(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 ln={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},xn=1e5,br=xn+1;function qs(e,r=xn){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 Ro=0,xr=null;function Us(e=document){var t;if(Ro++,Ro===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;xr={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,Ro=Math.max(0,Ro-1),Ro===0&&xr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=xr.originalOverflow,s.style.position=xr.originalPosition,s.style.top=xr.originalTop,s.style.width=xr.originalWidth,o.scrollTo(0,xr.scrollY),xr=null}}}var us={side:"right",width:"420px",animate:!0,reveal:"resize"},Zt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Un=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:us.side,width:(s=r==null?void 0:r.width)!=null?s:us.width,animate:(o=r==null?void 0:r.animate)!=null?o:us.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:us.reveal}};var Vn={"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 Ho=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
6
+ `);a=(oe=_e.pop())!=null?oe:"";for(let Tt of _e){let yt=Tt.split(`
7
+ `),St="message",et="";for(let P of yt)P.startsWith("event:")?St=P.replace("event:","").trim():P.startsWith("data:")&&(et+=P.replace("data:","").trim());if(!et)continue;let y;try{y=JSON.parse(et)}catch(P){t({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let se=St!=="message"?St:(Oe=y.type)!=null?Oe:"message";if((Z=this.onSSEEvent)==null||Z.call(this,se,y),this.parseSSEEvent){f.current=g;let P=await this.handleCustomSSEEvent(y,t,f,p,c,v);if(f.current&&f.current!==g&&(g=f.current),P)continue}if(se==="reason_start"){let P=(te=I(y,!0))!=null?te:`reason-${c()}`,S=Q(P);S.reasoning=(kt=S.reasoning)!=null?kt:{id:P,status:"streaming",chunks:[]},S.reasoning.startedAt=(Nt=S.reasoning.startedAt)!=null?Nt:xe((lt=y.startedAt)!=null?lt:y.timestamp),S.reasoning.completedAt=void 0,S.reasoning.durationMs=void 0,S.streaming=!0,S.reasoning.status="streaming",p(S)}else if(se==="reason_delta"||se==="reason_chunk"){let P=($e=(Xt=I(y,!1))!=null?Xt:I(y,!0))!=null?$e:`reason-${c()}`,S=Q(P);S.reasoning=(ce=S.reasoning)!=null?ce:{id:P,status:"streaming",chunks:[]},S.reasoning.startedAt=(Pt=S.reasoning.startedAt)!=null?Pt:xe((He=y.startedAt)!=null?He:y.timestamp);let Y=(st=(ot=(Wt=y.reasoningText)!=null?Wt:y.text)!=null?ot:y.delta)!=null?st:"";if(Y&&y.hidden!==!0){let N=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(N!==void 0){let pe=it(Be,P,N,String(Y));S.reasoning.chunks=[pe]}else S.reasoning.chunks.push(String(Y))}if(S.reasoning.status=y.done?"complete":"streaming",y.done){S.reasoning.completedAt=xe((rn=y.completedAt)!=null?rn:y.timestamp);let N=(tn=S.reasoning.startedAt)!=null?tn:Date.now();S.reasoning.durationMs=Math.max(0,((on=S.reasoning.completedAt)!=null?on:Date.now())-N),Be.delete(P)}S.streaming=S.reasoning.status!=="complete",p(S)}else if(se==="reason_complete"){let P=(Ie=(j=I(y,!1))!=null?j:I(y,!0))!=null?Ie:`reason-${c()}`,S=x.get(P);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=xe((ue=y.completedAt)!=null?ue:y.timestamp);let N=(gt=S.reasoning.startedAt)!=null?gt:Date.now();S.reasoning.durationMs=Math.max(0,((Fe=S.reasoning.completedAt)!=null?Fe:Date.now())-N),S.streaming=!1,Be.delete(P),p(S)}let Y=M(y);Y&&k.byStep.delete(Y)}else if(se==="tool_start"){let P=(ne=Le(y,!0))!=null?ne:`tool-${c()}`,S=(ye=y.toolName)!=null?ye:y.name;if(ke(S)){re.add(P);continue}let Y=ae(P),N=(De=Y.toolCall)!=null?De:{id:P,status:"pending"};N.name=S!=null?S:N.name,N.status="running",y.args!==void 0?N.args=y.args:y.parameters!==void 0&&(N.args=y.parameters),N.startedAt=(zt=N.startedAt)!=null?zt:xe((xt=y.startedAt)!=null?xt:y.timestamp),N.completedAt=void 0,N.durationMs=void 0,Y.toolCall=N,Y.streaming=!0;let pe=y.agentContext;(pe||y.executionId)&&(Y.agentMetadata={executionId:(ct=pe==null?void 0:pe.executionId)!=null?ct:y.executionId,iteration:(qt=pe==null?void 0:pe.iteration)!=null?qt:y.iteration}),p(Y)}else if(se==="tool_chunk"||se==="tool_delta"){let P=(Ke=(ft=Le(y,!1))!=null?ft:Le(y,!0))!=null?Ke:`tool-${c()}`;if(re.has(P))continue;let S=ae(P),Y=(ht=S.toolCall)!=null?ht:{id:P,status:"running"};Y.startedAt=(Vt=Y.startedAt)!=null?Vt:xe((We=y.startedAt)!=null?We:y.timestamp);let N=(On=(tr=(Gn=y.text)!=null?Gn:y.delta)!=null?tr:y.message)!=null?On:"";N&&(Y.chunks=(Qe=Y.chunks)!=null?Qe:[],Y.chunks.push(String(N))),Y.status="running",S.toolCall=Y,S.streaming=!0;let pe=y.agentContext;(pe||y.executionId)&&(S.agentMetadata=(Mr=S.agentMetadata)!=null?Mr:{executionId:(Tr=pe==null?void 0:pe.executionId)!=null?Tr:y.executionId,iteration:(Xn=pe==null?void 0:pe.iteration)!=null?Xn:y.iteration}),p(S)}else if(se==="tool_complete"){let P=(_r=(Pn=Le(y,!1))!=null?Pn:Le(y,!0))!=null?_r:`tool-${c()}`;if(re.has(P)){re.delete(P);continue}let S=ae(P),Y=(pr=S.toolCall)!=null?pr:{id:P,status:"running"};Y.status="complete",y.result!==void 0&&(Y.result=y.result),typeof y.duration=="number"&&(Y.duration=y.duration),Y.completedAt=xe((nr=y.completedAt)!=null?nr:y.timestamp);let N=(at=y.duration)!=null?at:y.executionTime;if(typeof N=="number")Y.durationMs=N;else{let tt=(wn=Y.startedAt)!=null?wn:Date.now();Y.durationMs=Math.max(0,(($n=Y.completedAt)!=null?$n:Date.now())-tt)}S.toolCall=Y,S.streaming=!1;let pe=y.agentContext;(pe||y.executionId)&&(S.agentMetadata=(Sn=S.agentMetadata)!=null?Sn:{executionId:(dn=pe==null?void 0:pe.executionId)!=null?dn:y.executionId,iteration:(ur=pe==null?void 0:pe.iteration)!=null?ur:y.iteration}),p(S);let Ye=W(y);Ye&&H.byCall.delete(Ye)}else if(se==="text_start"){let P=y.partId;if(P!==void 0&&v.current!==null&&P!==v.current){let S=g;S&&(S.streaming=!1,p(S),Et=S,g=null,E=!0)}P!==void 0&&(v.current=P)}else if(se==="text_end"){let P=g;P&&(P.streaming=!1,p(P),Et=P,g=null,E=!0)}else if(se==="step_chunk"||se==="step_delta"){let P=y.stepType,S=y.executionType;if(P==="tool"||S==="context")continue;let Y=y.partId;if(Y!==void 0&&v.current!==null&&Y!==v.current){let Ye=g;Ye&&(Ye.streaming=!1,p(Ye),Et=Ye,g=null,E=!0)}Y!==void 0&&(v.current=Y);let N=K();Y!==void 0&&!N.partId&&(N.partId=Y);let pe=(mr=(Wn=(pn=(wt=y.text)!=null?wt:y.delta)!=null?pn:y.content)!=null?Wn:y.chunk)!=null?mr:"";if(pe){let Ye=typeof y.seq=="number"?y.seq:void 0,tt;Ye!==void 0?tt=it(Ee,N.id,Ye,pe):tt=((rr=ie.get(N.id))!=null?rr:"")+pe,N.rawContent=tt,de.has(N.id)||de.set(N.id,this.createStreamParser());let Ht=de.get(N.id),nn=tt.trim().startsWith("{")||tt.trim().startsWith("[");if(nn&&ie.set(N.id,tt),Ht.__isPlainTextParser===!0){Ye!==void 0?N.content=tt:N.content+=pe,ie.delete(N.id),de.delete(N.id),N.rawContent=void 0,p(N);continue}let Kt=Ht.processChunk(tt);if(Kt instanceof Promise)Kt.then(Ge=>{var Zt;let Mt=typeof Ge=="string"?Ge:(Zt=Ge==null?void 0:Ge.text)!=null?Zt:null;if(Mt!==null&&Mt.trim()!=="")N.content=Mt,p(N);else if(!nn&&!tt.trim().startsWith("<")){let Ot=g;Ot&&Ot.id===N.id&&(Ye!==void 0?Ot.content=tt:Ot.content+=pe,ie.delete(Ot.id),de.delete(Ot.id),Ot.rawContent=void 0,p(Ot))}}).catch(()=>{Ye!==void 0?N.content=tt:N.content+=pe,ie.delete(N.id),de.delete(N.id),N.rawContent=void 0,p(N)});else{let Ge=typeof Kt=="string"?Kt:(gr=Kt==null?void 0:Kt.text)!=null?gr:null;Ge!==null&&Ge.trim()!==""?(N.content=Ge,p(N)):!nn&&!tt.trim().startsWith("<")&&(Ye!==void 0?N.content=tt:N.content+=pe,ie.delete(N.id),de.delete(N.id),N.rawContent=void 0,p(N))}}if(y.isComplete){let Ye=(An=(Kn=y.result)==null?void 0:Kn.response)!=null?An:N.content;if(Ye){let tt=ie.get(N.id),Ht=tt!=null?tt:je(Ye);N.rawContent=Ht;let nn=de.get(N.id),Ft=null,Kt=!1;if(nn&&(Ft=nn.getExtractedText(),Ft===null&&(Ft=Nr(Ht)),Ft===null)){let Ge=nn.processChunk(Ht);Ge instanceof Promise?(Kt=!0,Ge.then(Mt=>{var Ot;let Zt=typeof Mt=="string"?Mt:(Ot=Mt==null?void 0:Mt.text)!=null?Ot:null;if(Zt!==null){let Lt=g;Lt&&Lt.id===N.id&&(Lt.content=Zt,Lt.streaming=!1,de.delete(Lt.id),ie.delete(Lt.id),Ee.delete(Lt.id),p(Lt))}})):Ft=typeof Ge=="string"?Ge:(Zn=Ge==null?void 0:Ge.text)!=null?Zn:null}if(!Kt){Ft!==null&&Ft.trim()!==""?N.content=Ft:ie.has(N.id)||(N.content=je(Ye));let Ge=de.get(N.id);if(Ge){let Mt=(vt=Ge.close)==null?void 0:vt.call(Ge);Mt instanceof Promise&&Mt.catch(()=>{}),de.delete(N.id)}ie.delete(N.id),Ee.delete(N.id),N.streaming=!1,p(N)}}}}else if(se==="step_complete"){let P=y.stepType,S=y.executionType;if(P==="tool"||S==="context")continue;if(E){if(g!==null){let tt=g;de.delete(tt.id),ie.delete(tt.id),Ee.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,p(tt))}let pe=($t=y.result)==null?void 0:$t.response,Ye=Et;Ye&&(pe!=null?q(Ye,pe):(de.delete(Ye.id),ie.delete(Ye.id))),Et=null;continue}let Y=(_t=y.result)==null?void 0:_t.response,N=K();if(Y!=null){let pe=de.get(N.id),Ye=!1,tt=!1;if(pe){let Ht=pe.getExtractedText(),nn=ie.get(N.id),Ft=nn!=null?nn:je(Y);if(N.rawContent=Ft,Ht!==null&&Ht.trim()!=="")N.content=Ht,Ye=!0;else{let Kt=Nr(Ft);if(Kt!==null)N.content=Kt,Ye=!0;else{let Ge=pe.processChunk(Ft);if(Ge instanceof Promise)tt=!0,Ge.then(Mt=>{var Ot;let Zt=typeof Mt=="string"?Mt:(Ot=Mt==null?void 0:Mt.text)!=null?Ot:null;if(Zt!==null&&Zt.trim()!==""){let Lt=g;Lt&&Lt.id===N.id&&(Lt.content=Zt,Lt.streaming=!1,de.delete(Lt.id),ie.delete(Lt.id),Ee.delete(Lt.id),p(Lt))}else{let Lt=pe.getExtractedText(),Ln=g;Ln&&Ln.id===N.id&&(Lt!==null&&Lt.trim()!==""?Ln.content=Lt:ie.has(Ln.id)||(Ln.content=je(Y)),Ln.streaming=!1,de.delete(Ln.id),ie.delete(Ln.id),Ee.delete(Ln.id),p(Ln))}});else{let Mt=typeof Ge=="string"?Ge:(En=Ge==null?void 0:Ge.text)!=null?En:null;if(Mt!==null&&Mt.trim()!=="")N.content=Mt,Ye=!0;else{let Zt=pe.getExtractedText();Zt!==null&&Zt.trim()!==""&&(N.content=Zt,Ye=!0)}}}}}if(!tt){if(!N.rawContent){let Ht=ie.get(N.id);N.rawContent=Ht!=null?Ht:je(Y)}if(!Ye&&!ie.has(N.id)&&(N.content=je(Y)),pe){let Ht=(fr=pe.close)==null?void 0:fr.call(pe);Ht instanceof Promise&&Ht.catch(()=>{})}de.delete(N.id),ie.delete(N.id),Ee.delete(N.id),N.streaming=!1,p(N)}}else de.delete(N.id),ie.delete(N.id),Ee.delete(N.id),N.streaming=!1,p(N)}else if(se==="flow_complete"){let P=(_n=y.result)==null?void 0:_n.response;if(E){if(g!==null){let S=g;de.delete(S.id),ie.delete(S.id),Ee.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}}else if(P!=null){let S=K(),Y=ie.get(S.id),N=Y!=null?Y:je(P);S.rawContent=N;let pe=je(P),Ye=de.get(S.id);if(Ye){let nn=Nr(N);if(nn!==null)pe=nn;else{let Ft=Ye.processChunk(N);Ft instanceof Promise&&Ft.then(Ge=>{var Zt;let Mt=typeof Ge=="string"?Ge:(Zt=Ge==null?void 0:Ge.text)!=null?Zt:null;Mt!==null&&(S.content=Mt,S.streaming=!1,p(S))});let Kt=Ye.getExtractedText();Kt!==null&&(pe=Kt)}}de.delete(S.id),ie.delete(S.id),Ee.delete(S.id);let tt=pe!==S.content,Ht=S.streaming!==!1;tt&&(S.content=pe),S.streaming=!1,(tt||Ht)&&p(S)}else if(g!==null){let S=g;de.delete(S.id),ie.delete(S.id),Ee.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}t({type:"status",status:"idle"})}else if(se==="agent_start")F={executionId:y.executionId,agentId:(Tn=y.agentId)!=null?Tn:"virtual",agentName:(D=y.agentName)!=null?D:"",status:"running",currentIteration:0,maxTurns:(jn=y.maxTurns)!=null?jn:1,startedAt:xe(y.startedAt)};else if(se==="agent_iteration_start"){if(F&&(F.currentIteration=y.iteration),_==="separate"&&y.iteration>1){let P=g;P&&(P.streaming=!1,p(P),le.set(y.iteration-1,P),g=null)}}else if(se!=="agent_turn_start"){if(se==="agent_turn_delta"){if(y.contentType==="text"){let P=K();P.content+=(Rn=y.delta)!=null?Rn:"",P.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId,agentName:F==null?void 0:F.agentName},p(P)}else if(y.contentType==="thinking"){let P=(hr=y.turnId)!=null?hr:`agent-think-${y.iteration}`,S=Q(P);S.reasoning=(gn=S.reasoning)!=null?gn:{id:P,status:"streaming",chunks:[]},S.reasoning.chunks.push((Mn=y.delta)!=null?Mn:""),S.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId},p(S)}else if(y.contentType==="tool_input"){let P=(ee=y.toolCallId)!=null?ee:H.lastId;if(P){let S=C.get(P);S!=null&&S.toolCall&&(S.toolCall.chunks=(zn=S.toolCall.chunks)!=null?zn:[],S.toolCall.chunks.push((or=y.delta)!=null?or:""),p(S))}}}else if(se==="agent_turn_complete"){let P=y.turnId;if(P){let S=x.get(P);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=xe(y.completedAt);let Y=(jo=S.reasoning.startedAt)!=null?jo:Date.now();S.reasoning.durationMs=Math.max(0,((co=S.reasoning.completedAt)!=null?co:Date.now())-Y),S.streaming=!1,p(S)}}}else if(se==="agent_tool_start"){let P=(jr=y.toolCallId)!=null?jr:`agent-tool-${c()}`;Ce(W(y),P);let S=ae(P),Y=(Ze=S.toolCall)!=null?Ze:{id:P,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};Y.name=(Hn=(po=y.toolName)!=null?po:y.name)!=null?Hn:Y.name,Y.status="running",y.parameters!==void 0&&(Y.args=y.parameters),Y.startedAt=xe((fn=y.startedAt)!=null?fn:y.timestamp),S.toolCall=Y,S.streaming=!0,S.agentMetadata={executionId:y.executionId,iteration:y.iteration},p(S)}else if(se==="agent_tool_delta"){let P=(zo=y.toolCallId)!=null?zo:H.lastId;if(P){let S=(qo=C.get(P))!=null?qo:ae(P);S.toolCall&&(S.toolCall.chunks=(uo=S.toolCall.chunks)!=null?uo:[],S.toolCall.chunks.push((sr=y.delta)!=null?sr:""),S.toolCall.status="running",S.streaming=!0,p(S))}}else if(se==="agent_tool_complete"){let P=(Vo=y.toolCallId)!=null?Vo:H.lastId;if(P){let S=(zr=C.get(P))!=null?zr:ae(P);if(S.toolCall){S.toolCall.status="complete",y.result!==void 0&&(S.toolCall.result=y.result),typeof y.executionTime=="number"&&(S.toolCall.durationMs=y.executionTime),S.toolCall.completedAt=xe((mo=y.completedAt)!=null?mo:y.timestamp),S.streaming=!1,p(S);let Y=W(y);Y&&H.byCall.delete(Y)}}}else if(se!=="agent_iteration_complete"){if(se==="agent_reflection"||se==="agent_reflect"){let P=`agent-reflection-${y.executionId}-${y.iteration}`,S={id:P,role:"assistant",content:(ar=y.reflection)!=null?ar:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:P,status:"complete",chunks:[(go=y.reflection)!=null?go:""]},agentMetadata:{executionId:y.executionId,iteration:y.iteration}};p(S)}else if(se==="agent_complete"){F&&(F.status=y.success?"complete":"error",F.completedAt=xe(y.completedAt),F.stopReason=y.stopReason);let P=g;P&&(P.streaming=!1,p(P)),t({type:"status",status:"idle"})}else if(se==="agent_error"){let P=typeof y.error=="string"?y.error:(br=(yr=y.error)==null?void 0:yr.message)!=null?br:"Agent execution error";y.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",P):t({type:"error",error:new Error(P)})}else if(se!=="agent_ping")if(se==="agent_approval_start"){let P=(Uo=y.approvalId)!=null?Uo:`approval-${c()}`,S={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:(Jo=F==null?void 0:F.agentId)!=null?Jo:"virtual",executionId:(kr=(Ws=y.executionId)!=null?Ws:F==null?void 0:F.executionId)!=null?kr:"",toolName:(Lr=y.toolName)!=null?Lr:"",toolType:y.toolType,description:(qr=y.description)!=null?qr:`Execute ${(Rt=y.toolName)!=null?Rt:"tool"}`,parameters:y.parameters}};p(S)}else if(se==="step_await"&&y.awaitReason==="approval_required"){let P=(Vr=y.approvalId)!=null?Vr:`approval-${c()}`,S={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:(fo=F==null?void 0:F.agentId)!=null?fo:"virtual",executionId:(yo=(ho=y.executionId)!=null?ho:F==null?void 0:F.executionId)!=null?yo:"",toolName:(bo=y.toolName)!=null?bo:"",toolType:y.toolType,description:(kn=y.description)!=null?kn:`Execute ${(un=y.toolName)!=null?un:"tool"}`,parameters:y.parameters}};p(S)}else if(se==="agent_approval_complete"){let P=y.approvalId;if(P){let Y={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:(ir=y.decision)!=null?ir:"approved",agentId:(qe=F==null?void 0:F.agentId)!=null?qe:"virtual",executionId:(Ir=(xo=y.executionId)!=null?xo:F==null?void 0:F.executionId)!=null?Ir:"",toolName:(qn=y.toolName)!=null?qn:"",description:(Yo=y.description)!=null?Yo:"",resolvedAt:Date.now()}};p(Y)}}else if(se==="artifact_start"||se==="artifact_delta"||se==="artifact_update"||se==="artifact_complete"){if(se==="artifact_start"){let P=y.artifactType,S=String(y.id),Y=typeof y.title=="string"?y.title:void 0;if(t({type:"artifact_start",id:S,artifactType:P,title:Y,component:typeof y.component=="string"?y.component:void 0}),he.set(S,{markdown:"",title:Y}),!Ne.has(S)){Ne.add(S);let N={id:`artifact-ref-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:S,title:Y,artifactType:P,status:"streaming"}})};Ae.set(S,N),p(N)}}else if(se==="artifact_delta"){let P=String(y.id),S=typeof y.delta=="string"?y.delta:String((Ur=y.delta)!=null?Ur:"");t({type:"artifact_delta",id:P,artDelta:S});let Y=he.get(P);Y&&(Y.markdown+=S)}else if(se==="artifact_update"){let P=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};t({type:"artifact_update",id:String(y.id),props:P,component:typeof y.component=="string"?y.component:void 0})}else if(se==="artifact_complete"){let P=String(y.id);t({type:"artifact_complete",id:P});let S=Ae.get(P);if(S){S.streaming=!1;try{let Y=JSON.parse((Jr=S.rawContent)!=null?Jr:"{}");if(Y.props){Y.props.status="complete";let N=he.get(P);N!=null&&N.markdown&&(Y.props.markdown=N.markdown)}S.rawContent=JSON.stringify(Y)}catch{}he.delete(P),p(S),Ae.delete(P)}}}else if(se==="transcript_insert"){let P=y.message;if(!P||typeof P!="object")continue;let S=String((Pr=P.id)!=null?Pr:`msg-${c()}`),Y=P.role,pe={id:S,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(p(pe),pe.rawContent)try{let Ye=JSON.parse(pe.rawContent),tt=(xr=Ye==null?void 0:Ye.props)==null?void 0:xr.artifactId;typeof tt=="string"&&Ne.add(tt)}catch{}g=null,f.current=null,de.delete(S),ie.delete(S),Ee.delete(S)}else se==="error"&&y.error&&t({type:"error",error:y.error instanceof Error?y.error:new Error(String(y.error))})}}}}}};function pp(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Mo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Zr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var rs="[Image]";function up(e){return typeof e=="string"?[{type:"text",text:e}]:e}function mp(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function gp(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function fp(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function os(e){return{type:"text",text:e}}function hp(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 yp(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 bp(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 Sc=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],xp=["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"],cr=[...Sc,...xp];function vp(e){return Sc.includes(e)||e.startsWith("image/")}function ss(e){return vp(e.type)}async function Ac(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;ss(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 Ec(e,r=cr,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 Cp(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Tc(e,r){let t=Cp(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 as=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var is=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 d=0;d<a.length;d++)i+=a[d]*a[d];let u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var ko=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 is;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let d=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let v=!1,E=C=>{v||(v=!0,clearTimeout(x),f(new Error(C)))},x=setTimeout(()=>E("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(x),g())},{once:!0}),this.ws.addEventListener("error",()=>{E("WebSocket connection failed to "+d+"."+p)},{once:!0}),this.ws.addEventListener("close",C=>{if(!C.wasClean&&!v){let k=C.code!==1006?` (code ${C.code})`:"";E("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new as(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let d=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:d});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Fr=class{constructor(r={}){this.config=r;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Qr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ko(e.runtype);case"browser":if(!Fr.isSupported())throw new Error("Browser speech recognition not supported");return new Fr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function _s(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Qr({type:"runtype",runtype:e.runtype});if(Fr.isSupported())return Qr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ls(e){try{return _s(e),!0}catch{return!1}}var Lo=class e{constructor(r={},t){this.config=r;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Kr(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 ls((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Qr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var d,p,g,f,v,E;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((d=c.transcript)!=null&&d.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=c.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=c.text)!=null&&f.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let x=(E=this.pendingVoiceAssistantMessageId)!=null?E:(v=[...this.messages].reverse().find(C=>C.role==="assistant"))==null?void 0:v.id;x&&this.ttsSpokenMessageIds.add(x)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var d,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(d=this.callbacks).onVoiceStatusChanged)==null||p.call(d,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,d;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(d=r.browser)==null?void 0:d.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 Kr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:d}=r,g={id:a!=null?a:t==="user"?Mo():t==="assistant"?Zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...d!==void 0&&{voiceProcessing:d}};return this.upsertMessage(g),g}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:d,streaming:p=!1}=n,f={id:u!=null?u:s==="user"?Mo():s==="assistant"?Zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(f)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,d,p,g,f;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=Mo(),o=Zr(),a={id:s,role:"user",content:n||rs,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!E){let x={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(x)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,E||(v instanceof Error?(p=(d=this.callbacks).onError)==null||p.call(d,v):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(v))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Zr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let d={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(d),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,d;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let g=null;if(p instanceof Response){if(!p.ok){let f=await p.json().catch(()=>null);throw new Error((u=f==null?void 0:f.error)!=null?u:`Approval request failed: ${p.status}`)}g=p.body}else p instanceof ReadableStream&&(g=p);g?await this.connectStream(g):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(d=(c=this.callbacks).onError)==null||d.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Qn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as wp 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=wp[s];return o?Sp(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 Sp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,d])=>{c!=="stroke"&&u.setAttribute(c,String(d))}),s.appendChild(u)}}}),s}var cs={allowedTypes:cr,maxFileSize:10*1024*1024,maxFiles:4};function Ap(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ep(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var eo=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:cs.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:cs.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:cs.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:cs.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let d=Ec(c,this.config.allowedTypes,this.config.maxFileSize);if(!d.valid){let p=(s=d.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await Ac(c),g=ss(c)?URL.createObjectURL(c):null,f={id:Ap(),file:c,previewUrl:g,contentPart:p};this.attachments.push(f),this.renderPreview(f)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=ss(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=Ep(r.file.type),u=me(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=Tc(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 Mc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Io(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];Mc(o)&&Mc(s)?t[n]=Io(o,s):t[n]=s}return t}var Nn="min(440px, calc(100vw - 24px))",js="440px",It={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Nn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function kc(e,r){if(!(!e&&!r))return e?r?Io(e,r):e:r}function zs(e){var r,t,n,s,o,a,i,u,c,d,p,g,f,v,E,x,C,k,H,w,M;return e?{...It,...e,theme:kc(It.theme,e.theme),darkTheme:kc(It.darkTheme,e.darkTheme),launcher:{...It.launcher,...e.launcher,dock:{...(r=It.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=It.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...It.copy,...e.copy},sendButton:{...It.sendButton,...e.sendButton},statusIndicator:{...It.statusIndicator,...e.statusIndicator},voiceRecognition:{...It.voiceRecognition,...e.voiceRecognition},features:(()=>{var Q,Ce,re,Ae;let W=(Q=It.features)==null?void 0:Q.artifacts,T=(Ce=e.features)==null?void 0:Ce.artifacts,G=(re=It.features)==null?void 0:re.scrollToBottom,K=(Ae=e.features)==null?void 0:Ae.scrollToBottom,J=W===void 0&&T===void 0?void 0:{...W,...T,layout:{...W==null?void 0:W.layout,...T==null?void 0:T.layout}},I=G===void 0&&K===void 0?void 0:{...G,...K};return{...It.features,...e.features,...I!==void 0?{scrollToBottom:I}:{},...J!==void 0?{artifacts:J}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...It.layout,...e.layout,header:{...(a=It.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=It.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(d=It.layout)==null?void 0:d.messages)==null?void 0:p.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(E=(v=It.layout)==null?void 0:v.messages)==null?void 0:E.timestamp,...(C=(x=e.layout)==null?void 0:x.messages)==null?void 0:C.timestamp}},slots:{...(k=It.layout)==null?void 0:k.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...It.markdown,...e.markdown,options:{...(w=It.markdown)==null?void 0:w.options,...(M=e.markdown)==null?void 0:M.options}},messageActions:{...It.messageActions,...e.messageActions}}:It}var Lc={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"}},Ic={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"}},Pc={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Nn,maxWidth:js,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 Po(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."))?Po(e,n):n}function qs(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=Po(e,a);u!==void 0&&(r[i]={path:i,value:u,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function Wc(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 Tp(e,r){return r?Rc(e,r):e}function Wo(e,r={}){var s,o,a,i,u,c,d,p,g,f,v,E,x;let t={palette:Lc,semantic:Ic,components:Pc},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(d=e==null?void 0:e.semantic)==null?void 0:d.colors,interactive:{...t.semantic.colors.interactive,...(g=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(E=e==null?void 0:e.semantic)==null?void 0:E.spacing},typography:{...t.semantic.typography,...(x=e==null?void 0:e.semantic)==null?void 0:x.typography}},components:Tp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let C=Wc(n);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(k=>k.message).join(", ")}`)}if(r.plugins)for(let C of r.plugins)n=C.transform(n);return n}function Vs(e){var v,E,x,C,k,H,w,M,W,T,G,K,J,I,Q,Ce,re,Ae,Ne,he,ke,Le,ae,xe,je,de,ie,Ee,Be,it,Et,q,F,le,_,V,oe,Oe,Z,te,kt,lt,Nt,Xt,$e,ce,He,Pt,Wt,ot,st,rn,tn,on,j,Ie,ue,gt,Fe,ne,ye,De,xt,zt,ct,qt,ft,Ke,ht,We,Vt,Gn,tr,On,Qe,Tr,Xn,Mr,Pn,_r,pr,nr,at,wn,$n,dn,ur,Sn,wt,pn,Wn,mr,rr,gr,Kn,An,Zn,vt,$t,_t,En,fr,_n,Tn,D,jn,Rn,hr,gn,Mn;let r=qs(e),t={};for(let[ee,zn]of Object.entries(r)){let or=ee.replace(/\./g,"-");t[`--persona-${or}`]=zn.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(x=t["--persona-semantic-colors-accent"])!=null?x: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"]=(k=t["--persona-semantic-colors-background"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(M=t["--persona-semantic-colors-text-muted"])!=null?M:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W: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"]=(G=t["--persona-semantic-colors-divider"])!=null?G:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(K=t["--persona-components-voice-recording-indicator"])!=null?K:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(J=t["--persona-components-voice-recording-background"])!=null?J:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(I=t["--persona-components-voice-processing-icon"])!=null?I:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(Q=t["--persona-components-voice-speaking-icon"])!=null?Q:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ce=t["--persona-components-approval-requested-background"])!=null?Ce:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(re=t["--persona-components-approval-requested-border"])!=null?re:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ae=t["--persona-components-approval-requested-text"])!=null?Ae:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(Ne=t["--persona-components-approval-approve-background"])!=null?Ne: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"]=(ke=t["--persona-components-attachment-image-background"])!=null?ke:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Le=t["--persona-components-attachment-image-border"])!=null?Le:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ae=t["--persona-semantic-typography-fontFamily"])!=null?ae:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(xe=t["--persona-semantic-typography-fontSize"])!=null?xe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(je=t["--persona-semantic-typography-fontWeight"])!=null?je: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"]=(ie=t["--persona-palette-radius-sm"])!=null?ie:"0.125rem",t["--persona-radius-md"]=(Ee=t["--persona-palette-radius-md"])!=null?Ee:"0.375rem",t["--persona-radius-lg"]=(Be=t["--persona-palette-radius-lg"])!=null?Be:"0.5rem",t["--persona-radius-xl"]=(it=t["--persona-palette-radius-xl"])!=null?it:"0.75rem",t["--persona-radius-full"]=(Et=t["--persona-palette-radius-full"])!=null?Et:"9999px",t["--persona-launcher-radius"]=(F=(q=t["--persona-components-launcher-borderRadius"])!=null?q:t["--persona-palette-radius-full"])!=null?F:"9999px",t["--persona-launcher-bg"]=(le=t["--persona-components-launcher-background"])!=null?le:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(V=t["--persona-components-launcher-border"])!=null?V:t["--persona-border"],t["--persona-button-primary-bg"]=(oe=t["--persona-components-button-primary-background"])!=null?oe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Oe=t["--persona-components-button-primary-foreground"])!=null?Oe:t["--persona-text-inverse"],t["--persona-button-radius"]=(te=(Z=t["--persona-components-button-primary-borderRadius"])!=null?Z:t["--persona-palette-radius-full"])!=null?te:"9999px",t["--persona-panel-radius"]=(lt=(kt=t["--persona-components-panel-borderRadius"])!=null?kt:t["--persona-radius-xl"])!=null?lt:"0.75rem",t["--persona-panel-border"]=(Nt=t["--persona-components-panel-border"])!=null?Nt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=($e=(Xt=t["--persona-components-panel-shadow"])!=null?Xt:t["--persona-palette-shadows-xl"])!=null?$e:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(He=(ce=t["--persona-components-input-borderRadius"])!=null?ce:t["--persona-radius-lg"])!=null?He:"0.5rem",t["--persona-message-user-radius"]=(Wt=(Pt=t["--persona-components-message-user-borderRadius"])!=null?Pt:t["--persona-radius-lg"])!=null?Wt:"0.5rem",t["--persona-message-assistant-radius"]=(st=(ot=t["--persona-components-message-assistant-borderRadius"])!=null?ot:t["--persona-radius-lg"])!=null?st:"0.5rem",t["--persona-header-bg"]=(rn=t["--persona-components-header-background"])!=null?rn:t["--persona-surface"],t["--persona-header-border"]=(tn=t["--persona-components-header-border"])!=null?tn:t["--persona-divider"],t["--persona-header-icon-bg"]=(on=t["--persona-components-header-iconBackground"])!=null?on:t["--persona-primary"],t["--persona-header-icon-fg"]=(j=t["--persona-components-header-iconForeground"])!=null?j:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ie=t["--persona-components-header-titleForeground"])!=null?Ie:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ue=t["--persona-components-header-subtitleForeground"])!=null?ue:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(gt=t["--persona-components-header-actionIconForeground"])!=null?gt:t["--persona-muted"];let n=(Fe=e.components)==null?void 0:Fe.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"]=(ne=t["--persona-components-input-background"])!=null?ne:t["--persona-surface"],t["--persona-input-placeholder"]=(ye=t["--persona-components-input-placeholder"])!=null?ye:t["--persona-text-muted"],t["--persona-message-user-bg"]=(De=t["--persona-components-message-user-background"])!=null?De:t["--persona-accent"],t["--persona-message-user-text"]=(xt=t["--persona-components-message-user-text"])!=null?xt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(zt=t["--persona-components-message-user-shadow"])!=null?zt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(ct=t["--persona-components-message-assistant-background"])!=null?ct:t["--persona-surface"],t["--persona-message-assistant-text"]=(qt=t["--persona-components-message-assistant-text"])!=null?qt:t["--persona-text"],t["--persona-message-assistant-border"]=(ft=t["--persona-components-message-assistant-border"])!=null?ft:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Ke=t["--persona-components-message-assistant-shadow"])!=null?Ke:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(We=(ht=t["--persona-components-scrollToBottom-background"])!=null?ht:t["--persona-button-primary-bg"])!=null?We:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Gn=(Vt=t["--persona-components-scrollToBottom-foreground"])!=null?Vt:t["--persona-button-primary-fg"])!=null?Gn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(tr=t["--persona-components-scrollToBottom-border"])!=null?tr:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(On=t["--persona-components-scrollToBottom-size"])!=null?On:"40px",t["--persona-scroll-to-bottom-radius"]=(Xn=(Tr=(Qe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Qe:t["--persona-button-radius"])!=null?Tr:t["--persona-radius-full"])!=null?Xn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Pn=(Mr=t["--persona-components-scrollToBottom-shadow"])!=null?Mr:t["--persona-palette-shadows-sm"])!=null?Pn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(_r=t["--persona-components-scrollToBottom-padding"])!=null?_r:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(pr=t["--persona-components-scrollToBottom-gap"])!=null?pr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(at=(nr=t["--persona-components-scrollToBottom-fontSize"])!=null?nr:t["--persona-palette-typography-fontSize-sm"])!=null?at:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(wn=t["--persona-components-scrollToBottom-iconSize"])!=null?wn:"14px",t["--persona-tool-bubble-shadow"]=($n=t["--persona-components-toolBubble-shadow"])!=null?$n:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(dn=t["--persona-components-reasoningBubble-shadow"])!=null?dn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(ur=t["--persona-components-composer-shadow"])!=null?ur:"none",t["--persona-md-inline-code-bg"]=(Sn=t["--persona-components-markdown-inlineCode-background"])!=null?Sn:t["--persona-container"],t["--persona-md-inline-code-color"]=(wt=t["--persona-components-markdown-inlineCode-foreground"])!=null?wt:t["--persona-text"],t["--persona-md-link-color"]=(Wn=(pn=t["--persona-components-markdown-link-foreground"])!=null?pn:t["--persona-accent"])!=null?Wn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(mr=t["--persona-components-markdown-codeBlock-background"])!=null?mr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(rr=t["--persona-components-markdown-codeBlock-borderColor"])!=null?rr:t["--persona-border"],t["--persona-md-code-block-text-color"]=(gr=t["--persona-components-markdown-codeBlock-textColor"])!=null?gr:"inherit",t["--persona-md-table-header-bg"]=(Kn=t["--persona-components-markdown-table-headerBackground"])!=null?Kn:t["--persona-container"],t["--persona-md-table-border-color"]=(An=t["--persona-components-markdown-table-borderColor"])!=null?An:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(vt=t["--persona-components-markdown-blockquote-borderColor"])!=null?vt:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=($t=t["--persona-components-markdown-blockquote-background"])!=null?$t:"transparent",t["--persona-md-blockquote-text-color"]=(_t=t["--persona-components-markdown-blockquote-textColor"])!=null?_t:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(En=t["--persona-components-collapsibleWidget-container"])!=null?En:t["--persona-surface"],t["--cw-surface"]=(fr=t["--persona-components-collapsibleWidget-surface"])!=null?fr:t["--persona-surface"],t["--cw-border"]=(_n=t["--persona-components-collapsibleWidget-border"])!=null?_n:t["--persona-border"],t["--persona-message-border"]=(Tn=t["--persona-components-message-border"])!=null?Tn:t["--persona-border"];let c=e.components,d=c==null?void 0:c.iconButton;d&&(d.background&&(t["--persona-icon-btn-bg"]=d.background),d.border&&(t["--persona-icon-btn-border"]=d.border),d.color&&(t["--persona-icon-btn-color"]=d.color),d.padding&&(t["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(t["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(t["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(t["--persona-icon-btn-active-border"]=d.activeBorder));let p=c==null?void 0:c.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.gap));let g=c==null?void 0:c.toggleGroup;g&&(g.gap&&(t["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(t["--persona-toggle-group-radius"]=g.borderRadius));let f=c==null?void 0:c.artifact;if(f!=null&&f.toolbar){let ee=f.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"]=(jn=t["--persona-dropdown-border"])!=null?jn:ee.copyMenuBorder),ee.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ee.copyMenuShadow,t["--persona-dropdown-shadow"]=(Rn=t["--persona-dropdown-shadow"])!=null?Rn:ee.copyMenuShadow),ee.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ee.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(hr=t["--persona-dropdown-radius"])!=null?hr: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(f!=null&&f.tab){let ee=f.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(f!=null&&f.pane){let ee=f.pane;if(ee.toolbarBackground){let zn=(Mn=Po(e,ee.toolbarBackground))!=null?Mn:ee.toolbarBackground;t["--persona-artifact-toolbar-bg"]=zn}}return t}var Mp={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 kp={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"}}},Hc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ds=()=>{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"},Lp=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":ds()},Bc=e=>Lp(e),Ip=e=>Wo(e),Pp=e=>{var t;let r=Wo(void 0,{validate:!1});return Wo({...e,palette:{...r.palette,colors:{...kp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},ps=e=>{let r=Bc(e),t=Hc(e==null?void 0:e.theme),n=Hc(e==null?void 0:e.darkTheme);return r==="dark"?Pp(Io(t!=null?t:{},n!=null?n:{})):Ip(t)},Wp=e=>Vs(e),Or=(e,r)=>{var o;let t=ps(r),n=Wp(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)},Us=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(ds())});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(ds());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 Rp}from"idiomorph";var Dc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Rp.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 Nc(e,r){var t,n,s,o,a,i,u,c,d,p,g,f,v,E,x,C,k,H,w,M,W,T,G,K,J,I,Q;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(d=(c=e.llmContent)==null?void 0:c.length)!=null?d:0,(g=(p=e.approval)==null?void 0:p.status)!=null?g:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(C=(x=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:x.length)!=null?C:0,(M=(w=(H=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:H[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?M:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(T=e.toolCall)!=null&&T.args?JSON.stringify(e.toolCall.args).length:0,(J=(K=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:K.length)!=null?J:0,(Q=(I=e.contentParts)==null?void 0:I.length)!=null?Q:0,r].join("\0")}function Fc(){return new Map}function Oc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function $c(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function _c(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function us(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Ro(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ho(e,r){return Ro(e)-e.scrollTop<=r}function ms(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,d=t-n;return a||Math.abs(d)<o?{action:"none",delta:d,nextLastScrollTop:t}:!r&&s&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:t}:r&&i&&d<0?{action:"pause",delta:d,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:d,nextLastScrollTop:t}:{action:"none",delta:d,nextLastScrollTop:t}}function gs(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},vn=1e5,Cr=vn+1;function Js(e,r=vn){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 Bo=0,wr=null;function Ys(e=document){var t;if(Bo++,Bo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;wr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Bo=Math.max(0,Bo-1),Bo===0&&wr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=wr.originalOverflow,s.style.position=wr.originalPosition,s.style.top=wr.originalTop,s.style.width=wr.originalWidth,o.scrollTo(0,wr.scrollY),wr=null}}}var fs={side:"right",width:"420px",animate:!0,reveal:"resize"},en=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Jn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:fs.side,width:(s=r==null?void 0:r.width)!=null?s:fs.width,animate:(o=r==null?void 0:r.animate)!=null?o:fs.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:fs.reveal}};var Yn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Do=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
8
8
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
10
10
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -12,14 +12,14 @@ import{Marked as Bd}from"marked";var Dd=e=>{if(e)return e},Qo=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 R,w,M,W,E,G,K,J,L,Q,we,ne,Ee,Oe;let a=(R=o.launcher)!=null?R:{},i=Zt(o),u=t.querySelector("[data-role='launcher-title']");if(u){let fe=(w=a.title)!=null?w:"Chat Assistant";u.textContent=fe,u.setAttribute("title",fe)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let fe=(M=a.subtitle)!=null?M:"Get answers fast";c.textContent=fe,c.setAttribute("title",fe)}let d=t.querySelector(".persona-flex-col");d&&(a.textHidden||i?d.style.display="none":d.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let fe=(W=a.agentIconSize)!=null?W:"40px";if(p.style.height=fe,p.style.width=fe,p.innerHTML="",a.agentIconName){let Ie=parseFloat(fe)||24,Pe=ge(a.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(p.appendChild(Pe),p.style.display=""):(p.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(G=a.agentIconText)!=null?G:"\u{1F4AC}",p.style.display="")}let m=t.querySelector("[data-role='launcher-image']");if(m){let fe=(K=a.agentIconSize)!=null?K:"40px";m.style.height=fe,m.style.width=fe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(m.src=a.iconUrl,m.style.display="block"):m.style.display="none"}let f=t.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let fe=(J=a.callToActionIconSize)!=null?J:"32px";f.style.height=fe,f.style.width=fe,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let Ie=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Ie=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Pe=parseFloat(fe)||24,se=Math.max(Pe-Ie,8),be=ge(a.callToActionIconName,se,"currentColor",2);be?f.appendChild(be):f.textContent=(L=a.callToActionIconText)!=null?L:"\u2197"}else f.textContent=(Q=a.callToActionIconText)!=null?Q:"\u2197"}let v=a.position&&Vn[a.position]?Vn[a.position]:Vn["bottom-right"],A="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",x="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?x:`${A} ${v}`,i||(t.style.zIndex=String((we=a.zIndex)!=null?we:xn));let C="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(ne=a.border)!=null?ne:C,t.style.boxShadow=(Ee=a.shadow)!=null?Ee:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Oe=a.collapsedMaxWidth)!=null?Oe:"",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 vn={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))"},vr=e=>{var J,L,Q,we,ne,Ee,Oe,fe,Ie,Pe,se,be,ze,ce,ae,Te,Ne,lt,Tt,q,F,ie,j,U,re,_e,Z,ee,kt,ct,Dt,Jt;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=(J=r==null?void 0:r.launcher)!=null?J:{},o=(L=s.headerIconSize)!=null?L:"48px",a=(Q=s.closeButtonSize)!=null?Q:"32px",i=(we=s.closeButtonPlacement)!=null?we:"inline",u=(ne=s.headerIconHidden)!=null?ne:!1,c=s.headerIconName,d=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(d.style.height=o,d.style.width=o,d.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",d.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let je=parseFloat(o)||24,le=ge(c,je*.6,"currentColor",1);le?d.replaceChildren(le):d.textContent=(Oe=(Ee=r==null?void 0:r.launcher)==null?void 0:Ee.agentIconText)!=null?Oe:"\u{1F4AC}"}else if((fe=r==null?void 0:r.launcher)!=null&&fe.iconUrl){let je=h("img");je.src=r.launcher.iconUrl,je.alt="",je.className="persona-rounded-xl persona-object-cover",je.style.height=o,je.style.width=o,d.replaceChildren(je)}else d.textContent=(Pe=(Ie=r==null?void 0:r.launcher)==null?void 0:Ie.agentIconText)!=null?Pe:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=h("span","persona-text-base persona-font-semibold");m.style.color=vn.titleColor,m.textContent=(be=(se=r==null?void 0:r.launcher)==null?void 0:se.title)!=null?be:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=vn.subtitleColor,f.textContent=(ce=(ze=r==null?void 0:r.launcher)==null?void 0:ze.subtitle)!=null?ce:"Here to help you get answers fast",p.append(m,f),u?n.append(p):n.append(d,p);let v=(ae=s.clearChat)!=null?ae:{},A=(Te=v.enabled)!=null?Te:!0,x=(Ne=v.placement)!=null?Ne:"inline",C=null,k=null;if(A){let je=(lt=v.size)!=null?lt:"32px",le=(Tt=v.iconName)!=null?Tt:"refresh-cw",De=(q=v.iconColor)!=null?q:"",It=(F=v.backgroundColor)!=null?F:"",Pt=(ie=v.borderWidth)!=null?ie:"",rt=(j=v.borderColor)!=null?j:"",ot=(U=v.borderRadius)!=null?U:"",en=(re=v.paddingX)!=null?re:"",Qt=(_e=v.paddingY)!=null?_e:"",tn=(Z=v.tooltipText)!=null?Z:"Clear chat",_=(ee=v.showTooltip)!=null?ee:!0;k=h("div",x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),x==="top-right"&&(k.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=je,C.style.width=je,C.type="button",C.setAttribute("aria-label",tn),C.style.color=De||vn.actionIconColor;let We=ge(le,"20px","currentColor",1);if(We&&C.appendChild(We),It&&(C.style.backgroundColor=It,C.classList.remove("hover:persona-bg-gray-100")),Pt||rt){let de=Pt||"0px",ft=rt||"transparent";C.style.border=`${de} solid ${ft}`,C.classList.remove("persona-border-none")}if(ot&&(C.style.borderRadius=ot,C.classList.remove("persona-rounded-full")),en?(C.style.paddingLeft=en,C.style.paddingRight=en):(C.style.paddingLeft="",C.style.paddingRight=""),Qt?(C.style.paddingTop=Qt,C.style.paddingBottom=Qt):(C.style.paddingTop="",C.style.paddingBottom=""),k.appendChild(C),_&&tn&&C&&k){let de=null,ft=()=>{if(de||!C)return;let te=C.ownerDocument,he=te.body;if(!he)return;de=Kn(te,"div","persona-clear-chat-tooltip"),de.textContent=tn;let Fe=Kn(te,"div");Fe.className="persona-clear-chat-tooltip-arrow",de.appendChild(Fe);let Ct=C.getBoundingClientRect();de.style.position="fixed",de.style.zIndex=String(br),de.style.left=`${Ct.left+Ct.width/2}px`,de.style.top=`${Ct.top-8}px`,de.style.transform="translate(-50%, -100%)",he.appendChild(de)},$e=()=>{de&&de.parentNode&&(de.parentNode.removeChild(de),de=null)};k.addEventListener("mouseenter",ft),k.addEventListener("mouseleave",$e),C.addEventListener("focus",ft),C.addEventListener("blur",$e),k._cleanupTooltip=()=>{$e(),k&&(k.removeEventListener("mouseenter",ft),k.removeEventListener("mouseleave",$e)),C&&(C.removeEventListener("focus",ft),C.removeEventListener("blur",$e))}}x==="inline"&&n.appendChild(k)}let R=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":A&&x==="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 M=(kt=s.closeButtonTooltipText)!=null?kt:"Close chat",W=(ct=s.closeButtonShowTooltip)!=null?ct:!0;w.setAttribute("aria-label",M),w.style.display=t?"":"none";let E=(Dt=s.closeButtonIconName)!=null?Dt:"x",G=(Jt=s.closeButtonIconText)!=null?Jt:"\xD7";w.style.color=s.closeButtonColor||vn.actionIconColor;let K=ge(E,"20px","currentColor",1);if(K?w.appendChild(K):w.textContent=G,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let je=s.closeButtonBorderWidth||"0px",le=s.closeButtonBorderColor||"transparent";w.style.border=`${je} 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),W&&M){let je=null,le=()=>{if(je)return;let It=w.ownerDocument,Pt=It.body;if(!Pt)return;je=Kn(It,"div","persona-clear-chat-tooltip"),je.textContent=M;let rt=Kn(It,"div");rt.className="persona-clear-chat-tooltip-arrow",je.appendChild(rt);let ot=w.getBoundingClientRect();je.style.position="fixed",je.style.zIndex=String(br),je.style.left=`${ot.left+ot.width/2}px`,je.style.top=`${ot.top-8}px`,je.style.transform="translate(-50%, -100%)",Pt.appendChild(je)},De=()=>{je&&je.parentNode&&(je.parentNode.removeChild(je),je=null)};R.addEventListener("mouseenter",le),R.addEventListener("mouseleave",De),w.addEventListener("focus",le),w.addEventListener("blur",De),R._cleanupTooltip=()=>{De(),R.removeEventListener("mouseenter",le),R.removeEventListener("mouseleave",De),w.removeEventListener("focus",le),w.removeEventListener("blur",De)}}return i!=="top-right"&&n.appendChild(R),{header:n,iconHolder:d,headerTitle:m,headerSubtitle:f,closeButton:w,closeButtonWrapper:R,clearChatButton:C,clearChatButtonWrapper:k}},eo=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function Nr(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(br)):(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 f of r){if(f.dividerBefore){let x=document.createElement("hr");a.appendChild(x)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let x=ge(f.icon,16,"currentColor",1.5);x&&v.appendChild(x)}let A=document.createElement("span");A.textContent=f.label,v.appendChild(A),v.addEventListener("click",x=>{x.stopPropagation(),d(),t(f.id)}),a.appendChild(v)}let i=null;function u(){if(!o)return;let f=n.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!n.contains(v.target)&&d()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function d(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?c():d()}function m(){d(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:d,toggle:p,destroy:m}}function Bt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=ge(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[d,p]of Object.entries(i))u.setAttribute(d,p);return u}function gs(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let d=h("button",c);if(d.type="button",d.setAttribute("aria-label",t),r){let m=ge(r,o!=null?o:14,"currentColor",2);m&&d.appendChild(m)}let p=h("span");if(p.textContent=t,d.appendChild(p),i&&d.addEventListener("click",i),u)for(let[m,f]of Object.entries(u))d.setAttribute(m,f);return d}function ms(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let d of i)d.btn.setAttribute("aria-pressed",d.id===a?"true":"false")}for(let d of r){let p;d.icon?p=Bt({icon:d.icon,label:d.label,onClick:()=>{a=d.id,u(),n(d.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",d.label),p.title=d.label,p.textContent=d.label,p.addEventListener("click",()=>{a=d.id,u(),n(d.id)})),p.setAttribute("aria-pressed",d.id===a?"true":"false"),i.push({id:d.id,btn:p}),o.appendChild(p)}function c(d){a=d,u()}return{element:o,setSelected:c}}function Vs(e){var f,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let d=h("span","persona-combo-btn-label");d.textContent=r,c.appendChild(d);let p=ge(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",c.appendChild(p)),u&&(c.style.borderRadius=(f=u.borderRadius)!=null?f:"10px",c.style.padding=(v=u.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var A,x;c.style.backgroundColor=(A=u.background)!=null?A:"",c.style.borderColor=(x=u.border)!=null?x:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let m=Nr({items:n,onSelect:A=>{c.setAttribute("aria-expanded","false"),s(A)},anchor:c,position:o,portal:a});return a||c.appendChild(m.element),c.addEventListener("click",A=>{A.stopPropagation();let x=!m.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),m.toggle()}),c.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),c.click())}),{element:c,setLabel:A=>{d.textContent=A,c.setAttribute("aria-label",A)},open:()=>{c.setAttribute("aria-expanded","true"),m.show()},close:()=>{c.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let A=!m.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",A?"false":"true"),m.toggle()},destroy:()=>{m.destroy(),c.remove()}}}var kc=e=>{var n;let r=vr({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 xp(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=ge(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=Nr({items:a.menuItems,onSelect:d=>t==null?void 0:t(d),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",d=>{d.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Lc=e=>{var k,R,w,M,W,E,G,K,J;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(k=r==null?void 0:r.launcher)!=null?k:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=s==null?void 0:s.titleMenu,c,d;if(u)c=Vs({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=vn.titleColor,d=(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"),d=h("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=vn.titleColor,d.textContent=(M=a.title)!=null?M:"Chat Assistant",c.appendChild(d),xp(c,s==null?void 0:s.trailingActions,(W=s==null?void 0:s.onAction)!=null?W:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let Q=s.onTitleClick;c.addEventListener("click",we=>{we.target.closest("button")||Q()}),c.addEventListener("keydown",we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),Q())})}let L=s==null?void 0:s.titleRowHover;L&&(c.style.borderRadius=(E=L.borderRadius)!=null?E:"10px",c.style.padding=(G=L.padding)!=null?G:"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 Q,we;c.style.backgroundColor=(Q=L.background)!=null?Q:"",c.style.borderColor=(we=L.border)!=null?we:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let p=(K=a.closeButtonSize)!=null?K:"32px",m=h("div",""),f=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");f.style.height=p,f.style.width=p,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=t?"":"none",f.style.color=a.closeButtonColor||vn.actionIconColor;let v=(J=a.closeButtonIconName)!=null?J:"x",A=ge(v,"20px","currentColor",2);A?f.appendChild(A):f.textContent="\xD7",n&&f.addEventListener("click",n),m.appendChild(f),i.appendChild(m);let x=h("div");x.style.display="none";let C=h("span");return C.style.display="none",{header:i,iconHolder:x,headerTitle:d,headerSubtitle:C,closeButton:f,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}},Js={default:kc,minimal:Lc},Ic=e=>{var r;return(r=Js[e])!=null?r:Js.default},Bo=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),d=h("div");d.style.display="none";let p=h("span"),m=h("span"),f=h("button");f.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:d,headerTitle:p,headerSubtitle:m,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Ic(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Do=e=>{var Ne,lt,Tt,q,F,ie,j,U,re,_e,Z,ee,kt,ct,Dt,Jt,je,le,De,It,Pt,rt,ot,en,Qt,tn,_;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=(lt=(Ne=r==null?void 0:r.copy)==null?void 0:Ne.inputPlaceholder)!=null?lt:"Type your message\u2026",o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let We=Math.min(o.scrollHeight,u);o.style.height=`${We}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 d=(Tt=r==null?void 0:r.sendButton)!=null?Tt:{},p=(q=d.useIcon)!=null?q:!1,m=(F=d.iconText)!=null?F:"\u2191",f=d.iconName,v=(ie=d.tooltipText)!=null?ie:"Send message",A=(j=d.showTooltip)!=null?j:!1,x=(U=d.size)!=null?U:"40px",C=d.backgroundColor,k=d.textColor,R=h("div","persona-send-button-wrapper"),w=h("button",p?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),p){if(w.style.width=x,w.style.height=x,w.style.minWidth=x,w.style.minHeight=x,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",k?w.style.color=k:w.style.color="var(--persona-button-primary-fg, #ffffff)",f){let We=parseFloat(x)||24,de=(k==null?void 0:k.trim())||"currentColor",ft=ge(f,We,de,2);ft?w.appendChild(ft):w.textContent=m}else w.textContent=m;C?w.style.backgroundColor=C:w.classList.add("persona-bg-persona-primary")}else w.textContent=(_e=(re=r==null?void 0:r.copy)==null?void 0:re.sendButtonLabel)!=null?_e:"Send",k?w.style.color=k:w.classList.add("persona-text-white");if(d.borderWidth&&(w.style.borderWidth=d.borderWidth,w.style.borderStyle="solid"),d.borderColor&&(w.style.borderColor=d.borderColor),d.paddingX?(w.style.paddingLeft=d.paddingX,w.style.paddingRight=d.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),d.paddingY?(w.style.paddingTop=d.paddingY,w.style.paddingBottom=d.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),A&&v){let We=h("div","persona-send-button-tooltip");We.textContent=v,R.appendChild(We)}R.appendChild(w);let M=(Z=r==null?void 0:r.voiceRecognition)!=null?Z:{},W=M.enabled===!0,E=null,G=null,K=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),J=((ee=M.provider)==null?void 0:ee.type)==="runtype";if(W&&(K||J)){G=h("div","persona-send-button-wrapper"),E=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),E.type="button",E.setAttribute("data-persona-composer-mic",""),E.setAttribute("aria-label","Start voice recognition");let We=(kt=M.iconName)!=null?kt:"mic",de=(ct=M.iconSize)!=null?ct:x,ft=parseFloat(de)||24,$e=(Dt=M.backgroundColor)!=null?Dt:C,te=(Jt=M.iconColor)!=null?Jt:k;E.style.width=de,E.style.height=de,E.style.minWidth=de,E.style.minHeight=de,E.style.fontSize="18px",E.style.lineHeight="1",te?E.style.color=te:E.style.color="var(--persona-text, #111827)";let Fe=ge(We,ft,te||"currentColor",1.5);Fe?E.appendChild(Fe):E.textContent="\u{1F3A4}",$e&&(E.style.backgroundColor=$e),M.borderWidth&&(E.style.borderWidth=M.borderWidth,E.style.borderStyle="solid"),M.borderColor&&(E.style.borderColor=M.borderColor),M.paddingX&&(E.style.paddingLeft=M.paddingX,E.style.paddingRight=M.paddingX),M.paddingY&&(E.style.paddingTop=M.paddingY,E.style.paddingBottom=M.paddingY),G.appendChild(E);let Ct=(je=M.tooltipText)!=null?je:"Start voice recognition";if(((le=M.showTooltip)!=null?le:!1)&&Ct){let dt=h("div","persona-send-button-tooltip");dt.textContent=Ct,G.appendChild(dt)}}let Q=(De=r==null?void 0:r.attachments)!=null?De:{},we=Q.enabled===!0,ne=null,Ee=null,Oe=null,fe=null;if(we){fe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fe.style.display="none",Oe=h("input"),Oe.type="file",Oe.accept=((It=Q.allowedTypes)!=null?It:ar).join(","),Oe.multiple=((Pt=Q.maxFiles)!=null?Pt:4)>1,Oe.style.display="none",Oe.setAttribute("aria-label","Attach files"),Ee=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",(rt=Q.buttonTooltipText)!=null?rt:"Attach file");let We=(ot=Q.buttonIconName)!=null?ot:"paperclip",de=x,ft=parseFloat(de)||40,$e=Math.round(ft*.6);ne.style.width=de,ne.style.height=de,ne.style.minWidth=de,ne.style.minHeight=de,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 te=ge(We,$e,"currentColor",1.5);te?ne.appendChild(te):ne.textContent="\u{1F4CE}",ne.addEventListener("click",Ct=>{Ct.preventDefault(),Oe==null||Oe.click()}),Ee.appendChild(ne);let he=(en=Q.buttonTooltipText)!=null?en:"Attach file",Fe=h("div","persona-send-button-tooltip");Fe.textContent=he,Ee.appendChild(Fe)}s.addEventListener("click",We=>{We.target!==w&&We.target!==R&&We.target!==E&&We.target!==G&&We.target!==ne&&We.target!==Ee&&o.focus()}),fe&&(fe.style.gap="8px",s.append(fe)),Oe&&s.append(Oe),s.append(o);let Ie=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Pe=h("div","persona-flex persona-items-center persona-gap-2");Ee&&Pe.append(Ee);let se=h("div","persona-flex persona-items-center persona-gap-1");G&&se.append(G),se.append(R),Ie.append(Pe,se),s.append(Ie);let be=(Qt=r==null?void 0:r.statusIndicator)!=null?Qt:{},ze=be.align==="left"?"persona-text-left":be.align==="center"?"persona-text-center":"persona-text-right",ce=h("div",`persona-mt-2 ${ze} persona-text-xs persona-text-persona-muted`);ce.setAttribute("data-persona-composer-status","");let ae=(tn=be.visible)!=null?tn:!0;ce.style.display=ae?"":"none";let Te=(_=be.idleText)!=null?_:"Online";if(be.idleLink){let We=h("a");We.href=be.idleLink,We.target="_blank",We.rel="noopener noreferrer",We.textContent=Te,We.style.color="inherit",We.style.textDecoration="none",ce.appendChild(We)}else ce.textContent=Te;return t.append(n,s,ce),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:R,micButton:E,micButtonWrapper:G,statusText:ce,attachmentButton:ne,attachmentButtonWrapper:Ee,attachmentInput:Oe,attachmentPreviewsContainer:fe,actionsRow:Ie,leftActions:Pe,rightActions:se}};var Pc=e=>{var c,d,p,m,f,v,A,x,C;let r=(d=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?d:!0;if(Zt(e)){let k=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),R=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return k.appendChild(R),{wrapper:k,panel:R}}if(!r){let k=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=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?m:"100%";return k.style.width=w,R.style.width="100%",k.appendChild(R),{wrapper:k,panel:R}}let n=(f=e==null?void 0:e.launcher)!=null?f:{},s=n.position&&Vn[n.position]?Vn[n.position]:Vn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((A=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?A:xn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(C=(x=e==null?void 0:e.launcher)==null?void 0:x.width)!=null?C:e==null?void 0:e.launcherWidth,u=i!=null?i:Bn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},Wc=(e,r=!0)=>{var x,C,k,R,w,M,W,E,G;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=(x=e==null?void 0:e.layout)==null?void 0:x.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=n?Bo(e,n,{showClose:r}):vr({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=Zt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(R=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?R:"Hello \u{1F44B}";let d=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");d.textContent=(M=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",u.append(c,d);let p=h("div","persona-flex persona-flex-col persona-gap-3"),m=(W=e==null?void 0:e.layout)==null?void 0:W.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,p);let v=Do({config:e}),A=((G=e==null?void 0:e.layout)==null?void 0:G.showFooter)!==!1;return s?eo(t,o,e):(o.header.style.display="none",eo(t,o,e)),t.append(a),A||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:p,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:d,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 vp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Cp=320,wp=320,Sp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Ap=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Cp}px`,c.style.maxHeight=`${wp}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 d=!1;s+=1,c.addEventListener("error",()=>{d||(d=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{d=!0}),vp(i.image)?(c.src=i.image,n.appendChild(c)):(d=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},to=()=>{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},Hc=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:to};if(r){let s=r(n);if(s!==null)return s}return to()},Ep=(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},Rc=(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},Tp=(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},Bc=(e,r,t)=>{var f,v,A,x,C,k;let n=(f=r.showCopy)!=null?f:!0,s=(v=r.showUpvote)!=null?v:!0,o=(A=r.showDownvote)!=null?A:!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=(x=r.visibility)!=null?x:"hover",i=(C=r.align)!=null?C:"right",u=(k=r.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],d={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${d} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=(R,w,M)=>{let W=Bt({icon:R,label:w,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return n&&p.appendChild(m("copy","Copy message","copy")),s&&p.appendChild(m("thumbs-up","Upvote","upvote")),o&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},No=(e,r,t,n,s,o)=>{var J,L,Q,we,ne,Ee,Oe;let a=t!=null?t:{},i=(J=a.layout)!=null?J:"bubble",u=a.avatar,c=a.timestamp,d=(L=u==null?void 0:u.show)!=null?L:!1,p=(Q=c==null?void 0:c.show)!=null?Q:!1,m=(we=u==null?void 0:u.position)!=null?we:"left",f=(ne=c==null?void 0:c.position)!=null?ne:"below",v=Tp(e.role,i),A=h("div",v.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let x=Sp(e),C=(Oe=(Ee=e.content)==null?void 0:Ee.trim())!=null?Oe:"",R=x.length>0&&C===ts,w=document.createElement("div");w.classList.add("persona-message-content");let M=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),W=null;if(R?(W=document.createElement("div"),W.innerHTML=M,W.style.display="none",w.appendChild(W)):w.innerHTML=M,p&&f==="inline"&&e.createdAt){let fe=Rc(e,c);fe.classList.add("persona-ml-2","persona-inline"),w.appendChild(fe)}if(x.length>0){let fe=Ap(x,!R&&!!C,()=>{R&&W&&(W.style.display="")});fe?A.appendChild(fe):R&&W&&(W.style.display="")}if(A.appendChild(w),p&&f==="below"&&e.createdAt){let fe=Rc(e,c);fe.classList.add("persona-mt-1"),A.appendChild(fe)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let fe=Hc("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);fe&&A.appendChild(fe)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let fe=Bc(e,n,s);A.appendChild(fe)}if(!d||e.role==="system")return A;let G=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),K=Ep(u,e.role);return m==="right"||m==="left"&&e.role==="user"?G.append(A,K):G.append(K,A),A.classList.remove("persona-max-w-[85%]"),A.classList.add("persona-max-w-[calc(85%-2.5rem)]"),G},Mp=(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}):No(e,r,t,n,s,o)};var no=new Set,kp=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Lp=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
16
- `):""},Dc=(e,r)=>{let t=no.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),o=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Ys=(e,r)=>{var M,W,E,G,K,J,L;let t=e.reasoning,n=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let s=(W=(M=r==null?void 0:r.features)==null?void 0:M.reasoningDisplay)!=null?W:{},o=s.expandable!==!1,a=o&&no.has(e.id),i=t.status!=="complete",u=Lp(e,(E=s.previewMaxLines)!=null?E:3),c=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),m="Thinking...",f=(K=(G=r==null?void 0:r.reasoning)==null?void 0:G.renderCollapsedSummary)==null?void 0:K.call(G,{message:e,reasoning:t,defaultSummary:m,previewText:u,isActive:i,config:r!=null?r:{}});typeof f=="string"&&f.trim()?(p.textContent=f,d.appendChild(p)):f instanceof HTMLElement?d.appendChild(f):(p.textContent=m,d.appendChild(p));let v=h("span","persona-text-xs persona-text-persona-primary");v.textContent=ac(t),d.appendChild(v),t.status==="complete"?p.style.display="none":p.style.display="";let A=null;if(o){A=h("div","persona-flex persona-items-center");let we=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);we?A.appendChild(we):A.textContent=a?"Hide":"Show";let ne=h("div","persona-flex persona-items-center persona-ml-auto");ne.append(A),c.append(d,ne)}else c.append(d);let x=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(x.setAttribute("data-persona-collapsed-preview","reasoning"),x.style.display="none",x.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&u){let Q=(L=(J=r==null?void 0:r.reasoning)==null?void 0:J.renderCollapsedPreview)==null?void 0:L.call(J,{message:e,reasoning:t,defaultPreview:u,isActive:i,config:r!=null?r:{}});kp(x,Q)||(x.textContent=u),x.style.display=""}if(!a&&i&&s.activeMinHeight&&(n.style.minHeight=s.activeMinHeight),!o)return n.append(c,x),n;let C=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");C.style.display=a?"":"none";let k=t.chunks.join(""),R=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return R.textContent=k||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),C.appendChild(R),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),A){A.innerHTML="";let we=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);we?A.appendChild(we):A.textContent=a?"Hide":"Show"}C.style.display=a?"":"none",x.style.display=a?"none":x.textContent||x.childNodes.length?"":"none"})(),n.append(c,x,C),n};var ro=new Set,Ip=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Pp=(e,r)=>{var o;let t=e.toolCall;if(!t)return"";let n=((o=t.chunks)!=null?o:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
17
- `);let s=Gr(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
18
- `):""},Wp=(e,r)=>{var c,d,p,m;let t=e.toolCall,n=(c=r==null?void 0:r.features)==null?void 0:c.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=Pp(e,(p=n==null?void 0:n.previewMaxLines)!=null?p:3),a=t?ic(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=a;return s==="tool-name"?u=((m=t.name)==null?void 0:m.trim())||a:s==="tool-preview"&&o&&(u=o),{summary:u,previewText:o,isActive:i}},Nc=(e,r,t)=>{var d;let n=ro.has(e),s=(d=t==null?void 0:t.toolCall)!=null?d:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",m=ge(n?"chevron-up":"chevron-down",16,p,2);m?c.appendChild(m):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Gs=(e,r)=>{var R,w,M,W,E,G;let t=e.toolCall,n=(R=r==null?void 0:r.toolCall)!=null?R:{},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=(M=(w=r==null?void 0:r.features)==null?void 0:w.toolCallDisplay)!=null?M:{},a=o.expandable!==!1,i=a&&ro.has(e.id),{summary:u,previewText:c,isActive:d}=Wp(e,r),p=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(p.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(p.style.paddingLeft=n.headerPaddingX,p.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(p.style.paddingTop=n.headerPaddingY,p.style.paddingBottom=n.headerPaddingY);let m=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let v=(E=n.renderCollapsedSummary)==null?void 0:E.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(W=o.collapsedMode)!=null?W:"tool-call",isActive:d,config:r!=null?r:{}});typeof v=="string"&&v.trim()?(f.textContent=v,m.appendChild(f)):v instanceof HTMLElement?m.appendChild(v):(f.textContent=u,m.appendChild(f));let A=null;if(a){A=h("div","persona-flex persona-items-center");let K=n.toggleTextColor||n.headerTextColor||"currentColor",J=ge(i?"chevron-up":"chevron-down",16,K,2);J?A.appendChild(J):A.textContent=i?"Hide":"Show";let L=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");L.append(A),p.append(m,L)}else p.append(m);let x=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(x.setAttribute("data-persona-collapsed-preview","tool"),x.style.display="none",x.style.whiteSpace="pre-wrap",!i&&d&&o.activePreview&&c){let K=(G=n.renderCollapsedPreview)==null?void 0:G.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:d,config:r!=null?r:{}});Ip(x,K)||(x.textContent=c),x.style.display=""}if(!i&&d&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,x),s;let C=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(C.style.display=i?"":"none",n.contentBackgroundColor&&(C.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(C.style.color=n.contentTextColor),n.contentPaddingX&&(C.style.paddingLeft=n.contentPaddingX,C.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(C.style.paddingTop=n.contentPaddingY,C.style.paddingBottom=n.contentPaddingY),t.name){let K=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?K.style.color=n.contentTextColor:n.headerTextColor&&(K.style.color=n.headerTextColor),K.textContent=t.name,C.appendChild(K)}if(t.args!==void 0){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Arguments";let L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(L.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(L.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(L.style.color=n.codeBlockTextColor),L.textContent=Gr(t.args),K.append(J,L),C.appendChild(K)}if(t.chunks&&t.chunks.length){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Activity";let L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(L.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(L.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(L.style.color=n.codeBlockTextColor),L.textContent=t.chunks.join(""),K.append(J,L),C.appendChild(K)}if(t.status==="complete"&&t.result!==void 0){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Result";let L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(L.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(L.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(L.style.color=n.codeBlockTextColor),L.textContent=Gr(t.result),K.append(J,L),C.appendChild(K)}if(t.status==="complete"&&typeof t.duration=="number"){let K=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(K.style.color=n.contentTextColor),K.textContent=`Duration: ${t.duration}ms`,C.appendChild(K)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),A){A.innerHTML="";let K=n.toggleTextColor||n.headerTextColor||"currentColor",J=ge(i?"chevron-up":"chevron-down",16,K,2);J?A.appendChild(J):A.textContent=i?"Hide":"Show"}C.style.display=i?"":"none",x.style.display=i?"none":x.textContent||x.childNodes.length?"":"none"})(),s.append(p,x,C),s};var Xs=(e,r)=>{var A,x,C,k,R,w,M,W,E,G,K,J;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=(A=n==null?void 0:n.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(x=n==null?void 0:n.borderColor)!=null?x:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(C=n==null?void 0:n.titleColor)!=null?C:"currentColor",d=ge(u,20,c,2);d&&i.appendChild(d);let p=h("div","persona-flex-1 persona-min-w-0"),m=h("div","persona-flex persona-items-center persona-gap-2"),f=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(k=n==null?void 0:n.title)!=null?k:"Approval Required",m.appendChild(f),!s){let L=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");L.setAttribute("data-approval-status",t.status),t.status==="approved"?(L.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",L.style.color="var(--persona-palette-colors-success-700, #15803d)",L.textContent="Approved"):t.status==="denied"?(L.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",L.style.color="var(--persona-palette-colors-error-700, #b91c1c)",L.textContent="Denied"):t.status==="timeout"&&(L.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",L.style.color="var(--persona-palette-colors-warning-700, #b45309)",L.textContent="Timeout"),m.appendChild(L)}p.appendChild(m);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,p.appendChild(v),t.parameters){let L=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&&(L.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(L.style.color=n.parameterTextColor),L.style.fontSize="0.75rem",L.style.lineHeight="1rem",L.textContent=Gr(t.parameters),p.appendChild(L)}if(s){let L=h("div","persona-flex persona-gap-2 persona-mt-2");L.setAttribute("data-approval-buttons","true");let Q=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");Q.type="button",Q.style.backgroundColor=(R=n==null?void 0:n.approveButtonColor)!=null?R:"var(--persona-approval-approve-bg, #22c55e)",Q.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",Q.setAttribute("data-approval-action","approve");let we=ge("shield-check",14,(M=n==null?void 0:n.approveButtonTextColor)!=null?M:"#ffffff",2);we&&(we.style.marginRight="4px",Q.appendChild(we));let ne=document.createTextNode((W=n==null?void 0:n.approveLabel)!=null?W:"Approve");Q.appendChild(ne);let Ee=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Ee.type="button",Ee.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",Ee.style.color=(G=n==null?void 0:n.denyButtonTextColor)!=null?G:"var(--persona-feedback-error, #dc2626)",Ee.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ee.setAttribute("data-approval-action","deny");let Oe=ge("shield-x",14,(K=n==null?void 0:n.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);Oe&&(Oe.style.marginRight="4px",Ee.appendChild(Oe));let fe=document.createTextNode((J=n==null?void 0:n.denyLabel)!=null?J:"Deny");Ee.appendChild(fe),L.append(Q,Ee),p.appendChild(L)}return a.append(i,p),o.appendChild(a),o};var Fc=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(f=>f.role==="user"))return;let d=document.createDocumentFragment(),p=s?s.isStreaming():!1,m=f=>{switch(f){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(f=>{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=f,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=m(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(f))}),d.appendChild(v),r.push(v)}),e.appendChild(d)}}};var Fo=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 Oo=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 oo(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Rp={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)"}},Hp={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Bp=["flowName","stepName","reasoningText","text","name","tool","toolName"],Dp=100;function Np(e,r){let t={...Rp,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Hp}function Fp(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Op(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 $p(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 _p(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 jp(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 zp(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function Ks(e,r,t,n,s,o,a,i){var m;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");oo(c,(m=n.classNames)==null?void 0:m.eventRow);let d=a.find(f=>f.renderEventStreamRow);if(d!=null&&d.renderEventStreamRow&&i){let f=d.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(f)return c.appendChild(f),c}return c.appendChild(p()),c;function p(){var Q,we;let f=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 A=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),x=ge(u?"chevron-down":"chevron-right","14px","currentColor",2);x&&A.appendChild(x);let C=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(Q=n.timestampFormat)!=null?Q:"relative";C.textContent=k==="relative"?Fp(e.timestamp,t):Op(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=Np(e.type,n.badgeColors),M=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");M.style.backgroundColor=w.bg,M.style.color=w.text,M.style.borderColor=w.text+"50",M.textContent=e.type;let W=(we=n.descriptionFields)!=null?we:Bp,E=$p(e.payload,W),G=null;E&&(G=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),G.textContent=E);let K=h("div","persona-flex-1 persona-min-w-0"),J=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"),L=ge("clipboard","12px","currentColor",1.5);return L&&J.appendChild(L),J.addEventListener("click",async ne=>{ne.stopPropagation(),await _p(jp(e)),J.innerHTML="";let Ee=ge("check","12px","currentColor",1.5);Ee&&J.appendChild(Ee),setTimeout(()=>{J.innerHTML="";let Oe=ge("clipboard","12px","currentColor",1.5);Oe&&J.appendChild(Oe)},1500)}),v.appendChild(A),v.appendChild(C),R&&v.appendChild(R),v.appendChild(M),G&&v.appendChild(G),v.appendChild(K),v.appendChild(J),f.appendChild(v),u&&f.appendChild(zp(e,a,i)),f}}function Oc(e){var f,v,A,x,C;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(f=s==null?void 0:s.features)==null?void 0:f.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(A=a==null?void 0:a.label)!=null?A:"",d=(C=(x=s==null?void 0:s.features)==null?void 0:x.eventStream)!=null?C:{},p=o.find(k=>k.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let k=p.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>m().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return m();function m(){let k=d.classNames,R=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");oo(R,k==null?void 0:k.panel);let w=[],M="",W="",E=null,G=[],K={},J=0,L=cs(),Q=0,we=0,ne=!1,Ee=null,Oe=!1,fe=0,Ie=new Set,Pe=new Map,se="",be="",ze=null,ce,ae,Te,Ne,lt;function Tt(){let te=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),he=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");oo(he,k==null?void 0:k.headerBar);let Fe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fe.textContent="Events",ce=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"),ce.textContent="0";let Ct=h("div","persona-flex-1");ae=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 _t=h("option","");_t.value="",_t.textContent="All events",ae.appendChild(_t),Te=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"),Te.type="button",Te.title="Copy All";let jt=ge("clipboard-copy","12px","currentColor",1.5);jt&&Te.appendChild(jt);let ht=h("span","persona-text-xs");ht.textContent="Copy All",Te.appendChild(ht),he.appendChild(Fe),he.appendChild(ce),he.appendChild(Ct),he.appendChild(ae),he.appendChild(Te);let Ze=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");oo(Ze,k==null?void 0:k.searchBar);let yt=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),Ue=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");yt&&Ue.appendChild(yt),Ne=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"),oo(Ne,k==null?void 0:k.searchInput),Ne.type="text",Ne.placeholder="Search event payloads...",lt=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"),lt.type="button",lt.style.display="none";let zt=ge("x","12px","currentColor",2);return zt&&lt.appendChild(zt),Ze.appendChild(Ue),Ze.appendChild(Ne),Ze.appendChild(lt),te.appendChild(he),te.appendChild(Ze),te}let q,F=o.find(te=>te.renderEventStreamToolbar);if(F!=null&&F.renderEventStreamToolbar&&s){let te=F.renderEventStreamToolbar({config:s,defaultRenderer:()=>Tt(),eventCount:r.getSize(),filteredCount:0,onFilterChange:he=>{M=he,Jt(),De()},onSearchChange:he=>{W=he,Jt(),De()}});q=te!=null?te:Tt()}else q=Tt();let ie=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");ie.style.display="none";let j=h("div","persona-flex-1 persona-min-h-0 persona-relative"),U=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");U.style.height="100%";let re=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");oo(re,k==null?void 0:k.scrollIndicator),re.style.display="none",re.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let _e=ge(u,"14px","currentColor",2);_e&&re.appendChild(_e);let Z=h("span","");Z.textContent=c,re.appendChild(Z);let ee=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ee.style.display="none",j.appendChild(U),j.appendChild(ee),j.appendChild(re),R.setAttribute("tabindex","0"),R.appendChild(q),R.appendChild(ie),R.appendChild(j);function kt(){let te=r.getAll(),he={};for(let ht of te)he[ht.type]=(he[ht.type]||0)+1;let Fe=Object.keys(he).sort(),Ct=Fe.length!==G.length||!Fe.every((ht,Ze)=>ht===G[Ze]),_t=!Ct&&Fe.some(ht=>he[ht]!==K[ht]),dt=te.length!==Object.values(K).reduce((ht,Ze)=>ht+Ze,0);if(!Ct&&!_t&&!dt||(G=Fe,K=he,!ae))return;let jt=ae.value;if(ae.options[0].textContent="All events",Ct){for(;ae.options.length>1;)ae.remove(1);for(let ht of Fe){let Ze=h("option","");Ze.value=ht,Ze.textContent=`${ht} (${he[ht]||0})`,ae.appendChild(Ze)}jt&&Fe.includes(jt)?ae.value=jt:jt&&(ae.value="",M="")}else for(let ht=1;ht<ae.options.length;ht++){let Ze=ae.options[ht];Ze.textContent=`${Ze.value} (${he[Ze.value]||0})`}}function ct(){let te=r.getAll();if(M&&(te=te.filter(he=>he.type===M)),W){let he=W.toLowerCase();te=te.filter(Fe=>Fe.type.toLowerCase().includes(he)||Fe.payload.toLowerCase().includes(he))}return te}function Dt(){return M!==""||W!==""}function Jt(){J=0,Q=0,L.resume(),re.style.display="none"}function je(te){Ie.has(te)?Ie.delete(te):Ie.add(te),ze=te;let he=U.scrollTop,Fe=L.isFollowing();Oe=!0,L.pause(),De(),U.scrollTop=he,Fe&&L.resume(),Oe=!1}function le(){return Wo(U,50)}function De(){we=Date.now(),ne=!1,kt();let te=r.getEvictedCount();te>0?(ie.textContent=`${te.toLocaleString()} older events truncated`,ie.style.display=""):ie.style.display="none",w=ct();let he=w.length,Fe=r.getSize()>0;ce&&(ce.textContent=String(r.getSize())),he===0&&Fe&&Dt()?(ee.textContent=W?`No events matching '${W}'`:"No events matching filter",ee.style.display="",U.style.display="none"):(ee.style.display="none",U.style.display=""),Te&&(Te.title=Dt()?`Copy Filtered (${he})`:"Copy All"),i&&!L.isFollowing()&&he>J&&(Q+=he-J,Z.textContent=c?`${c}${Q>0?` (${Q})`:""}`:"",re.style.display=""),J=he;let Ct=r.getAll(),_t=Ct.length>0?Ct[0].timestamp:0,dt=new Set(w.map(Ze=>Ze.id));for(let Ze of Ie)dt.has(Ze)||Ie.delete(Ze);let jt=M!==se||W!==be,ht=Pe.size===0&&w.length>0;if(jt||ht||w.length===0){U.innerHTML="",Pe.clear();let Ze=document.createDocumentFragment();for(let yt=0;yt<w.length;yt++){let Ue=Ks(w[yt],yt,_t,d,Ie,je,o,s);Pe.set(w[yt].id,Ue),Ze.appendChild(Ue)}U.appendChild(Ze),se=M,be=W,ze=null}else{if(ze!==null){let yt=Pe.get(ze);if(yt&&yt.parentNode===U){let Ue=w.findIndex(zt=>zt.id===ze);if(Ue>=0){let zt=Ks(w[Ue],Ue,_t,d,Ie,je,o,s);U.insertBefore(zt,yt),yt.remove(),Pe.set(ze,zt)}}ze=null}let Ze=new Set(w.map(yt=>yt.id));for(let[yt,Ue]of Pe)Ze.has(yt)||(Ue.remove(),Pe.delete(yt));for(let yt=0;yt<w.length;yt++){let Ue=w[yt];if(!Pe.has(Ue.id)){let zt=Ks(Ue,yt,_t,d,Ie,je,o,s);Pe.set(Ue.id,zt),U.appendChild(zt)}}}L.isFollowing()&&(U.scrollTop=U.scrollHeight)}function It(){if(Date.now()-we>=Dp){Ee!==null&&(cancelAnimationFrame(Ee),Ee=null),De();return}ne||(ne=!0,Ee=requestAnimationFrame(()=>{Ee=null,De()}))}let Pt=(te,he)=>{if(!Te)return;Te.innerHTML="";let Fe=ge(te,"12px","currentColor",1.5);Fe&&Te.appendChild(Fe);let Ct=h("span","persona-text-xs");Ct.textContent="Copy All",Te.appendChild(Ct),setTimeout(()=>{Te.innerHTML="";let _t=ge("clipboard-copy","12px","currentColor",1.5);_t&&Te.appendChild(_t);let dt=h("span","persona-text-xs");dt.textContent="Copy All",Te.appendChild(dt),Te.disabled=!1},he)},rt=async()=>{if(Te){Te.disabled=!0;try{let te;Dt()?te=w:t?(te=await t(),te.length===0&&(te=r.getAll())):te=r.getAll();let he=te.map(Fe=>{try{return JSON.parse(Fe.payload)}catch{return Fe.payload}});await navigator.clipboard.writeText(JSON.stringify(he,null,2)),Pt("check",1500)}catch{Pt("x",1500)}}},ot=()=>{ae&&(M=ae.value,Jt(),De())},en=()=>{!Ne||!lt||(lt.style.display=Ne.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{W=Ne.value,Jt(),De()},150))},Qt=()=>{!Ne||!lt||(Ne.value="",W="",lt.style.display="none",E&&clearTimeout(E),Jt(),De())},tn=()=>{if(Oe)return;let te=U.scrollTop,{action:he,nextLastScrollTop:Fe}=ds({following:L.isFollowing(),currentScrollTop:te,lastScrollTop:fe,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});fe=Fe,he==="resume"?(L.resume(),Q=0,re.style.display="none"):he==="pause"&&(L.pause(),i&&(Z.textContent=c,re.style.display=""))},_=te=>{let he=ps({following:L.isFollowing(),deltaY:te.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});he==="pause"?(L.pause(),i&&(Z.textContent=c,re.style.display="")):he==="resume"&&(L.resume(),Q=0,re.style.display="none")},We=()=>{i&&(U.scrollTop=U.scrollHeight,L.resume(),Q=0,re.style.display="none")},de=te=>{let he=te.target;if(!he||he.closest("button"))return;let Fe=he.closest("[data-event-id]");if(!Fe)return;let Ct=Fe.getAttribute("data-event-id");Ct&&je(Ct)},ft=te=>{if((te.metaKey||te.ctrlKey)&&te.key==="f"){te.preventDefault(),Ne==null||Ne.focus(),Ne==null||Ne.select();return}te.key==="Escape"&&(Ne&&document.activeElement===Ne?(Qt(),Ne.blur(),R.focus()):n&&n())};Te&&Te.addEventListener("click",rt),ae&&ae.addEventListener("change",ot),Ne&&Ne.addEventListener("input",en),lt&&lt.addEventListener("click",Qt),U.addEventListener("scroll",tn),U.addEventListener("wheel",_,{passive:!0}),U.addEventListener("click",de),re.addEventListener("click",We),R.addEventListener("keydown",ft);function $e(){E&&clearTimeout(E),Ee!==null&&(cancelAnimationFrame(Ee),Ee=null),ne=!1,Pe.clear(),Te&&Te.removeEventListener("click",rt),ae&&ae.removeEventListener("change",ot),Ne&&Ne.removeEventListener("input",en),lt&&lt.removeEventListener("click",Qt),U.removeEventListener("scroll",tn),U.removeEventListener("wheel",_),U.removeEventListener("click",de),re.removeEventListener("click",We),R.removeEventListener("keydown",ft)}return{element:R,update:It,destroy:$e}}}function $c(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let d=document.createElement("div");d.className="persona-truncate persona-text-sm persona-font-medium",d.style.color="var(--persona-text, #1f2937)",d.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let m=document.createElement("span");m.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",m.style.backgroundColor="var(--persona-primary, #171717)",m.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(m);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(f)}else p.textContent=a;if(c.append(d,p),i.append(u,c),s==="complete"){let m=document.createElement("button");m.type="button",m.textContent="Download",m.title=`Download ${t}`,m.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-text, #1f2937)",m.style.backgroundColor="transparent",m.style.cursor="pointer",m.setAttribute("data-download-artifact",n),i.append(m)}return i}var _c=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",d=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>$c(e,r)});if(d)return d}return $c(e,r)};var Zs=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)})}},Cr=new Zs;Cr.register("PersonaArtifactCard",_c);function qp(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 jc(e,r){var Te,Ne,lt,Tt;let t=(Ne=(Te=e.features)==null?void 0:Te.artifacts)==null?void 0:Ne.layout,s=((lt=t==null?void 0:t.toolbarPreset)!=null?lt:"default")==="document",o=(Tt=t==null?void 0:t.panePadding)==null?void 0:Tt.trim(),a=e.markdown?Yr(e.markdown):null,i=Ao(e.sanitize),u=q=>{let F=a?a(q):So(q);return i?i(F):F},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,d=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),L==null||L.hide()};c&&c.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let m=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");m.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&m.classList.add("persona-artifact-toolbar-document");let f=h("span","persona-text-xs persona-font-medium persona-truncate");f.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 q;d(),(q=r.onDismiss)==null||q.call(r)});let A="rendered",x=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?Bt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Bt({icon:"eye",label:"Rendered view"}),k=s?Bt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Bt({icon:"code-2",label:"Source"}),R=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,M=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,W=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(M&&W&&W.length>0),G=null,K,J=null,L=null;if(s&&(w||M)&&!E){if(K=w?gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),M){let q=ge("chevron-down",14,"currentColor",2);q&&K.appendChild(q)}}else s&&E?(G=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),K=w?gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),J=Bt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),G.append(K,J)):s?K=Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):K=Bt({icon:"copy",label:"Copy"});let Q=s?Bt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Bt({icon:"refresh-cw",label:"Refresh"}),we=s?Bt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Bt({icon:"x",label:"Close"}),ne=()=>{var U,re,_e;let q=(U=se.find(Z=>Z.id===be))!=null?U:se[se.length-1],F=(re=q==null?void 0:q.id)!=null?re:null,ie=(q==null?void 0:q.artifactType)==="markdown"&&(_e=q.markdown)!=null?_e:"",j=q?JSON.stringify({component:q.component,props:q.props},null,2):"";return{markdown:ie,jsonPayload:j,id:F}},Ee=async()=>{var U;let{markdown:q,jsonPayload:F}=ne(),ie=(U=se.find(re=>re.id===be))!=null?U:se[se.length-1],j=(ie==null?void 0:ie.artifactType)==="markdown"?q:ie?F:"";try{await navigator.clipboard.writeText(j)}catch{}};if(K.addEventListener("click",async()=>{let q=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(q&&E){let{markdown:F,jsonPayload:ie,id:j}=ne();try{await q({actionId:"primary",artifactId:j,markdown:F,jsonPayload:ie})}catch{}return}await Ee()}),J&&(W!=null&&W.length)){let q=()=>{var ie;return(ie=p.closest("[data-persona-root]"))!=null?ie:document.body},F=()=>{L=Nr({items:W.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:j,jsonPayload:U,id:re}=ne(),_e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:ie,artifactId:re,markdown:j,jsonPayload:U}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(j):ie==="json"||ie==="source"?await navigator.clipboard.writeText(U):await navigator.clipboard.writeText(j||U)}catch{}},anchor:G!=null?G:J,position:"bottom-right",portal:q()})};p.isConnected?F():requestAnimationFrame(F),J.addEventListener("click",ie=>{ie.stopPropagation(),L==null||L.toggle()})}Q.addEventListener("click",async()=>{var q;try{await((q=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:q.call(t))}catch{}ce()}),we.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});let Oe=()=>{s&&(C.setAttribute("aria-pressed",A==="rendered"?"true":"false"),k.setAttribute("aria-pressed",A==="source"?"true":"false"))};C.addEventListener("click",()=>{A="rendered",Oe(),ce()}),k.addEventListener("click",()=>{A="source",Oe(),ce()});let fe=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?(m.replaceChildren(),x.append(C,k),G?R.append(G,Q,we):R.append(K,Q,we),m.append(x,fe,R),Oe()):(m.appendChild(f),m.appendChild(v)),o&&(m.style.paddingLeft=o,m.style.paddingRight=o);let Ie=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"),Pe=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Ie.style.paddingLeft=o,Ie.style.paddingRight=o,Pe.style.padding=o),p.appendChild(m),p.appendChild(Ie),p.appendChild(Pe);let se=[],be=null,ze=!1,ce=()=>{var j,U,re,_e;let q=s&&se.length<=1;Ie.classList.toggle("persona-hidden",q),Ie.replaceChildren();for(let Z of se){let ee=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");ee.type="button",ee.textContent=Z.title||Z.id.slice(0,8),Z.id===be&&ee.classList.add("persona-bg-persona-container","persona-border-persona-border"),ee.addEventListener("click",()=>r.onSelect(Z.id)),Ie.appendChild(ee)}Pe.replaceChildren();let F=be&&se.find(Z=>Z.id===be)||se[se.length-1];if(!F)return;if(s){let Z=F.artifactType==="markdown"?"MD":(j=F.component)!=null?j:"Component",kt=(F.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";fe.textContent=`${kt} \xB7 ${Z}`}else f.textContent="Artifacts";if(F.artifactType==="markdown"){if(s&&A==="source"){let ee=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ee.textContent=(U=F.markdown)!=null?U:"",Pe.appendChild(ee);return}let Z=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Z.innerHTML=u((re=F.markdown)!=null?re:""),Pe.appendChild(Z);return}let ie=F.component?Cr.get(F.component):void 0;if(ie){let ee={message:{id:F.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let kt=ie((_e=F.props)!=null?_e:{},ee);if(kt){Pe.appendChild(kt);return}}catch{}}Pe.appendChild(qp(F))},ae=()=>{var F;let q=se.length>0;if(p.classList.toggle("persona-hidden",!q),c){let ie=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,U=((F=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?F:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;q&&U&&ze?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(q){var F,ie,j;se=q.artifacts,be=(j=(ie=q.selectedId)!=null?ie:(F=q.artifacts[q.artifacts.length-1])==null?void 0:F.id)!=null?j:null,se.length>0&&(ze=!0),ce(),ae()},setMobileOpen(q){ze=q,!q&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ae()}}}function Dn(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 zc(e,r){var o,a,i,u;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Dn(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Up(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 fs(e,r){var u,c,d,p,m,f,v,A,x,C;if(!Dn(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"),Up(e),zc(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(d=t==null?void 0:t.splitGap)!=null?d:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(m=t==null?void 0:t.paneMaxWidth)!=null?m:"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=(f=t==null?void 0:t.paneBackground)==null?void 0:f.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=(A=t==null?void 0:t.documentToolbarIconColor)==null?void 0:A.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(x=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:x.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"),zc(e,r)}var qc=["panel","seamless"];function hs(e,r){var i,u,c,d,p,m;for(let f of qc)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!Dn(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=qc.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(d=t==null?void 0:t.paneBorderRadius)==null?void 0:d.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((m=t.unifiedSplitOuterRadius)==null?void 0:m.trim())||o;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Uc(e,r){var t,n,s;return!r||!Dn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Vp(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 Jp(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 Yp(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Gp(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Vc(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 Jc(e,r,t,n,s,o){let a=Vp(s,200),i=Gp(r,t,n,200);i=Math.max(a,i);let u=Jp(o);return u!==null&&(i=Math.min(i,u)),Yp(e,a,i)}var Yc={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"}},Qs=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,A,x;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(A=Yc[a])!=null?A:Yc.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let C=h("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,u.appendChild(C)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var W,E;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${r.id}-${a}-${C.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=C.label,k.appendChild(R);let w=(W=C.type)!=null?W:"text",M;w==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=w),M.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",M.id=`${r.id}-${a}-${C.name}`,M.name=C.name,M.placeholder=(E=C.placeholder)!=null?E:"",C.required&&(M.required=!0),k.appendChild(M),d.appendChild(k)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),m=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=(x=i.submitLabel)!=null?x:"Submit",p.appendChild(m),p.appendChild(f),d.appendChild(p),o.replaceChildren(u,d),d.addEventListener("submit",async C=>{var M,W;C.preventDefault();let k=(M=t.formEndpoint)!=null?M:"/form",R=new FormData(d),w={};R.forEach((E,G)=>{w[G]=E}),w.type=a,f.disabled=!0,m.textContent="Submitting\u2026";try{let E=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let G=await E.json();m.textContent=(W=G.message)!=null?W:"Thanks! We'll be in touch soon.",G.success&&G.nextPrompt&&await n.sendMessage(String(G.nextPrompt))}catch(E){m.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var ea=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},ys=new ea;var Gc=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Xp=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Kp=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},bs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Xp(e),t=Kp(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}},ta=e=>typeof e=="string"?e:e==null?"":String(e),so={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ta(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ta(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:ta(t.text)}}},Xc=e=>Array.isArray(e)?e.map(r=>String(r)):[],xs=e=>{let r=new Set(Xc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Xc(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,d)=>c||(d==null?void 0:d({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let d=()=>{e.emit("action:resubmit",u)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:t}};var Zp=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}},Qp=e=>e.map(r=>({...r,streaming:!1})),na=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Zp(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Qp(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 eu,STR as tu,OBJ as nu}from"partial-json";function ru(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function ou(e,r){if(!ru(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 ra(){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=eu(t,tu|nu),o=ou(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function su(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function oa(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Cr.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 au(){let e=ra();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function sa(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 aa(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 iu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ia(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=iu}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,f.appendChild(v);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,f.appendChild(A),m.appendChild(f);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-csat",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];for(let W=1;W<=5;W++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${c[W-1]}`),E.title=c[W-1],E.dataset.rating=String(W),E.innerHTML=`
15
+ `,t.addEventListener("click",r);let n=o=>{var H,w,M,W,T,G,K,J,I,Q,Ce,re,Ae,Ne;let a=(H=o.launcher)!=null?H:{},i=en(o),u=t.querySelector("[data-role='launcher-title']");if(u){let he=(w=a.title)!=null?w:"Chat Assistant";u.textContent=he,u.setAttribute("title",he)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let he=(M=a.subtitle)!=null?M:"Get answers fast";c.textContent=he,c.setAttribute("title",he)}let d=t.querySelector(".persona-flex-col");d&&(a.textHidden||i?d.style.display="none":d.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let he=(W=a.agentIconSize)!=null?W:"40px";if(p.style.height=he,p.style.width=he,p.innerHTML="",a.agentIconName){let ke=parseFloat(he)||24,Le=me(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(p.appendChild(Le),p.style.display=""):(p.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(G=a.agentIconText)!=null?G:"\u{1F4AC}",p.style.display="")}let g=t.querySelector("[data-role='launcher-image']");if(g){let he=(K=a.agentIconSize)!=null?K:"40px";g.style.height=he,g.style.width=he,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=t.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let he=(J=a.callToActionIconSize)!=null?J:"32px";f.style.height=he,f.style.width=he,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let ke=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,ke=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Le=parseFloat(he)||24,ae=Math.max(Le-ke,8),xe=me(a.callToActionIconName,ae,"currentColor",2);xe?f.appendChild(xe):f.textContent=(I=a.callToActionIconText)!=null?I:"\u2197"}else f.textContent=(Q=a.callToActionIconText)!=null?Q:"\u2197"}let v=a.position&&Yn[a.position]?Yn[a.position]:Yn["bottom-right"],E="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",x="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?x:`${E} ${v}`,i||(t.style.zIndex=String((Ce=a.zIndex)!=null?Ce:vn));let C="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(re=a.border)!=null?re:C,t.style.boxShadow=(Ae=a.shadow)!=null?Ae:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Ne=a.collapsedMaxWidth)!=null?Ne:"",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 Cn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Sr=e=>{var J,I,Q,Ce,re,Ae,Ne,he,ke,Le,ae,xe,je,de,ie,Ee,Be,it,Et,q,F,le,_,V,oe,Oe,Z,te,kt,lt,Nt,Xt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(J=r==null?void 0:r.launcher)!=null?J:{},o=(I=s.headerIconSize)!=null?I:"48px",a=(Q=s.closeButtonSize)!=null?Q:"32px",i=(Ce=s.closeButtonPlacement)!=null?Ce:"inline",u=(re=s.headerIconHidden)!=null?re:!1,c=s.headerIconName,d=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(d.style.height=o,d.style.width=o,d.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",d.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let $e=parseFloat(o)||24,ce=me(c,$e*.6,"currentColor",1);ce?d.replaceChildren(ce):d.textContent=(Ne=(Ae=r==null?void 0:r.launcher)==null?void 0:Ae.agentIconText)!=null?Ne:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let $e=h("img");$e.src=r.launcher.iconUrl,$e.alt="",$e.className="persona-rounded-xl persona-object-cover",$e.style.height=o,$e.style.width=o,d.replaceChildren($e)}else d.textContent=(Le=(ke=r==null?void 0:r.launcher)==null?void 0:ke.agentIconText)!=null?Le:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=h("span","persona-text-base persona-font-semibold");g.style.color=Cn.titleColor,g.textContent=(xe=(ae=r==null?void 0:r.launcher)==null?void 0:ae.title)!=null?xe:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Cn.subtitleColor,f.textContent=(de=(je=r==null?void 0:r.launcher)==null?void 0:je.subtitle)!=null?de:"Here to help you get answers fast",p.append(g,f),u?n.append(p):n.append(d,p);let v=(ie=s.clearChat)!=null?ie:{},E=(Ee=v.enabled)!=null?Ee:!0,x=(Be=v.placement)!=null?Be:"inline",C=null,k=null;if(E){let $e=(it=v.size)!=null?it:"32px",ce=(Et=v.iconName)!=null?Et:"refresh-cw",He=(q=v.iconColor)!=null?q:"",Pt=(F=v.backgroundColor)!=null?F:"",Wt=(le=v.borderWidth)!=null?le:"",ot=(_=v.borderColor)!=null?_:"",st=(V=v.borderRadius)!=null?V:"",rn=(oe=v.paddingX)!=null?oe:"",tn=(Oe=v.paddingY)!=null?Oe:"",on=(Z=v.tooltipText)!=null?Z:"Clear chat",j=(te=v.showTooltip)!=null?te:!0;k=h("div",x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),x==="top-right"&&(k.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=$e,C.style.width=$e,C.type="button",C.setAttribute("aria-label",on),C.style.color=He||Cn.actionIconColor;let Ie=me(ce,"20px","currentColor",1);if(Ie&&C.appendChild(Ie),Pt&&(C.style.backgroundColor=Pt,C.classList.remove("hover:persona-bg-gray-100")),Wt||ot){let ue=Wt||"0px",gt=ot||"transparent";C.style.border=`${ue} solid ${gt}`,C.classList.remove("persona-border-none")}if(st&&(C.style.borderRadius=st,C.classList.remove("persona-rounded-full")),rn?(C.style.paddingLeft=rn,C.style.paddingRight=rn):(C.style.paddingLeft="",C.style.paddingRight=""),tn?(C.style.paddingTop=tn,C.style.paddingBottom=tn):(C.style.paddingTop="",C.style.paddingBottom=""),k.appendChild(C),j&&on&&C&&k){let ue=null,gt=()=>{if(ue||!C)return;let ne=C.ownerDocument,ye=ne.body;if(!ye)return;ue=Qn(ne,"div","persona-clear-chat-tooltip"),ue.textContent=on;let De=Qn(ne,"div");De.className="persona-clear-chat-tooltip-arrow",ue.appendChild(De);let xt=C.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(Cr),ue.style.left=`${xt.left+xt.width/2}px`,ue.style.top=`${xt.top-8}px`,ue.style.transform="translate(-50%, -100%)",ye.appendChild(ue)},Fe=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};k.addEventListener("mouseenter",gt),k.addEventListener("mouseleave",Fe),C.addEventListener("focus",gt),C.addEventListener("blur",Fe),k._cleanupTooltip=()=>{Fe(),k&&(k.removeEventListener("mouseenter",gt),k.removeEventListener("mouseleave",Fe)),C&&(C.removeEventListener("focus",gt),C.removeEventListener("blur",Fe))}}x==="inline"&&n.appendChild(k)}let H=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":E&&x==="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 M=(kt=s.closeButtonTooltipText)!=null?kt:"Close chat",W=(lt=s.closeButtonShowTooltip)!=null?lt:!0;w.setAttribute("aria-label",M),w.style.display=t?"":"none";let T=(Nt=s.closeButtonIconName)!=null?Nt:"x",G=(Xt=s.closeButtonIconText)!=null?Xt:"\xD7";w.style.color=s.closeButtonColor||Cn.actionIconColor;let K=me(T,"20px","currentColor",1);if(K?w.appendChild(K):w.textContent=G,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 $e=s.closeButtonBorderWidth||"0px",ce=s.closeButtonBorderColor||"transparent";w.style.border=`${$e} solid ${ce}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),H.appendChild(w),W&&M){let $e=null,ce=()=>{if($e)return;let Pt=w.ownerDocument,Wt=Pt.body;if(!Wt)return;$e=Qn(Pt,"div","persona-clear-chat-tooltip"),$e.textContent=M;let ot=Qn(Pt,"div");ot.className="persona-clear-chat-tooltip-arrow",$e.appendChild(ot);let st=w.getBoundingClientRect();$e.style.position="fixed",$e.style.zIndex=String(Cr),$e.style.left=`${st.left+st.width/2}px`,$e.style.top=`${st.top-8}px`,$e.style.transform="translate(-50%, -100%)",Wt.appendChild($e)},He=()=>{$e&&$e.parentNode&&($e.parentNode.removeChild($e),$e=null)};H.addEventListener("mouseenter",ce),H.addEventListener("mouseleave",He),w.addEventListener("focus",ce),w.addEventListener("blur",He),H._cleanupTooltip=()=>{He(),H.removeEventListener("mouseenter",ce),H.removeEventListener("mouseleave",He),w.removeEventListener("focus",ce),w.removeEventListener("blur",He)}}return i!=="top-right"&&n.appendChild(H),{header:n,iconHolder:d,headerTitle:g,headerSubtitle:f,closeButton:w,closeButtonWrapper:H,clearChatButton:C,clearChatButtonWrapper:k}},to=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function $r(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Cr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of r){if(f.dividerBefore){let x=document.createElement("hr");a.appendChild(x)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let x=me(f.icon,16,"currentColor",1.5);x&&v.appendChild(x)}let E=document.createElement("span");E.textContent=f.label,v.appendChild(E),v.addEventListener("click",x=>{x.stopPropagation(),d(),t(f.id)}),a.appendChild(v)}let i=null;function u(){if(!o)return;let f=n.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!n.contains(v.target)&&d()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function d(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?c():d()}function g(){d(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:d,toggle:p,destroy:g}}function Dt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=me(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[d,p]of Object.entries(i))u.setAttribute(d,p);return u}function hs(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let d=h("button",c);if(d.type="button",d.setAttribute("aria-label",t),r){let g=me(r,o!=null?o:14,"currentColor",2);g&&d.appendChild(g)}let p=h("span");if(p.textContent=t,d.appendChild(p),i&&d.addEventListener("click",i),u)for(let[g,f]of Object.entries(u))d.setAttribute(g,f);return d}function ys(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let d of i)d.btn.setAttribute("aria-pressed",d.id===a?"true":"false")}for(let d of r){let p;d.icon?p=Dt({icon:d.icon,label:d.label,onClick:()=>{a=d.id,u(),n(d.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",d.label),p.title=d.label,p.textContent=d.label,p.addEventListener("click",()=>{a=d.id,u(),n(d.id)})),p.setAttribute("aria-pressed",d.id===a?"true":"false"),i.push({id:d.id,btn:p}),o.appendChild(p)}function c(d){a=d,u()}return{element:o,setSelected:c}}function Gs(e){var f,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let d=h("span","persona-combo-btn-label");d.textContent=r,c.appendChild(d);let p=me(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",c.appendChild(p)),u&&(c.style.borderRadius=(f=u.borderRadius)!=null?f:"10px",c.style.padding=(v=u.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var E,x;c.style.backgroundColor=(E=u.background)!=null?E:"",c.style.borderColor=(x=u.border)!=null?x:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=$r({items:n,onSelect:E=>{c.setAttribute("aria-expanded","false"),s(E)},anchor:c,position:o,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",E=>{E.stopPropagation();let x=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),g.toggle()}),c.addEventListener("keydown",E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),c.click())}),{element:c,setLabel:E=>{d.textContent=E,c.setAttribute("aria-label",E)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let E=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var jc=e=>{var n;let r=Sr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return r};function Hp(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=me(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=$r({items:a.menuItems,onSelect:d=>t==null?void 0:t(d),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",d=>{d.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var zc=e=>{var k,H,w,M,W,T,G,K,J;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(k=r==null?void 0:r.launcher)!=null?k:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=s==null?void 0:s.titleMenu,c,d;if(u)c=Gs({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=Cn.titleColor,d=(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"),d=h("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Cn.titleColor,d.textContent=(M=a.title)!=null?M:"Chat Assistant",c.appendChild(d),Hp(c,s==null?void 0:s.trailingActions,(W=s==null?void 0:s.onAction)!=null?W:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let Q=s.onTitleClick;c.addEventListener("click",Ce=>{Ce.target.closest("button")||Q()}),c.addEventListener("keydown",Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),Q())})}let I=s==null?void 0:s.titleRowHover;I&&(c.style.borderRadius=(T=I.borderRadius)!=null?T:"10px",c.style.padding=(G=I.padding)!=null?G:"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 Q,Ce;c.style.backgroundColor=(Q=I.background)!=null?Q:"",c.style.borderColor=(Ce=I.border)!=null?Ce:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let p=(K=a.closeButtonSize)!=null?K:"32px",g=h("div",""),f=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");f.style.height=p,f.style.width=p,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=t?"":"none",f.style.color=a.closeButtonColor||Cn.actionIconColor;let v=(J=a.closeButtonIconName)!=null?J:"x",E=me(v,"20px","currentColor",2);E?f.appendChild(E):f.textContent="\xD7",n&&f.addEventListener("click",n),g.appendChild(f),i.appendChild(g);let x=h("div");x.style.display="none";let C=h("span");return C.style.display="none",{header:i,iconHolder:x,headerTitle:d,headerSubtitle:C,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Xs={default:jc,minimal:zc},qc=e=>{var r;return(r=Xs[e])!=null?r:Xs.default},No=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),d=h("div");d.style.display="none";let p=h("span"),g=h("span"),f=h("button");f.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:d,headerTitle:p,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=qc(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Fo=e=>{var Be,it,Et,q,F,le,_,V,oe,Oe,Z,te,kt,lt,Nt,Xt,$e,ce,He,Pt,Wt,ot,st,rn,tn,on,j;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=(it=(Be=r==null?void 0:r.copy)==null?void 0:Be.inputPlaceholder)!=null?it:"Type your message\u2026",o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let Ie=Math.min(o.scrollHeight,u);o.style.height=`${Ie}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 d=(Et=r==null?void 0:r.sendButton)!=null?Et:{},p=(q=d.useIcon)!=null?q:!1,g=(F=d.iconText)!=null?F:"\u2191",f=d.iconName,v=(le=d.tooltipText)!=null?le:"Send message",E=(_=d.showTooltip)!=null?_:!1,x=(V=d.size)!=null?V:"40px",C=d.backgroundColor,k=d.textColor,H=h("div","persona-send-button-wrapper"),w=h("button",p?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),p){if(w.style.width=x,w.style.height=x,w.style.minWidth=x,w.style.minHeight=x,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",k?w.style.color=k:w.style.color="var(--persona-button-primary-fg, #ffffff)",f){let Ie=parseFloat(x)||24,ue=(k==null?void 0:k.trim())||"currentColor",gt=me(f,Ie,ue,2);gt?w.appendChild(gt):w.textContent=g}else w.textContent=g;C?w.style.backgroundColor=C:w.classList.add("persona-bg-persona-primary")}else w.textContent=(Oe=(oe=r==null?void 0:r.copy)==null?void 0:oe.sendButtonLabel)!=null?Oe:"Send",k?w.style.color=k:w.classList.add("persona-text-white");if(d.borderWidth&&(w.style.borderWidth=d.borderWidth,w.style.borderStyle="solid"),d.borderColor&&(w.style.borderColor=d.borderColor),d.paddingX?(w.style.paddingLeft=d.paddingX,w.style.paddingRight=d.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),d.paddingY?(w.style.paddingTop=d.paddingY,w.style.paddingBottom=d.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),E&&v){let Ie=h("div","persona-send-button-tooltip");Ie.textContent=v,H.appendChild(Ie)}H.appendChild(w);let M=(Z=r==null?void 0:r.voiceRecognition)!=null?Z:{},W=M.enabled===!0,T=null,G=null,K=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),J=((te=M.provider)==null?void 0:te.type)==="runtype";if(W&&(K||J)){G=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 Ie=(kt=M.iconName)!=null?kt:"mic",ue=(lt=M.iconSize)!=null?lt:x,gt=parseFloat(ue)||24,Fe=(Nt=M.backgroundColor)!=null?Nt:C,ne=(Xt=M.iconColor)!=null?Xt:k;T.style.width=ue,T.style.height=ue,T.style.minWidth=ue,T.style.minHeight=ue,T.style.fontSize="18px",T.style.lineHeight="1",ne?T.style.color=ne:T.style.color="var(--persona-text, #111827)";let De=me(Ie,gt,ne||"currentColor",1.5);De?T.appendChild(De):T.textContent="\u{1F3A4}",Fe&&(T.style.backgroundColor=Fe),M.borderWidth&&(T.style.borderWidth=M.borderWidth,T.style.borderStyle="solid"),M.borderColor&&(T.style.borderColor=M.borderColor),M.paddingX&&(T.style.paddingLeft=M.paddingX,T.style.paddingRight=M.paddingX),M.paddingY&&(T.style.paddingTop=M.paddingY,T.style.paddingBottom=M.paddingY),G.appendChild(T);let xt=($e=M.tooltipText)!=null?$e:"Start voice recognition";if(((ce=M.showTooltip)!=null?ce:!1)&&xt){let ct=h("div","persona-send-button-tooltip");ct.textContent=xt,G.appendChild(ct)}}let Q=(He=r==null?void 0:r.attachments)!=null?He:{},Ce=Q.enabled===!0,re=null,Ae=null,Ne=null,he=null;if(Ce){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",Ne=h("input"),Ne.type="file",Ne.accept=((Pt=Q.allowedTypes)!=null?Pt:cr).join(","),Ne.multiple=((Wt=Q.maxFiles)!=null?Wt:4)>1,Ne.style.display="none",Ne.setAttribute("aria-label","Attach files"),Ae=h("div","persona-send-button-wrapper"),re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),re.type="button",re.setAttribute("aria-label",(ot=Q.buttonTooltipText)!=null?ot:"Attach file");let Ie=(st=Q.buttonIconName)!=null?st:"paperclip",ue=x,gt=parseFloat(ue)||40,Fe=Math.round(gt*.6);re.style.width=ue,re.style.height=ue,re.style.minWidth=ue,re.style.minHeight=ue,re.style.fontSize="18px",re.style.lineHeight="1",re.style.backgroundColor="transparent",re.style.color="var(--persona-primary, #111827)",re.style.border="none",re.style.borderRadius="6px",re.style.transition="background-color 0.15s ease",re.addEventListener("mouseenter",()=>{re.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),re.addEventListener("mouseleave",()=>{re.style.backgroundColor="transparent"});let ne=me(Ie,Fe,"currentColor",1.5);ne?re.appendChild(ne):re.textContent="\u{1F4CE}",re.addEventListener("click",xt=>{xt.preventDefault(),Ne==null||Ne.click()}),Ae.appendChild(re);let ye=(rn=Q.buttonTooltipText)!=null?rn:"Attach file",De=h("div","persona-send-button-tooltip");De.textContent=ye,Ae.appendChild(De)}s.addEventListener("click",Ie=>{Ie.target!==w&&Ie.target!==H&&Ie.target!==T&&Ie.target!==G&&Ie.target!==re&&Ie.target!==Ae&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),Ne&&s.append(Ne),s.append(o);let ke=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Le=h("div","persona-flex persona-items-center persona-gap-2");Ae&&Le.append(Ae);let ae=h("div","persona-flex persona-items-center persona-gap-1");G&&ae.append(G),ae.append(H),ke.append(Le,ae),s.append(ke);let xe=(tn=r==null?void 0:r.statusIndicator)!=null?tn:{},je=xe.align==="left"?"persona-text-left":xe.align==="center"?"persona-text-center":"persona-text-right",de=h("div",`persona-mt-2 ${je} persona-text-xs persona-text-persona-muted`);de.setAttribute("data-persona-composer-status","");let ie=(on=xe.visible)!=null?on:!0;de.style.display=ie?"":"none";let Ee=(j=xe.idleText)!=null?j:"Online";if(xe.idleLink){let Ie=h("a");Ie.href=xe.idleLink,Ie.target="_blank",Ie.rel="noopener noreferrer",Ie.textContent=Ee,Ie.style.color="inherit",Ie.style.textDecoration="none",de.appendChild(Ie)}else de.textContent=Ee;return t.append(n,s,de),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:H,micButton:T,micButtonWrapper:G,statusText:de,attachmentButton:re,attachmentButtonWrapper:Ae,attachmentInput:Ne,attachmentPreviewsContainer:he,actionsRow:ke,leftActions:Le,rightActions:ae}};var Vc=e=>{var c,d,p,g,f,v,E,x,C;let r=(d=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?d:!0;if(en(e)){let k=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),H=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return k.appendChild(H),{wrapper:k,panel:H}}if(!r){let k=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),H=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(g=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?g:"100%";return k.style.width=w,H.style.width="100%",k.appendChild(H),{wrapper:k,panel:H}}let n=(f=e==null?void 0:e.launcher)!=null?f:{},s=n.position&&Yn[n.position]?Yn[n.position]:Yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:vn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(C=(x=e==null?void 0:e.launcher)==null?void 0:x.width)!=null?C:e==null?void 0:e.launcherWidth,u=i!=null?i:Nn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},Uc=(e,r=!0)=>{var x,C,k,H,w,M,W,T,G;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=(x=e==null?void 0:e.layout)==null?void 0:x.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=n?No(e,n,{showClose:r}):Sr({config:e,showClose:r}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=en(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(H=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?H:"Hello \u{1F44B}";let d=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");d.textContent=(M=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",u.append(c,d);let p=h("div","persona-flex persona-flex-col persona-gap-3"),g=(W=e==null?void 0:e.layout)==null?void 0:W.contentMaxWidth;g&&(p.style.maxWidth=g,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,p);let v=Fo({config:e}),E=((G=e==null?void 0:e.layout)==null?void 0:G.showFooter)!==!1;return s?to(t,o,e):(o.header.style.display="none",to(t,o,e)),t.append(a),E||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:p,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:d,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 Bp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Dp=320,Np=320,Fp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Op=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Dp}px`,c.style.maxHeight=`${Np}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 d=!1;s+=1,c.addEventListener("error",()=>{d||(d=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{d=!0}),Bp(i.image)?(c.src=i.image,n.appendChild(c)):(d=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},no=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},Yc=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:no};if(r){let s=r(n);if(s!==null)return s}return no()},$p=(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},Jc=(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},_p=(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},Gc=(e,r,t)=>{var f,v,E,x,C,k;let n=(f=r.showCopy)!=null?f:!0,s=(v=r.showUpvote)!=null?v:!0,o=(E=r.showDownvote)!=null?E:!0;if(!n&&!s&&!o){let H=h("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(x=r.visibility)!=null?x:"hover",i=(C=r.align)!=null?C:"right",u=(k=r.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],d={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${d} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let g=(H,w,M)=>{let W=Dt({icon:H,label:w,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return n&&p.appendChild(g("copy","Copy message","copy")),s&&p.appendChild(g("thumbs-up","Upvote","upvote")),o&&p.appendChild(g("thumbs-down","Downvote","downvote")),p},Oo=(e,r,t,n,s,o)=>{var J,I,Q,Ce,re,Ae,Ne;let a=t!=null?t:{},i=(J=a.layout)!=null?J:"bubble",u=a.avatar,c=a.timestamp,d=(I=u==null?void 0:u.show)!=null?I:!1,p=(Q=c==null?void 0:c.show)!=null?Q:!1,g=(Ce=u==null?void 0:u.position)!=null?Ce:"left",f=(re=c==null?void 0:c.position)!=null?re:"below",v=_p(e.role,i),E=h("div",v.join(" "));E.id=`bubble-${e.id}`,E.setAttribute("data-message-id",e.id),E.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(E.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",E.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(E.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",E.style.color="var(--persona-message-assistant-text, var(--persona-text))");let x=Fp(e),C=(Ne=(Ae=e.content)==null?void 0:Ae.trim())!=null?Ne:"",H=x.length>0&&C===rs,w=document.createElement("div");w.classList.add("persona-message-content");let M=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),W=null;if(H?(W=document.createElement("div"),W.innerHTML=M,W.style.display="none",w.appendChild(W)):w.innerHTML=M,p&&f==="inline"&&e.createdAt){let he=Jc(e,c);he.classList.add("persona-ml-2","persona-inline"),w.appendChild(he)}if(x.length>0){let he=Op(x,!H&&!!C,()=>{H&&W&&(W.style.display="")});he?E.appendChild(he):H&&W&&(W.style.display="")}if(E.appendChild(w),p&&f==="below"&&e.createdAt){let he=Jc(e,c);he.classList.add("persona-mt-1"),E.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=Yc("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&E.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=Gc(e,n,s);E.appendChild(he)}if(!d||e.role==="system")return E;let G=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),K=$p(u,e.role);return g==="right"||g==="left"&&e.role==="user"?G.append(E,K):G.append(K,E),E.classList.remove("persona-max-w-[85%]"),E.classList.add("persona-max-w-[calc(85%-2.5rem)]"),G},jp=(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}):Oo(e,r,t,n,s,o)};var ro=new Set,zp=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),qp=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
16
+ `):""},Xc=(e,r)=>{let t=ro.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),o=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=me(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Ks=(e,r)=>{var M,W,T,G,K,J,I;let t=e.reasoning,n=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let s=(W=(M=r==null?void 0:r.features)==null?void 0:M.reasoningDisplay)!=null?W:{},o=s.expandable!==!1,a=o&&ro.has(e.id),i=t.status!=="complete",u=qp(e,(T=s.previewMaxLines)!=null?T:3),c=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(K=(G=r==null?void 0:r.reasoning)==null?void 0:G.renderCollapsedSummary)==null?void 0:K.call(G,{message:e,reasoning:t,defaultSummary:g,previewText:u,isActive:i,config:r!=null?r:{}});typeof f=="string"&&f.trim()?(p.textContent=f,d.appendChild(p)):f instanceof HTMLElement?d.appendChild(f):(p.textContent=g,d.appendChild(p));let v=h("span","persona-text-xs persona-text-persona-primary");v.textContent=vc(t),d.appendChild(v),t.status==="complete"?p.style.display="none":p.style.display="";let E=null;if(o){E=h("div","persona-flex persona-items-center");let Ce=me(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?E.appendChild(Ce):E.textContent=a?"Hide":"Show";let re=h("div","persona-flex persona-items-center persona-ml-auto");re.append(E),c.append(d,re)}else c.append(d);let x=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(x.setAttribute("data-persona-collapsed-preview","reasoning"),x.style.display="none",x.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&u){let Q=(I=(J=r==null?void 0:r.reasoning)==null?void 0:J.renderCollapsedPreview)==null?void 0:I.call(J,{message:e,reasoning:t,defaultPreview:u,isActive:i,config:r!=null?r:{}});zp(x,Q)||(x.textContent=u),x.style.display=""}if(!a&&i&&s.activeMinHeight&&(n.style.minHeight=s.activeMinHeight),!o)return n.append(c,x),n;let C=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");C.style.display=a?"":"none";let k=t.chunks.join(""),H=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return H.textContent=k||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),C.appendChild(H),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),E){E.innerHTML="";let Ce=me(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?E.appendChild(Ce):E.textContent=a?"Hide":"Show"}C.style.display=a?"":"none",x.style.display=a?"none":x.textContent||x.childNodes.length?"":"none"})(),n.append(c,x,C),n};var oo=new Set,Vp=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Up=(e,r)=>{var o;let t=e.toolCall;if(!t)return"";let n=((o=t.chunks)!=null?o:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
17
+ `);let s=Xr(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
18
+ `):""},Jp=(e,r)=>{var c,d,p,g;let t=e.toolCall,n=(c=r==null?void 0:r.features)==null?void 0:c.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=Up(e,(p=n==null?void 0:n.previewMaxLines)!=null?p:3),a=t?Cc(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=a;return s==="tool-name"?u=((g=t.name)==null?void 0:g.trim())||a:s==="tool-preview"&&o&&(u=o),{summary:u,previewText:o,isActive:i}},Kc=(e,r,t)=>{var d;let n=oo.has(e),s=(d=t==null?void 0:t.toolCall)!=null?d:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",g=me(n?"chevron-up":"chevron-down",16,p,2);g?c.appendChild(g):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Zs=(e,r)=>{var H,w,M,W,T,G;let t=e.toolCall,n=(H=r==null?void 0:r.toolCall)!=null?H:{},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=(M=(w=r==null?void 0:r.features)==null?void 0:w.toolCallDisplay)!=null?M:{},a=o.expandable!==!1,i=a&&oo.has(e.id),{summary:u,previewText:c,isActive:d}=Jp(e,r),p=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(p.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(p.style.paddingLeft=n.headerPaddingX,p.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(p.style.paddingTop=n.headerPaddingY,p.style.paddingBottom=n.headerPaddingY);let g=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let v=(T=n.renderCollapsedSummary)==null?void 0:T.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(W=o.collapsedMode)!=null?W:"tool-call",isActive:d,config:r!=null?r:{}});typeof v=="string"&&v.trim()?(f.textContent=v,g.appendChild(f)):v instanceof HTMLElement?g.appendChild(v):(f.textContent=u,g.appendChild(f));let E=null;if(a){E=h("div","persona-flex persona-items-center");let K=n.toggleTextColor||n.headerTextColor||"currentColor",J=me(i?"chevron-up":"chevron-down",16,K,2);J?E.appendChild(J):E.textContent=i?"Hide":"Show";let I=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");I.append(E),p.append(g,I)}else p.append(g);let x=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(x.setAttribute("data-persona-collapsed-preview","tool"),x.style.display="none",x.style.whiteSpace="pre-wrap",!i&&d&&o.activePreview&&c){let K=(G=n.renderCollapsedPreview)==null?void 0:G.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:d,config:r!=null?r:{}});Vp(x,K)||(x.textContent=c),x.style.display=""}if(!i&&d&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,x),s;let C=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(C.style.display=i?"":"none",n.contentBackgroundColor&&(C.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(C.style.color=n.contentTextColor),n.contentPaddingX&&(C.style.paddingLeft=n.contentPaddingX,C.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(C.style.paddingTop=n.contentPaddingY,C.style.paddingBottom=n.contentPaddingY),t.name){let K=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?K.style.color=n.contentTextColor:n.headerTextColor&&(K.style.color=n.headerTextColor),K.textContent=t.name,C.appendChild(K)}if(t.args!==void 0){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Arguments";let I=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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(I.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(I.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(I.style.color=n.codeBlockTextColor),I.textContent=Xr(t.args),K.append(J,I),C.appendChild(K)}if(t.chunks&&t.chunks.length){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Activity";let I=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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(I.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(I.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(I.style.color=n.codeBlockTextColor),I.textContent=t.chunks.join(""),K.append(J,I),C.appendChild(K)}if(t.status==="complete"&&t.result!==void 0){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Result";let I=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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(I.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(I.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(I.style.color=n.codeBlockTextColor),I.textContent=Xr(t.result),K.append(J,I),C.appendChild(K)}if(t.status==="complete"&&typeof t.duration=="number"){let K=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(K.style.color=n.contentTextColor),K.textContent=`Duration: ${t.duration}ms`,C.appendChild(K)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let K=n.toggleTextColor||n.headerTextColor||"currentColor",J=me(i?"chevron-up":"chevron-down",16,K,2);J?E.appendChild(J):E.textContent=i?"Hide":"Show"}C.style.display=i?"":"none",x.style.display=i?"none":x.textContent||x.childNodes.length?"":"none"})(),s.append(p,x,C),s};var Qs=(e,r)=>{var E,x,C,k,H,w,M,W,T,G,K,J;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=(E=n==null?void 0:n.backgroundColor)!=null?E:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(x=n==null?void 0:n.borderColor)!=null?x:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(C=n==null?void 0:n.titleColor)!=null?C:"currentColor",d=me(u,20,c,2);d&&i.appendChild(d);let p=h("div","persona-flex-1 persona-min-w-0"),g=h("div","persona-flex persona-items-center persona-gap-2"),f=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(k=n==null?void 0:n.title)!=null?k:"Approval Required",g.appendChild(f),!s){let I=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");I.setAttribute("data-approval-status",t.status),t.status==="approved"?(I.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",I.style.color="var(--persona-palette-colors-success-700, #15803d)",I.textContent="Approved"):t.status==="denied"?(I.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",I.style.color="var(--persona-palette-colors-error-700, #b91c1c)",I.textContent="Denied"):t.status==="timeout"&&(I.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",I.style.color="var(--persona-palette-colors-warning-700, #b45309)",I.textContent="Timeout"),g.appendChild(I)}p.appendChild(g);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,p.appendChild(v),t.parameters){let I=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&&(I.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(I.style.color=n.parameterTextColor),I.style.fontSize="0.75rem",I.style.lineHeight="1rem",I.textContent=Xr(t.parameters),p.appendChild(I)}if(s){let I=h("div","persona-flex persona-gap-2 persona-mt-2");I.setAttribute("data-approval-buttons","true");let Q=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");Q.type="button",Q.style.backgroundColor=(H=n==null?void 0:n.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",Q.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",Q.setAttribute("data-approval-action","approve");let Ce=me("shield-check",14,(M=n==null?void 0:n.approveButtonTextColor)!=null?M:"#ffffff",2);Ce&&(Ce.style.marginRight="4px",Q.appendChild(Ce));let re=document.createTextNode((W=n==null?void 0:n.approveLabel)!=null?W:"Approve");Q.appendChild(re);let Ae=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");Ae.type="button",Ae.style.backgroundColor=(T=n==null?void 0:n.denyButtonColor)!=null?T:"transparent",Ae.style.color=(G=n==null?void 0:n.denyButtonTextColor)!=null?G:"var(--persona-feedback-error, #dc2626)",Ae.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ae.setAttribute("data-approval-action","deny");let Ne=me("shield-x",14,(K=n==null?void 0:n.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);Ne&&(Ne.style.marginRight="4px",Ae.appendChild(Ne));let he=document.createTextNode((J=n==null?void 0:n.denyLabel)!=null?J:"Deny");Ae.appendChild(he),I.append(Q,Ae),p.appendChild(I)}return a.append(i,p),o.appendChild(a),o};var Zc=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(f=>f.role==="user"))return;let d=document.createDocumentFragment(),p=s?s.isStreaming():!1,g=f=>{switch(f){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(f=>{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=f,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=g(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(f))}),d.appendChild(v),r.push(v)}),e.appendChild(d)}}};var $o=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 _o=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function so(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Yp={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)"}},Gp={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Xp=["flowName","stepName","reasoningText","text","name","tool","toolName"],Kp=100;function Zp(e,r){let t={...Yp,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Gp}function Qp(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function eu(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 tu(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 nu(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 ru(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 ou(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function ea(e,r,t,n,s,o,a,i){var g;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");so(c,(g=n.classNames)==null?void 0:g.eventRow);let d=a.find(f=>f.renderEventStreamRow);if(d!=null&&d.renderEventStreamRow&&i){let f=d.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(f)return c.appendChild(f),c}return c.appendChild(p()),c;function p(){var Q,Ce;let f=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 E=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),x=me(u?"chevron-down":"chevron-right","14px","currentColor",2);x&&E.appendChild(x);let C=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(Q=n.timestampFormat)!=null?Q:"relative";C.textContent=k==="relative"?Qp(e.timestamp,t):eu(e.timestamp);let H=null;n.showSequenceNumbers!==!1&&(H=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(r+1));let w=Zp(e.type,n.badgeColors),M=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");M.style.backgroundColor=w.bg,M.style.color=w.text,M.style.borderColor=w.text+"50",M.textContent=e.type;let W=(Ce=n.descriptionFields)!=null?Ce:Xp,T=tu(e.payload,W),G=null;T&&(G=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),G.textContent=T);let K=h("div","persona-flex-1 persona-min-w-0"),J=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"),I=me("clipboard","12px","currentColor",1.5);return I&&J.appendChild(I),J.addEventListener("click",async re=>{re.stopPropagation(),await nu(ru(e)),J.innerHTML="";let Ae=me("check","12px","currentColor",1.5);Ae&&J.appendChild(Ae),setTimeout(()=>{J.innerHTML="";let Ne=me("clipboard","12px","currentColor",1.5);Ne&&J.appendChild(Ne)},1500)}),v.appendChild(E),v.appendChild(C),H&&v.appendChild(H),v.appendChild(M),G&&v.appendChild(G),v.appendChild(K),v.appendChild(J),f.appendChild(v),u&&f.appendChild(ou(e,a,i)),f}}function Qc(e){var f,v,E,x,C;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(f=s==null?void 0:s.features)==null?void 0:f.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(E=a==null?void 0:a.label)!=null?E:"",d=(C=(x=s==null?void 0:s.features)==null?void 0:x.eventStream)!=null?C:{},p=o.find(k=>k.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let k=p.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>g().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return g();function g(){let k=d.classNames,H=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");so(H,k==null?void 0:k.panel);let w=[],M="",W="",T=null,G=[],K={},J=0,I=us(),Q=0,Ce=0,re=!1,Ae=null,Ne=!1,he=0,ke=new Set,Le=new Map,ae="",xe="",je=null,de,ie,Ee,Be,it;function Et(){let ne=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");so(ye,k==null?void 0:k.headerBar);let De=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");De.textContent="Events",de=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"),de.textContent="0";let xt=h("div","persona-flex-1");ie=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 zt=h("option","");zt.value="",zt.textContent="All events",ie.appendChild(zt),Ee=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"),Ee.type="button",Ee.title="Copy All";let qt=me("clipboard-copy","12px","currentColor",1.5);qt&&Ee.appendChild(qt);let ft=h("span","persona-text-xs");ft.textContent="Copy All",Ee.appendChild(ft),ye.appendChild(De),ye.appendChild(de),ye.appendChild(xt),ye.appendChild(ie),ye.appendChild(Ee);let Ke=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");so(Ke,k==null?void 0:k.searchBar);let ht=me("search","14px","var(--persona-muted, #9ca3af)",1.5),We=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");ht&&We.appendChild(ht),Be=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),so(Be,k==null?void 0:k.searchInput),Be.type="text",Be.placeholder="Search event payloads...",it=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"),it.type="button",it.style.display="none";let Vt=me("x","12px","currentColor",2);return Vt&&it.appendChild(Vt),Ke.appendChild(We),Ke.appendChild(Be),Ke.appendChild(it),ne.appendChild(ye),ne.appendChild(Ke),ne}let q,F=o.find(ne=>ne.renderEventStreamToolbar);if(F!=null&&F.renderEventStreamToolbar&&s){let ne=F.renderEventStreamToolbar({config:s,defaultRenderer:()=>Et(),eventCount:r.getSize(),filteredCount:0,onFilterChange:ye=>{M=ye,Xt(),He()},onSearchChange:ye=>{W=ye,Xt(),He()}});q=ne!=null?ne:Et()}else q=Et();let le=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");le.style.display="none";let _=h("div","persona-flex-1 persona-min-h-0 persona-relative"),V=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");V.style.height="100%";let oe=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");so(oe,k==null?void 0:k.scrollIndicator),oe.style.display="none",oe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Oe=me(u,"14px","currentColor",2);Oe&&oe.appendChild(Oe);let Z=h("span","");Z.textContent=c,oe.appendChild(Z);let te=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",_.appendChild(V),_.appendChild(te),_.appendChild(oe),H.setAttribute("tabindex","0"),H.appendChild(q),H.appendChild(le),H.appendChild(_);function kt(){let ne=r.getAll(),ye={};for(let ft of ne)ye[ft.type]=(ye[ft.type]||0)+1;let De=Object.keys(ye).sort(),xt=De.length!==G.length||!De.every((ft,Ke)=>ft===G[Ke]),zt=!xt&&De.some(ft=>ye[ft]!==K[ft]),ct=ne.length!==Object.values(K).reduce((ft,Ke)=>ft+Ke,0);if(!xt&&!zt&&!ct||(G=De,K=ye,!ie))return;let qt=ie.value;if(ie.options[0].textContent="All events",xt){for(;ie.options.length>1;)ie.remove(1);for(let ft of De){let Ke=h("option","");Ke.value=ft,Ke.textContent=`${ft} (${ye[ft]||0})`,ie.appendChild(Ke)}qt&&De.includes(qt)?ie.value=qt:qt&&(ie.value="",M="")}else for(let ft=1;ft<ie.options.length;ft++){let Ke=ie.options[ft];Ke.textContent=`${Ke.value} (${ye[Ke.value]||0})`}}function lt(){let ne=r.getAll();if(M&&(ne=ne.filter(ye=>ye.type===M)),W){let ye=W.toLowerCase();ne=ne.filter(De=>De.type.toLowerCase().includes(ye)||De.payload.toLowerCase().includes(ye))}return ne}function Nt(){return M!==""||W!==""}function Xt(){J=0,Q=0,I.resume(),oe.style.display="none"}function $e(ne){ke.has(ne)?ke.delete(ne):ke.add(ne),je=ne;let ye=V.scrollTop,De=I.isFollowing();Ne=!0,I.pause(),He(),V.scrollTop=ye,De&&I.resume(),Ne=!1}function ce(){return Ho(V,50)}function He(){Ce=Date.now(),re=!1,kt();let ne=r.getEvictedCount();ne>0?(le.textContent=`${ne.toLocaleString()} older events truncated`,le.style.display=""):le.style.display="none",w=lt();let ye=w.length,De=r.getSize()>0;de&&(de.textContent=String(r.getSize())),ye===0&&De&&Nt()?(te.textContent=W?`No events matching '${W}'`:"No events matching filter",te.style.display="",V.style.display="none"):(te.style.display="none",V.style.display=""),Ee&&(Ee.title=Nt()?`Copy Filtered (${ye})`:"Copy All"),i&&!I.isFollowing()&&ye>J&&(Q+=ye-J,Z.textContent=c?`${c}${Q>0?` (${Q})`:""}`:"",oe.style.display=""),J=ye;let xt=r.getAll(),zt=xt.length>0?xt[0].timestamp:0,ct=new Set(w.map(Ke=>Ke.id));for(let Ke of ke)ct.has(Ke)||ke.delete(Ke);let qt=M!==ae||W!==xe,ft=Le.size===0&&w.length>0;if(qt||ft||w.length===0){V.innerHTML="",Le.clear();let Ke=document.createDocumentFragment();for(let ht=0;ht<w.length;ht++){let We=ea(w[ht],ht,zt,d,ke,$e,o,s);Le.set(w[ht].id,We),Ke.appendChild(We)}V.appendChild(Ke),ae=M,xe=W,je=null}else{if(je!==null){let ht=Le.get(je);if(ht&&ht.parentNode===V){let We=w.findIndex(Vt=>Vt.id===je);if(We>=0){let Vt=ea(w[We],We,zt,d,ke,$e,o,s);V.insertBefore(Vt,ht),ht.remove(),Le.set(je,Vt)}}je=null}let Ke=new Set(w.map(ht=>ht.id));for(let[ht,We]of Le)Ke.has(ht)||(We.remove(),Le.delete(ht));for(let ht=0;ht<w.length;ht++){let We=w[ht];if(!Le.has(We.id)){let Vt=ea(We,ht,zt,d,ke,$e,o,s);Le.set(We.id,Vt),V.appendChild(Vt)}}}I.isFollowing()&&(V.scrollTop=V.scrollHeight)}function Pt(){if(Date.now()-Ce>=Kp){Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),He();return}re||(re=!0,Ae=requestAnimationFrame(()=>{Ae=null,He()}))}let Wt=(ne,ye)=>{if(!Ee)return;Ee.innerHTML="";let De=me(ne,"12px","currentColor",1.5);De&&Ee.appendChild(De);let xt=h("span","persona-text-xs");xt.textContent="Copy All",Ee.appendChild(xt),setTimeout(()=>{Ee.innerHTML="";let zt=me("clipboard-copy","12px","currentColor",1.5);zt&&Ee.appendChild(zt);let ct=h("span","persona-text-xs");ct.textContent="Copy All",Ee.appendChild(ct),Ee.disabled=!1},ye)},ot=async()=>{if(Ee){Ee.disabled=!0;try{let ne;Nt()?ne=w:t?(ne=await t(),ne.length===0&&(ne=r.getAll())):ne=r.getAll();let ye=ne.map(De=>{try{return JSON.parse(De.payload)}catch{return De.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),Wt("check",1500)}catch{Wt("x",1500)}}},st=()=>{ie&&(M=ie.value,Xt(),He())},rn=()=>{!Be||!it||(it.style.display=Be.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{W=Be.value,Xt(),He()},150))},tn=()=>{!Be||!it||(Be.value="",W="",it.style.display="none",T&&clearTimeout(T),Xt(),He())},on=()=>{if(Ne)return;let ne=V.scrollTop,{action:ye,nextLastScrollTop:De}=ms({following:I.isFollowing(),currentScrollTop:ne,lastScrollTop:he,nearBottom:ce(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=De,ye==="resume"?(I.resume(),Q=0,oe.style.display="none"):ye==="pause"&&(I.pause(),i&&(Z.textContent=c,oe.style.display=""))},j=ne=>{let ye=gs({following:I.isFollowing(),deltaY:ne.deltaY,nearBottom:ce(),resumeWhenNearBottom:!0});ye==="pause"?(I.pause(),i&&(Z.textContent=c,oe.style.display="")):ye==="resume"&&(I.resume(),Q=0,oe.style.display="none")},Ie=()=>{i&&(V.scrollTop=V.scrollHeight,I.resume(),Q=0,oe.style.display="none")},ue=ne=>{let ye=ne.target;if(!ye||ye.closest("button"))return;let De=ye.closest("[data-event-id]");if(!De)return;let xt=De.getAttribute("data-event-id");xt&&$e(xt)},gt=ne=>{if((ne.metaKey||ne.ctrlKey)&&ne.key==="f"){ne.preventDefault(),Be==null||Be.focus(),Be==null||Be.select();return}ne.key==="Escape"&&(Be&&document.activeElement===Be?(tn(),Be.blur(),H.focus()):n&&n())};Ee&&Ee.addEventListener("click",ot),ie&&ie.addEventListener("change",st),Be&&Be.addEventListener("input",rn),it&&it.addEventListener("click",tn),V.addEventListener("scroll",on),V.addEventListener("wheel",j,{passive:!0}),V.addEventListener("click",ue),oe.addEventListener("click",Ie),H.addEventListener("keydown",gt);function Fe(){T&&clearTimeout(T),Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),re=!1,Le.clear(),Ee&&Ee.removeEventListener("click",ot),ie&&ie.removeEventListener("change",st),Be&&Be.removeEventListener("input",rn),it&&it.removeEventListener("click",tn),V.removeEventListener("scroll",on),V.removeEventListener("wheel",j),V.removeEventListener("click",ue),oe.removeEventListener("click",Ie),H.removeEventListener("keydown",gt)}return{element:H,update:Pt,destroy:Fe}}}function ed(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let d=document.createElement("div");d.className="persona-truncate persona-text-sm persona-font-medium",d.style.color="var(--persona-text, #1f2937)",d.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(f)}else p.textContent=a;if(c.append(d,p),i.append(u,c),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${t}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",n),i.append(g)}return i}var td=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",d=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>ed(e,r)});if(d)return d}return ed(e,r)};var ta=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},Ar=new ta;Ar.register("PersonaArtifactCard",td);function su(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 nd(e,r){var Ee,Be,it,Et;let t=(Be=(Ee=e.features)==null?void 0:Ee.artifacts)==null?void 0:Be.layout,s=((it=t==null?void 0:t.toolbarPreset)!=null?it:"default")==="document",o=(Et=t==null?void 0:t.panePadding)==null?void 0:Et.trim(),a=e.markdown?Gr(e.markdown):null,i=To(e.sanitize),u=q=>{let F=a?a(q):Eo(q);return i?i(F):F},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,d=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),I==null||I.hide()};c&&c.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let g=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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let f=h("span","persona-text-xs persona-font-medium persona-truncate");f.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 q;d(),(q=r.onDismiss)==null||q.call(r)});let E="rendered",x=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?Dt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Dt({icon:"eye",label:"Rendered view"}),k=s?Dt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Dt({icon:"code-2",label:"Source"}),H=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,M=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,W=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(M&&W&&W.length>0),G=null,K,J=null,I=null;if(s&&(w||M)&&!T){if(K=w?hs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),M){let q=me("chevron-down",14,"currentColor",2);q&&K.appendChild(q)}}else s&&T?(G=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),K=w?hs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),J=Dt({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"}}),G.append(K,J)):s?K=Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):K=Dt({icon:"copy",label:"Copy"});let Q=s?Dt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Dt({icon:"refresh-cw",label:"Refresh"}),Ce=s?Dt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Dt({icon:"x",label:"Close"}),re=()=>{var V,oe,Oe;let q=(V=ae.find(Z=>Z.id===xe))!=null?V:ae[ae.length-1],F=(oe=q==null?void 0:q.id)!=null?oe:null,le=(q==null?void 0:q.artifactType)==="markdown"&&(Oe=q.markdown)!=null?Oe:"",_=q?JSON.stringify({component:q.component,props:q.props},null,2):"";return{markdown:le,jsonPayload:_,id:F}},Ae=async()=>{var V;let{markdown:q,jsonPayload:F}=re(),le=(V=ae.find(oe=>oe.id===xe))!=null?V:ae[ae.length-1],_=(le==null?void 0:le.artifactType)==="markdown"?q:le?F:"";try{await navigator.clipboard.writeText(_)}catch{}};if(K.addEventListener("click",async()=>{let q=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(q&&T){let{markdown:F,jsonPayload:le,id:_}=re();try{await q({actionId:"primary",artifactId:_,markdown:F,jsonPayload:le})}catch{}return}await Ae()}),J&&(W!=null&&W.length)){let q=()=>{var le;return(le=p.closest("[data-persona-root]"))!=null?le:document.body},F=()=>{I=$r({items:W.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:_,jsonPayload:V,id:oe}=re(),Oe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Oe?await Oe({actionId:le,artifactId:oe,markdown:_,jsonPayload:V}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(_):le==="json"||le==="source"?await navigator.clipboard.writeText(V):await navigator.clipboard.writeText(_||V)}catch{}},anchor:G!=null?G:J,position:"bottom-right",portal:q()})};p.isConnected?F():requestAnimationFrame(F),J.addEventListener("click",le=>{le.stopPropagation(),I==null||I.toggle()})}Q.addEventListener("click",async()=>{var q;try{await((q=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:q.call(t))}catch{}de()}),Ce.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});let Ne=()=>{s&&(C.setAttribute("aria-pressed",E==="rendered"?"true":"false"),k.setAttribute("aria-pressed",E==="source"?"true":"false"))};C.addEventListener("click",()=>{E="rendered",Ne(),de()}),k.addEventListener("click",()=>{E="source",Ne(),de()});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?(g.replaceChildren(),x.append(C,k),G?H.append(G,Q,Ce):H.append(K,Q,Ce),g.append(x,he,H),Ne()):(g.appendChild(f),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let ke=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ke.style.paddingLeft=o,ke.style.paddingRight=o,Le.style.padding=o),p.appendChild(g),p.appendChild(ke),p.appendChild(Le);let ae=[],xe=null,je=!1,de=()=>{var _,V,oe,Oe;let q=s&&ae.length<=1;ke.classList.toggle("persona-hidden",q),ke.replaceChildren();for(let Z of ae){let te=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");te.type="button",te.textContent=Z.title||Z.id.slice(0,8),Z.id===xe&&te.classList.add("persona-bg-persona-container","persona-border-persona-border"),te.addEventListener("click",()=>r.onSelect(Z.id)),ke.appendChild(te)}Le.replaceChildren();let F=xe&&ae.find(Z=>Z.id===xe)||ae[ae.length-1];if(!F)return;if(s){let Z=F.artifactType==="markdown"?"MD":(_=F.component)!=null?_:"Component",kt=(F.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${kt} \xB7 ${Z}`}else f.textContent="Artifacts";if(F.artifactType==="markdown"){if(s&&E==="source"){let te=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");te.textContent=(V=F.markdown)!=null?V:"",Le.appendChild(te);return}let Z=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Z.innerHTML=u((oe=F.markdown)!=null?oe:""),Le.appendChild(Z);return}let le=F.component?Ar.get(F.component):void 0;if(le){let te={message:{id:F.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let kt=le((Oe=F.props)!=null?Oe:{},te);if(kt){Le.appendChild(kt);return}}catch{}}Le.appendChild(su(F))},ie=()=>{var F;let q=ae.length>0;if(p.classList.toggle("persona-hidden",!q),c){let le=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,V=((F=le==null?void 0:le.classList.contains("persona-artifact-narrow-host"))!=null?F:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;q&&V&&je?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(q){var F,le,_;ae=q.artifacts,xe=(_=(le=q.selectedId)!=null?le:(F=q.artifacts[q.artifacts.length-1])==null?void 0:F.id)!=null?_:null,ae.length>0&&(je=!0),de(),ie()},setMobileOpen(q){je=q,!q&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ie()}}}function Fn(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 rd(e,r){var o,a,i,u;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Fn(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function au(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 bs(e,r){var u,c,d,p,g,f,v,E,x,C;if(!Fn(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"),au(e),rd(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(d=t==null?void 0:t.splitGap)!=null?d:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"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=(f=t==null?void 0:t.paneBackground)==null?void 0:f.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=(E=t==null?void 0:t.documentToolbarIconColor)==null?void 0:E.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(x=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:x.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"),rd(e,r)}var od=["panel","seamless"];function xs(e,r){var i,u,c,d,p,g;for(let f of od)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!Fn(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=od.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(d=t==null?void 0:t.paneBorderRadius)==null?void 0:d.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function sd(e,r){var t,n,s;return!r||!Fn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function iu(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 lu(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 cu(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function du(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function ad(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 id(e,r,t,n,s,o){let a=iu(s,200),i=du(r,t,n,200);i=Math.max(a,i);let u=lu(o);return u!==null&&(i=Math.min(i,u)),cu(e,a,i)}var ld={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"}},na=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,E,x;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(E=ld[a])!=null?E:ld.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let C=h("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,u.appendChild(C)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var W,T;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${r.id}-${a}-${C.name}`;let H=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=C.label,k.appendChild(H);let w=(W=C.type)!=null?W:"text",M;w==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=w),M.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",M.id=`${r.id}-${a}-${C.name}`,M.name=C.name,M.placeholder=(T=C.placeholder)!=null?T:"",C.required&&(M.required=!0),k.appendChild(M),d.appendChild(k)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=(x=i.submitLabel)!=null?x:"Submit",p.appendChild(g),p.appendChild(f),d.appendChild(p),o.replaceChildren(u,d),d.addEventListener("submit",async C=>{var M,W;C.preventDefault();let k=(M=t.formEndpoint)!=null?M:"/form",H=new FormData(d),w={};H.forEach((T,G)=>{w[G]=T}),w.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let T=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let G=await T.json();g.textContent=(W=G.message)!=null?W:"Thanks! We'll be in touch soon.",G.success&&G.nextPrompt&&await n.sendMessage(String(G.nextPrompt))}catch(T){g.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var ra=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},vs=new ra;var cd=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var pu=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},uu=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=pu(e),t=uu(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}},oa=e=>typeof e=="string"?e:e==null?"":String(e),ao={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:oa(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=oa(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:oa(t.text)}}},dd=e=>Array.isArray(e)?e.map(r=>String(r)):[],ws=e=>{let r=new Set(dd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(dd(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,d)=>c||(d==null?void 0:d({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let d=()=>{e.emit("action:resubmit",u)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!p)continue;if(p.handled){let g=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:g,resubmit:p.resubmit}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:t}};var mu=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}},gu=e=>e.map(r=>({...r,streaming:!1})),sa=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?mu(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?gu(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 fu,STR as hu,OBJ as yu}from"partial-json";function bu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function xu(e,r){if(!bu(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 aa(){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=fu(t,hu|yu),o=xu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function vu(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ia(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Ar.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Cu(){let e=aa();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function la(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 ca(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 wu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function da(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=wu}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let p=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,f.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,f.appendChild(E),g.appendChild(f);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-csat",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];for(let W=1;W<=5;W++){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",`${W} star${W>1?"s":""}: ${c[W-1]}`),T.title=c[W-1],T.dataset.rating=String(W),T.innerHTML=`
19
19
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
20
20
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
21
21
  </svg>
22
- `,E.addEventListener("click",()=>{p=W,C.forEach((G,K)=>{let J=K<W;G.classList.toggle("selected",J),G.setAttribute("aria-checked",K===W-1?"true":"false")})}),C.push(E),x.appendChild(E)}m.appendChild(x);let k=null;if(u){let W=document.createElement("div");W.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),W.appendChild(k),m.appendChild(W)}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(),d.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=a,M.addEventListener("click",async()=>{if(p===null){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let W=(k==null?void 0:k.value.trim())||void 0;await r(p,W),d.remove()}catch(W){M.disabled=!1,M.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),R.appendChild(w),R.appendChild(M),m.appendChild(R),d.appendChild(m),d}function la(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,v.appendChild(A);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,v.appendChild(x),f.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 k=document.createElement("div");k.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=d,k.appendChild(R),k.appendChild(w);let M=document.createElement("div");M.className="persona-feedback-numbers";let W=[];for(let L=0;L<=10;L++){let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-rating-btn persona-feedback-number-btn",Q.setAttribute("role","radio"),Q.setAttribute("aria-checked","false"),Q.setAttribute("aria-label",`Rating ${L} out of 10`),Q.textContent=String(L),Q.dataset.rating=String(L),L<=6?Q.classList.add("persona-feedback-detractor"):L<=8?Q.classList.add("persona-feedback-passive"):Q.classList.add("persona-feedback-promoter"),Q.addEventListener("click",()=>{m=L,W.forEach((we,ne)=>{we.classList.toggle("selected",ne===L),we.setAttribute("aria-checked",ne===L?"true":"false")})}),W.push(Q),M.appendChild(Q)}C.appendChild(k),C.appendChild(M),f.appendChild(C);let E=null;if(u){let L=document.createElement("div");L.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=o,E.rows=3,E.setAttribute("aria-label","Additional comments"),L.appendChild(E),f.appendChild(L)}let G=document.createElement("div");G.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=i,K.addEventListener("click",()=>{t==null||t(),p.remove()});let J=document.createElement("button");return J.type="button",J.className="persona-feedback-btn persona-feedback-btn-submit",J.textContent=a,J.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}J.disabled=!0,J.textContent="Submitting...";try{let L=(E==null?void 0:E.value.trim())||void 0;await r(m,L),p.remove()}catch(L){J.disabled=!1,J.textContent=a,console.error("[NPS Feedback] Failed to submit:",L)}}),G.appendChild(K),G.appendChild(J),f.appendChild(G),p.appendChild(f),p}var ao="persona-chat-history",lu=30*1e3,cu={"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 du(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=cu[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function pu(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function uu(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var ca=e=>!e||typeof e!="object"?{}:{...e},Kc=e=>e.map(r=>({...r,streaming:!1})),Zc=(e,r,t)=>{let n=e!=null&&e.markdown?Yr(e.markdown):null,s=Ao(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,d,p;let a=(c=o.text)!=null?c:"",i=(d=o.message.rawContent)!=null?d:null;if(r){let m=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});m!==null&&(a=m.text,m.persist||(o.message.__skipPersist=!0),m.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):n?u=n(a):u=So(a),s?s(u):u}},da=(e,r,t)=>{var nn,Yt,Gt,Xe,Mt,Xt,rn,Nt,kn,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Na,Fa,Oa,$a,_a,ja,za,qa,Ua,Va,Ja,Ya,Ga,Xa,Ka;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=$s(r),s=ys.getForInstance(n.plugins);n.components&&Cr.registerAll(n.components);let o=Gc(),a=(nn=n.storageAdapter)!=null?nn:na(),i={},u=null,c=!1,d=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:T}=g;return T&&(c=!0),b}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")u=l.then(g=>{let b=g!=null?g:{messages:[],metadata:{}};return d(b)});else{let g=l!=null?l:{messages:[],metadata:{}},b=d(g);b.metadata&&(i=ca(b.metadata)),(Yt=b.messages)!=null&&Yt.length&&(n={...n,initialMessages:b.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=d({messages:[],metadata:{}});(Gt=l.messages)!=null&&Gt.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>i,m=l=>{var b;i=(b=l({...i}))!=null?b:{},po()},f=n.actionParsers&&n.actionParsers.length?n.actionParsers:[bs],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[so.message,so.messageAndClick],A=xs({parsers:f,handlers:v,getSessionMetadata:p,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let x=(Mt=(Xe=n.launcher)==null?void 0:Xe.enabled)!=null?Mt:!0,C=(rn=(Xt=n.launcher)==null?void 0:Xt.autoExpand)!=null?rn:!1,k=(Nt=n.autoFocusInput)!=null?Nt:!1,R=C,w=x,M=(Ca=(kn=n.layout)==null?void 0:kn.header)==null?void 0:Ca.layout,W=!1,E=x?C:!0,G=!1,K=null,J=()=>{G=!0,K&&clearTimeout(K),K=setTimeout(()=>{G&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),G=!1)},1e4)},L=Zc(n,A,J),Q=(Sa=(wa=n.features)==null?void 0:wa.showReasoning)!=null?Sa:!0,we=(Ea=(Aa=n.features)==null?void 0:Aa.showToolCalls)!=null?Ea:!0,ne=(Ma=(Ta=n.features)==null?void 0:Ta.showEventStreamToggle)!=null?Ma:!1,Ee=(La=(ka=n.features)==null?void 0:ka.scrollToBottom)!=null?La:{},fe=`${(Pa=typeof n.persistState=="object"?(Ia=n.persistState)==null?void 0:Ia.keyPrefix:void 0)!=null?Pa:"persona-"}event-stream`,Ie=ne?new Oo(fe):null,Pe=(Ha=(Ra=(Wa=n.features)==null?void 0:Wa.eventStream)==null?void 0:Ra.maxEvents)!=null?Ha:2e3,se=ne?new Fo(Pe,Ie):null,be=null,ze=!1,ce=null,ae=0;Ie==null||Ie.open().then(()=>se==null?void 0:se.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Te={onCopy:l=>{var g,b;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.id,"copy").catch(T=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",T)}),(b=(g=n.messageActions)==null?void 0:g.onCopy)==null||b.call(g,l)},onFeedback:l=>{var g,b;o.emit("message:feedback",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.messageId,l.type).catch(T=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",T)}),(b=(g=n.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,l)}},Ne=(Ba=n.statusIndicator)!=null?Ba:{},lt=l=>{var g,b,T,I;return l==="idle"?(g=Ne.idleText)!=null?g:ln.idle:l==="connecting"?(b=Ne.connectingText)!=null?b:ln.connecting:l==="connected"?(T=Ne.connectedText)!=null?T:ln.connected:l==="error"?(I=Ne.errorText)!=null?I:ln.error:ln[l]};function Tt(l,g,b,T){if(T==="idle"&&b.idleLink){l.textContent="";let I=document.createElement("a");I.href=b.idleLink,I.target="_blank",I.rel="noopener noreferrer",I.textContent=g,I.style.color="inherit",I.style.textDecoration="none",l.appendChild(I)}else l.textContent=g}let{wrapper:q,panel:F}=Pc(n),ie=Wc(n,x),{container:j,body:U,messagesWrapper:re,suggestions:_e,textarea:Z,sendButton:ee,sendButtonWrapper:kt,composerForm:ct,statusText:Dt,introTitle:Jt,introSubtitle:je,closeButton:le,iconHolder:De,headerTitle:It,headerSubtitle:Pt,header:rt,footer:ot,actionsRow:en,leftActions:Qt,rightActions:tn}=ie,_=ie.micButton,We=ie.micButtonWrapper,de=ie.attachmentButton,ft=ie.attachmentButtonWrapper,$e=ie.attachmentInput,te=ie.attachmentPreviewsContainer;j.classList.add("persona-relative"),U.classList.add("persona-relative");let he=12,Fe=()=>{var l;return(l=Ee.label)!=null?l:""},Ct=()=>{var l;return(l=Ee.iconName)!=null?l:"arrow-down"},_t=()=>Ee.enabled!==!1,dt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");dt.type="button",dt.style.display="none",dt.setAttribute("data-persona-scroll-to-bottom","true");let jt=h("span","persona-flex persona-items-center"),ht=h("span","");dt.append(jt,ht),j.appendChild(dt);let Ze=()=>{let g=ot.style.display==="none"?0:ot.offsetHeight;dt.style.bottom=`${g+he}px`};Ze();let yt=()=>{let l=!!Fe();dt.setAttribute("aria-label",Fe()||"Jump to latest"),dt.title=Fe(),dt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),jt.innerHTML="";let g=ge(Ct(),"14px","currentColor",2);g?(jt.appendChild(g),jt.style.display=""):jt.style.display="none",ht.textContent=Fe(),ht.style.display=l?"":"none"};yt();let Ue=null,zt=null,Jn=s.find(l=>l.renderHeader);if(Jn!=null&&Jn.renderHeader){let l=Jn.renderHeader({config:n,defaultRenderer:()=>{let g=vr({config:n,showClose:x});return eo(j,g,n),g.header},onClose:()=>Wt(!1,"user")});if(l){let g=j.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),rt=l)}}let Qn=()=>{var g,b,T,I;if(!se)return;if(ze=!0,!be&&se&&(be=Oc({buffer:se,getFullHistory:()=>se.getAllFromStore(),onClose:()=>Nn(),config:n,plugins:s})),be&&(U.style.display="none",(g=ot.parentNode)==null||g.insertBefore(be.element,ot),be.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${vn.actionIconColor}`;let H=(I=(T=(b=n.features)==null?void 0:b.eventStream)==null?void 0:T.classNames)==null?void 0:I.toggleButtonActive;H&&H.split(/\s+/).forEach(B=>B&&et.classList.add(B))}let l=()=>{if(!ze)return;let H=Date.now();H-ae>=200&&(be==null||be.update(),ae=H),ce=requestAnimationFrame(l)};ae=0,ce=requestAnimationFrame(l),rr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var l,g,b;if(ze){if(ze=!1,be&&be.element.remove(),U.style.display="",et){et.style.boxShadow="";let T=(b=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;T&&T.split(/\s+/).forEach(I=>I&&et.classList.remove(I))}ce!==null&&(cancelAnimationFrame(ce),ce=null),rr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(ne){let l=(Na=(Da=n.features)==null?void 0:Da.eventStream)==null?void 0:Na.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:"");et=h("button",g),et.style.width="28px",et.style.height="28px",et.style.color=vn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let b=ge("activity","18px","currentColor",1.5);b&&et.appendChild(b);let T=ie.clearChatButtonWrapper,I=ie.closeButtonWrapper,H=T||I;H&&H.parentNode===rt?rt.insertBefore(et,H):rt.appendChild(et),et.addEventListener("click",()=>{ze?Nn():Qn()})}let Sr=l=>{var T,I,H;let g=n.attachments;if(!(g!=null&&g.enabled))return;let b=l.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let B=l.querySelector("[data-persona-composer-form]");B!=null&&B.parentNode?B.parentNode.insertBefore(b,B):l.insertBefore(b,l.firstChild)}if(!l.querySelector('input[type="file"]')){let B=h("input");B.type="file",B.accept=((T=g.allowedTypes)!=null?T:ar).join(","),B.multiple=((I=g.maxFiles)!=null?I:4)>1,B.style.display="none",B.setAttribute("aria-label",(H=g.buttonTooltipText)!=null?H:"Attach files"),l.appendChild(B)}},Yn=s.find(l=>l.renderComposer);if(Yn!=null&&Yn.renderComposer){let l=n.composer,g=Yn.renderComposer({config:n,defaultRenderer:()=>Do({config:n}).footer,onSubmit:b=>{D&&!D.isStreaming()&&D.sendMessage(b)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{$e==null||$e.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:b=>{n.composer={...n.composer,selectedModelId:b},n.agent&&(n.agent={...n.agent,model:b})},onVoiceToggle:((Fa=n.voiceRecognition)==null?void 0:Fa.enabled)===!0?()=>{zt==null||zt()}:void 0});g&&(ot.replaceWith(g),ot=g)}let Ar=l=>{let g=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),I=l.querySelector("[data-persona-composer-mic]"),H=l.querySelector("[data-persona-composer-status]");g&&(ct=g),b&&(Z=b),T&&(ee=T),I&&(_=I,We=I.parentElement),H&&(Dt=H);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(_e=B);let z=l.querySelector(".persona-attachment-button");z&&(de=z,ft=z.parentElement),$e=l.querySelector('input[type="file"]'),te=l.querySelector(".persona-attachment-previews");let O=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(en=O)};Sr(ot),Ar(ot);let In=(Oa=n.layout)==null?void 0:Oa.contentMaxWidth;In&&ct&&(ct.style.maxWidth=In,ct.style.marginLeft="auto",ct.style.marginRight="auto"),In&&_e&&(_e.style.maxWidth=In,_e.style.marginLeft="auto",_e.style.marginRight="auto"),In&&te&&(te.style.maxWidth=In,te.style.marginLeft="auto",te.style.marginRight="auto"),($a=n.attachments)!=null&&$a.enabled&&$e&&te&&(Ue=Qr.fromConfig(n.attachments),Ue.setPreviewsContainer(te),$e.addEventListener("change",l=>{let g=l.target;Ue==null||Ue.handleFileSelect(g.files),g.value=""})),(()=>{var T,I;let l=(I=(T=n.layout)==null?void 0:T.slots)!=null?I:{},g=H=>{switch(H){case"body-top":return j.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return re;case"footer-top":return _e;case"composer":return ct;case"footer-bottom":return Dt;default:return null}},b=(H,B)=>{var z;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")rt.insertBefore(B,rt.firstChild);else if(H==="header-right")rt.appendChild(B);else{let O=rt.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(B,O.nextSibling):rt.appendChild(B)}break;case"body-top":{let O=U.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(B):U.insertBefore(B,U.firstChild);break}case"body-bottom":U.appendChild(B);break;case"footer-top":_e.replaceWith(B);break;case"footer-bottom":Dt.replaceWith(B);break;default:break}};for(let[H,B]of Object.entries(l))if(B)try{let z=B({config:n,defaultContent:()=>g(H)});z&&b(H,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,z)}})();let lr=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let T=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!T)return;let I=T.getAttribute("data-message-id");if(!I)return;let H=b.getAttribute("data-bubble-type");H==="reasoning"?(no.has(I)?no.delete(I):no.add(I),Dc(I,T)):H==="tool"&&(ro.has(I)?ro.delete(I):ro.add(I),Nc(I,T,n)),Wn.delete(I)};re.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),lr(l))}),re.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),lr(l))});let er=new Map;re.addEventListener("click",l=>{var B;let b=l.target.closest(".persona-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let T=b.closest("[data-actions-for]");if(!T)return;let I=T.getAttribute("data-actions-for");if(!I)return;let H=b.getAttribute("data-action");if(H==="copy"){let O=D.getMessages().find(ue=>ue.id===I);if(O&&Te.onCopy){let ue=O.content||"";navigator.clipboard.writeText(ue).then(()=>{b.classList.add("persona-message-action-success");let Ce=ge("check",14,"currentColor",2);Ce&&(b.innerHTML="",b.appendChild(Ce)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let Ae=ge("copy",14,"currentColor",2);Ae&&(b.innerHTML="",b.appendChild(Ae))},2e3)}).catch(Ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ce)}),Te.onCopy(O)}}else if(H==="upvote"||H==="downvote")if(((B=er.get(I))!=null?B:null)===H)er.delete(I),b.classList.remove("persona-message-action-active");else{let ue=H==="upvote"?"downvote":"upvote",Ce=T.querySelector(`[data-action="${ue}"]`);Ce&&Ce.classList.remove("persona-message-action-active"),er.set(I,H),b.classList.add("persona-message-action-active");let ye=D.getMessages().find(Me=>Me.id===I);ye&&Te.onFeedback&&Te.onFeedback({type:H,messageId:ye.id,message:ye})}}),re.addEventListener("click",l=>{let b=l.target.closest("button[data-approval-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let T=b.closest(".persona-approval-bubble");if(!T)return;let I=T.getAttribute("data-message-id");if(!I)return;let H=b.getAttribute("data-approval-action");if(!H)return;let B=H==="approve"?"approved":"denied",O=D.getMessages().find(Ce=>Ce.id===I);if(!(O!=null&&O.approval))return;let ue=T.querySelector("[data-approval-buttons]");ue&&ue.querySelectorAll("button").forEach(Ae=>{Ae.disabled=!0,Ae.style.opacity="0.5",Ae.style.cursor="not-allowed"}),D.resolveApproval(O.approval,B)});let st=null,Cn=null,Fn={artifacts:[],selectedId:null},cn=!1,cr={current:null};re.addEventListener("click",l=>{var Ae,ye,Me,qe,ut;let b=l.target.closest("[data-download-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let T=b.getAttribute("data-download-artifact");if(!T||((Me=(ye=(Ae=n.features)==null?void 0:Ae.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:Me.call(ye,{type:"download",artifactId:T}))===!0)return;let H=D.getArtifactById(T),B=H==null?void 0:H.markdown,z=(H==null?void 0:H.title)||"artifact";if(!B){let Ke=b.closest("[data-open-artifact]"),$=Ke==null?void 0:Ke.closest("[data-message-id]"),Le=$==null?void 0:$.getAttribute("data-message-id");if(Le){let me=D.getMessages().find(He=>He.id===Le);if(me!=null&&me.rawContent)try{let He=JSON.parse(me.rawContent);B=(qe=He==null?void 0:He.props)==null?void 0:qe.markdown,z=((ut=He==null?void 0:He.props)==null?void 0:ut.title)||z}catch{}}}if(!B)return;let O=new Blob([B],{type:"text/markdown"}),ue=URL.createObjectURL(O),Ce=document.createElement("a");Ce.href=ue,Ce.download=`${z}.md`,Ce.click(),URL.revokeObjectURL(ue)}),re.addEventListener("click",l=>{var H,B,z;let b=l.target.closest("[data-open-artifact]");if(!b)return;let T=b.getAttribute("data-open-artifact");!T||((z=(B=(H=n.features)==null?void 0:H.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:z.call(B,{type:"open",artifactId:T}))===!0||(l.preventDefault(),l.stopPropagation(),cn=!1,D.selectArtifact(T),Sn())}),re.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let wn=null,St=null,dn=null,Pn=null,dr=()=>{};function tr(){Pn==null||Pn(),Pn=null}let pr=()=>{var B;if(!wn||!St)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),b=((B=e.ownerDocument.defaultView)!=null?B:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||b){St.style.removeProperty("position"),St.style.removeProperty("left"),St.style.removeProperty("top"),St.style.removeProperty("bottom"),St.style.removeProperty("width"),St.style.removeProperty("z-index");return}let T=wn.firstElementChild;if(!T||T===St)return;let I=10;St.style.position="absolute",St.style.top="0",St.style.bottom="0",St.style.width=`${I}px`,St.style.zIndex="5";let H=T.offsetWidth-I/2;St.style.left=`${Math.max(0,H)}px`},Gn=()=>{},Sn=()=>{var b,T,I,H,B;if(!st||!Dn(n))return;fs(e,n),hs(e,n),Gn();let l=(H=(I=(T=(b=n.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:I.narrowHostMaxWidth)!=null?H:520,g=F.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),st.update(Fn),cn?(st.setMobileOpen(!1),st.element.classList.add("persona-hidden"),(B=st.backdrop)==null||B.classList.add("persona-hidden")):Fn.artifacts.length>0&&(st.element.classList.remove("persona-hidden"),st.setMobileOpen(!0)),dr()};if(Dn(n)){F.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(j),st=jc(n,{onSelect:b=>{var T;return(T=cr.current)==null?void 0:T.selectArtifact(b)},onDismiss:()=>{cn=!0,Sn()}}),st.element.classList.add("persona-hidden"),wn=g,g.appendChild(l),g.appendChild(st.element),st.backdrop&&F.appendChild(st.backdrop),F.appendChild(g),dr=()=>{var T,I,H,B;if(!wn||!st)return;if(!(((H=(I=(T=n.features)==null?void 0:T.artifacts)==null?void 0:I.layout)==null?void 0:H.resizable)===!0)){dn==null||dn(),dn=null,tr(),St&&(St.remove(),St=null),st.element.style.removeProperty("width"),st.element.style.removeProperty("maxWidth");return}if(!St){let z=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,ue=(B=O.defaultView)!=null?B:window,Ce=Ae=>{var $,Le;if(!st||Ae.button!==0||e.classList.contains("persona-artifact-narrow-host")||ue.innerWidth<=640)return;Ae.preventDefault(),tr();let ye=Ae.clientX,Me=st.element.getBoundingClientRect().width,qe=(Le=($=n.features)==null?void 0:$.artifacts)==null?void 0:Le.layout,ut=Re=>{let me=wn.getBoundingClientRect().width,He=e.classList.contains("persona-artifact-appearance-seamless"),wt=He?0:Vc(wn,ue),vt=He?0:z.getBoundingClientRect().width||6,Ut=Me-(Re.clientX-ye),on=Jc(Ut,me,wt,vt,qe==null?void 0:qe.resizableMinWidth,qe==null?void 0:qe.resizableMaxWidth);st.element.style.width=`${on}px`,st.element.style.maxWidth="none",pr()},Ke=()=>{O.removeEventListener("pointermove",ut),O.removeEventListener("pointerup",Ke),O.removeEventListener("pointercancel",Ke),Pn=null;try{z.releasePointerCapture(Ae.pointerId)}catch{}};Pn=Ke,O.addEventListener("pointermove",ut),O.addEventListener("pointerup",Ke),O.addEventListener("pointercancel",Ke);try{z.setPointerCapture(Ae.pointerId)}catch{}};z.addEventListener("pointerdown",Ce),St=z,wn.insertBefore(z,st.element),dn=()=>{z.removeEventListener("pointerdown",Ce)}}if(St){let z=Fn.artifacts.length>0&&!cn;St.classList.toggle("persona-hidden",!z),pr()}},Gn=()=>{var ue,Ce,Ae,ye,Me,qe,ut,Ke,$,Le,Re,me,He,wt;if(!x||!st||((Ce=(ue=n.launcher)==null?void 0:ue.sidebarMode)!=null?Ce:!1)||Zt(n)&&Un(n).reveal==="emerge")return;let T=(Ae=e.ownerDocument.defaultView)!=null?Ae:window,I=(Me=(ye=n.launcher)==null?void 0:ye.mobileFullscreen)!=null?Me:!0,H=(ut=(qe=n.launcher)==null?void 0:qe.mobileBreakpoint)!=null?ut:640;if(I&&T.innerWidth<=H||!Uc(n,x))return;let B=(Le=($=(Ke=n.launcher)==null?void 0:Ke.width)!=null?$:n.launcherWidth)!=null?Le:Bn,z=(wt=(He=(me=(Re=n.features)==null?void 0:Re.artifacts)==null?void 0:me.layout)==null?void 0:He.expandedPanelWidth)!=null?wt:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!cn?(F.style.width=z,F.style.maxWidth=z):(F.style.width=B,F.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(Cn=new ResizeObserver(()=>{Sn()}),Cn.observe(F))}else F.appendChild(j);e.appendChild(q);let Xn=()=>{var vt,Ut,on,Se,fn,sn,zn,nt,gt,hn,sr,Je,Et,Lr,Ir,Jo,Yo,Go,Ls,Is,qt,Xo,bo;let l=Zt(n),g=(Ut=(vt=n.launcher)==null?void 0:vt.sidebarMode)!=null?Ut:!1,b=l||g||((Se=(on=n.launcher)==null?void 0:on.fullHeight)!=null?Se:!1),T=((fn=n.launcher)==null?void 0:fn.enabled)===!1,I=(zn=(sn=n.theme)==null?void 0:sn.components)==null?void 0:zn.panel,H=ls(n),B=(yn,Hn)=>{var Jr;return yn==null||yn===""?Hn:(Jr=Lo(H,yn))!=null?Jr:yn},z=(nt=e.ownerDocument.defaultView)!=null?nt:window,O=(hn=(gt=n.launcher)==null?void 0:gt.mobileFullscreen)!=null?hn:!0,ue=(Je=(sr=n.launcher)==null?void 0:sr.mobileBreakpoint)!=null?Je:640,Ce=z.innerWidth<=ue,Ae=O&&Ce&&x,ye=(Lr=(Et=n.launcher)==null?void 0:Et.position)!=null?Lr:"bottom-left",Me=ye==="bottom-left"||ye==="top-left",qe=(Jo=(Ir=n.launcher)==null?void 0:Ir.zIndex)!=null?Jo:xn,ut=g||Ae?"none":"1px solid var(--persona-border)",Ke=Ae?"none":g?Me?"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&&!Ae&&(Ke="none",ut="none");let $=g||Ae?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Le=B(I==null?void 0:I.border,ut),Re=B(I==null?void 0:I.shadow,Ke),me=B(I==null?void 0:I.borderRadius,$);if(e.style.cssText="",q.style.cssText="",F.style.cssText="",j.style.cssText="",U.style.cssText="",ot.style.cssText="",Ae){q.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"),q.style.cssText=`
22
+ `,T.addEventListener("click",()=>{p=W,C.forEach((G,K)=>{let J=K<W;G.classList.toggle("selected",J),G.setAttribute("aria-checked",K===W-1?"true":"false")})}),C.push(T),x.appendChild(T)}g.appendChild(x);let k=null;if(u){let W=document.createElement("div");W.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),W.appendChild(k),g.appendChild(W)}let H=document.createElement("div");H.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),d.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=a,M.addEventListener("click",async()=>{if(p===null){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let W=(k==null?void 0:k.value.trim())||void 0;await r(p,W),d.remove()}catch(W){M.disabled=!1,M.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),H.appendChild(w),H.appendChild(M),g.appendChild(H),d.appendChild(g),d}function pa(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=n,v.appendChild(E);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,v.appendChild(x),f.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 k=document.createElement("div");k.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=d,k.appendChild(H),k.appendChild(w);let M=document.createElement("div");M.className="persona-feedback-numbers";let W=[];for(let I=0;I<=10;I++){let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-rating-btn persona-feedback-number-btn",Q.setAttribute("role","radio"),Q.setAttribute("aria-checked","false"),Q.setAttribute("aria-label",`Rating ${I} out of 10`),Q.textContent=String(I),Q.dataset.rating=String(I),I<=6?Q.classList.add("persona-feedback-detractor"):I<=8?Q.classList.add("persona-feedback-passive"):Q.classList.add("persona-feedback-promoter"),Q.addEventListener("click",()=>{g=I,W.forEach((Ce,re)=>{Ce.classList.toggle("selected",re===I),Ce.setAttribute("aria-checked",re===I?"true":"false")})}),W.push(Q),M.appendChild(Q)}C.appendChild(k),C.appendChild(M),f.appendChild(C);let T=null;if(u){let I=document.createElement("div");I.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"),I.appendChild(T),f.appendChild(I)}let G=document.createElement("div");G.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=i,K.addEventListener("click",()=>{t==null||t(),p.remove()});let J=document.createElement("button");return J.type="button",J.className="persona-feedback-btn persona-feedback-btn-submit",J.textContent=a,J.addEventListener("click",async()=>{if(g===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}J.disabled=!0,J.textContent="Submitting...";try{let I=(T==null?void 0:T.value.trim())||void 0;await r(g,I),p.remove()}catch(I){J.disabled=!1,J.textContent=a,console.error("[NPS Feedback] Failed to submit:",I)}}),G.appendChild(K),G.appendChild(J),f.appendChild(G),p.appendChild(f),p}var io="persona-chat-history",Su=30*1e3,Au={"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 Eu(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=Au[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function Ss(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function Tu(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Mu(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var ua=e=>!e||typeof e!="object"?{}:{...e},pd=e=>e.map(r=>({...r,streaming:!1})),ud=(e,r,t)=>{let n=e!=null&&e.markdown?Gr(e.markdown):null,s=To(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,d,p;let a=(c=o.text)!=null?c:"",i=(d=o.message.rawContent)!=null?d:null;if(r){let g=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):n?u=n(a):u=Eo(a),s?s(u):u}};function md(e){var i,u,c,d;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(d=e==null?void 0:e.iconStrokeWidth)!=null?d:.5,a=me(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,r.appendChild(p)}return r}var ma=(e,r,t)=>{var Ea,Ta,Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Na,Fa,Oa,$a,_a,ja,za,qa,Va,Ua,Ja,Ya,Ga,Xa,Ka,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=zs(r),s=vs.getForInstance(n.plugins);n.components&&Ar.registerAll(n.components);let o=cd(),a=(Ea=n.storageAdapter)!=null?Ea:sa(),i={},u=null,c=!1,d=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:b,open:A}=m;return A&&(c=!0),b}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let b=m!=null?m:{messages:[],metadata:{}};return d(b)});else{let m=l!=null?l:{messages:[],metadata:{}},b=d(m);b.metadata&&(i=ua(b.metadata)),(Ta=b.messages)!=null&&Ta.length&&(n={...n,initialMessages:b.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=d({messages:[],metadata:{}});(Ma=l.messages)!=null&&Ma.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>i,g=l=>{var b;i=(b=l({...i}))!=null?b:{},uo()},f=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Cs],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ao.message,ao.messageAndClick],E=ws({parsers:f,handlers:v,getSessionMetadata:p,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let x=(La=(ka=n.launcher)==null?void 0:ka.enabled)!=null?La:!0,C=(Pa=(Ia=n.launcher)==null?void 0:Ia.autoExpand)!=null?Pa:!1,k=(Wa=n.autoFocusInput)!=null?Wa:!1,H=C,w=x,M=(Ha=(Ra=n.layout)==null?void 0:Ra.header)==null?void 0:Ha.layout,W=!1,T=x?C:!0,G=!1,K=null,J=()=>{G=!0,K&&clearTimeout(K),K=setTimeout(()=>{G&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),G=!1)},1e4)},I=ud(n,E,J),Q=(Da=(Ba=n.features)==null?void 0:Ba.showReasoning)!=null?Da:!0,Ce=(Fa=(Na=n.features)==null?void 0:Na.showToolCalls)!=null?Fa:!0,re=($a=(Oa=n.features)==null?void 0:Oa.showEventStreamToggle)!=null?$a:!1,Ae=(ja=(_a=n.features)==null?void 0:_a.scrollToBottom)!=null?ja:{},he=`${(qa=typeof n.persistState=="object"?(za=n.persistState)==null?void 0:za.keyPrefix:void 0)!=null?qa:"persona-"}event-stream`,ke=re?new _o(he):null,Le=(Ja=(Ua=(Va=n.features)==null?void 0:Va.eventStream)==null?void 0:Ua.maxEvents)!=null?Ja:2e3,ae=re?new $o(Le,ke):null,xe=null,je=!1,de=null,ie=0;ke==null||ke.open().then(()=>ae==null?void 0:ae.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Ee={onCopy:l=>{var m,b;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(b=(m=n.messageActions)==null?void 0:m.onCopy)==null||b.call(m,l)},onFeedback:l=>{var m,b;o.emit("message:feedback",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(b=(m=n.messageActions)==null?void 0:m.onFeedback)==null||b.call(m,l)}},Be=(Ya=n.statusIndicator)!=null?Ya:{},it=l=>{var m,b,A,L;return l==="idle"?(m=Be.idleText)!=null?m:cn.idle:l==="connecting"?(b=Be.connectingText)!=null?b:cn.connecting:l==="connected"?(A=Be.connectedText)!=null?A:cn.connected:l==="error"?(L=Be.errorText)!=null?L:cn.error:cn[l]};function Et(l,m,b,A){if(A==="idle"&&b.idleLink){l.textContent="";let L=document.createElement("a");L.href=b.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=m,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=m}let{wrapper:q,panel:F}=Vc(n),le=Uc(n,x),{container:_,body:V,messagesWrapper:oe,suggestions:Oe,textarea:Z,sendButton:te,sendButtonWrapper:kt,composerForm:lt,statusText:Nt,introTitle:Xt,introSubtitle:$e,closeButton:ce,iconHolder:He,headerTitle:Pt,headerSubtitle:Wt,header:ot,footer:st,actionsRow:rn,leftActions:tn,rightActions:on}=le,j=le.micButton,Ie=le.micButtonWrapper,ue=le.attachmentButton,gt=le.attachmentButtonWrapper,Fe=le.attachmentInput,ne=le.attachmentPreviewsContainer;_.classList.add("persona-relative"),V.classList.add("persona-relative");let ye=12,De=()=>{var l;return(l=Ae.label)!=null?l:""},xt=()=>{var l;return(l=Ae.iconName)!=null?l:"arrow-down"},zt=()=>Ae.enabled!==!1,ct=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");ct.type="button",ct.style.display="none",ct.setAttribute("data-persona-scroll-to-bottom","true");let qt=h("span","persona-flex persona-items-center"),ft=h("span","");ct.append(qt,ft),_.appendChild(ct);let Ke=()=>{let m=st.style.display==="none"?0:st.offsetHeight;ct.style.bottom=`${m+ye}px`};Ke();let ht=()=>{let l=!!De();ct.setAttribute("aria-label",De()||"Jump to latest"),ct.title=De(),ct.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),qt.innerHTML="";let m=me(xt(),"14px","currentColor",2);m?(qt.appendChild(m),qt.style.display=""):qt.style.display="none",ft.textContent=De(),ft.style.display=l?"":"none"};ht();let We=null,Vt=null,Gn=s.find(l=>l.renderHeader);if(Gn!=null&&Gn.renderHeader){let l=Gn.renderHeader({config:n,defaultRenderer:()=>{let m=Sr({config:n,showClose:x});return to(_,m,n),m.header},onClose:()=>Rt(!1,"user")});if(l){let m=_.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),ot=l)}}let tr=()=>{var m,b,A,L;if(!ae)return;if(je=!0,!xe&&ae&&(xe=Qc({buffer:ae,getFullHistory:()=>ae.getAllFromStore(),onClose:()=>On(),config:n,plugins:s})),xe&&(V.style.display="none",(m=st.parentNode)==null||m.insertBefore(xe.element,st),xe.update()),Qe){Qe.style.boxShadow=`inset 0 0 0 1.5px ${Cn.actionIconColor}`;let R=(L=(A=(b=n.features)==null?void 0:b.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;R&&R.split(/\s+/).forEach(B=>B&&Qe.classList.add(B))}let l=()=>{if(!je)return;let R=Date.now();R-ie>=200&&(xe==null||xe.update(),ie=R),de=requestAnimationFrame(l)};ie=0,de=requestAnimationFrame(l),ar(),o.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var l,m,b;if(je){if(je=!1,xe&&xe.element.remove(),V.style.display="",Qe){Qe.style.boxShadow="";let A=(b=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:b.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&Qe.classList.remove(L))}de!==null&&(cancelAnimationFrame(de),de=null),ar(),o.emit("eventStream:closed",{timestamp:Date.now()})}},Qe=null;if(re){let l=(Xa=(Ga=n.features)==null?void 0:Ga.eventStream)==null?void 0:Xa.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Qe=h("button",m),Qe.style.width="28px",Qe.style.height="28px",Qe.style.color=Cn.actionIconColor,Qe.type="button",Qe.setAttribute("aria-label","Event Stream"),Qe.title="Event Stream";let b=me("activity","18px","currentColor",1.5);b&&Qe.appendChild(b);let A=le.clearChatButtonWrapper,L=le.closeButtonWrapper,R=A||L;R&&R.parentNode===ot?ot.insertBefore(Qe,R):ot.appendChild(Qe),Qe.addEventListener("click",()=>{je?On():tr()})}let Tr=l=>{var A,L,R;let m=n.attachments;if(!(m!=null&&m.enabled))return;let b=l.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let B=l.querySelector("[data-persona-composer-form]");B!=null&&B.parentNode?B.parentNode.insertBefore(b,B):l.insertBefore(b,l.firstChild)}if(!l.querySelector('input[type="file"]')){let B=h("input");B.type="file",B.accept=((A=m.allowedTypes)!=null?A:cr).join(","),B.multiple=((L=m.maxFiles)!=null?L:4)>1,B.style.display="none",B.setAttribute("aria-label",(R=m.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(B)}},Xn=s.find(l=>l.renderComposer);if(Xn!=null&&Xn.renderComposer){let l=n.composer,m=Xn.renderComposer({config:n,defaultRenderer:()=>Fo({config:n}).footer,onSubmit:b=>{var B;if(!D||D.isStreaming())return;let A=b.trim(),L=(B=We==null?void 0:We.hasAttachments())!=null?B:!1;if(!A&&!L)return;let R;L&&(R=[],R.push(...We.getContentParts()),A&&R.push(os(A))),D.sendMessage(A,{contentParts:R}),L&&We.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe==null||Fe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:b=>{n.composer={...n.composer,selectedModelId:b},n.agent&&(n.agent={...n.agent,model:b})},onVoiceToggle:((Ka=n.voiceRecognition)==null?void 0:Ka.enabled)===!0?()=>{Vt==null||Vt()}:void 0});m&&(st.replaceWith(m),st=m)}let Mr=l=>{let m=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),R=l.querySelector("[data-persona-composer-status]");m&&(lt=m),b&&(Z=b),A&&(te=A),L&&(j=L,Ie=L.parentElement),R&&(Nt=R);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(Oe=B);let z=l.querySelector(".persona-attachment-button");z&&(ue=z,gt=z.parentElement),Fe=l.querySelector('input[type="file"]'),ne=l.querySelector(".persona-attachment-previews");let O=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(rn=O)};Tr(st),Mr(st);let Pn=(Za=n.layout)==null?void 0:Za.contentMaxWidth;if(Pn&&lt&&(lt.style.maxWidth=Pn,lt.style.marginLeft="auto",lt.style.marginRight="auto"),Pn&&Oe&&(Oe.style.maxWidth=Pn,Oe.style.marginLeft="auto",Oe.style.marginRight="auto"),Pn&&ne&&(ne.style.maxWidth=Pn,ne.style.marginLeft="auto",ne.style.marginRight="auto"),(Qa=n.attachments)!=null&&Qa.enabled&&Fe&&ne){We=eo.fromConfig(n.attachments),We.setPreviewsContainer(ne),Fe.addEventListener("change",b=>{let A=b.target;We==null||We.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=md(l);_.appendChild(m)}(()=>{var A,L;let l=(L=(A=n.layout)==null?void 0:A.slots)!=null?L:{},m=R=>{switch(R){case"body-top":return _.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return oe;case"footer-top":return Oe;case"composer":return lt;case"footer-bottom":return Nt;default:return null}},b=(R,B)=>{var z;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")ot.insertBefore(B,ot.firstChild);else if(R==="header-right")ot.appendChild(B);else{let O=ot.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(B,O.nextSibling):ot.appendChild(B)}break;case"body-top":{let O=V.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(B):V.insertBefore(B,V.firstChild);break}case"body-bottom":V.appendChild(B);break;case"footer-top":Oe.replaceWith(B);break;case"footer-bottom":Nt.replaceWith(B);break;default:break}};for(let[R,B]of Object.entries(l))if(B)try{let z=B({config:n,defaultContent:()=>m(R)});z&&b(R,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,z)}})();let pr=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let A=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let R=b.getAttribute("data-bubble-type");R==="reasoning"?(ro.has(L)?ro.delete(L):ro.add(L),Xc(L,A)):R==="tool"&&(oo.has(L)?oo.delete(L):oo.add(L),Kc(L,A,n)),Rn.delete(L)};oe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),pr(l))}),oe.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),pr(l))});let nr=new Map;oe.addEventListener("click",l=>{var B;let b=l.target.closest(".persona-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let A=b.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let R=b.getAttribute("data-action");if(R==="copy"){let O=D.getMessages().find(ge=>ge.id===L);if(O&&Ee.onCopy){let ge=O.content||"";navigator.clipboard.writeText(ge).then(()=>{b.classList.add("persona-message-action-success");let ve=me("check",14,"currentColor",2);ve&&(b.innerHTML="",b.appendChild(ve)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let Se=me("copy",14,"currentColor",2);Se&&(b.innerHTML="",b.appendChild(Se))},2e3)}).catch(ve=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ve)}),Ee.onCopy(O)}}else if(R==="upvote"||R==="downvote")if(((B=nr.get(L))!=null?B:null)===R)nr.delete(L),b.classList.remove("persona-message-action-active");else{let ge=R==="upvote"?"downvote":"upvote",ve=A.querySelector(`[data-action="${ge}"]`);ve&&ve.classList.remove("persona-message-action-active"),nr.set(L,R),b.classList.add("persona-message-action-active");let be=D.getMessages().find(Te=>Te.id===L);be&&Ee.onFeedback&&Ee.onFeedback({type:R,messageId:be.id,message:be})}}),oe.addEventListener("click",l=>{let b=l.target.closest("button[data-approval-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let A=b.closest(".persona-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let R=b.getAttribute("data-approval-action");if(!R)return;let B=R==="approve"?"approved":"denied",O=D.getMessages().find(ve=>ve.id===L);if(!(O!=null&&O.approval))return;let ge=A.querySelector("[data-approval-buttons]");ge&&ge.querySelectorAll("button").forEach(Se=>{Se.disabled=!0,Se.style.opacity="0.5",Se.style.cursor="not-allowed"}),D.resolveApproval(O.approval,B)});let at=null,wn=null,$n={artifacts:[],selectedId:null},dn=!1,ur={current:null};oe.addEventListener("click",l=>{var Se,be,Te,ze,pt;let b=l.target.closest("[data-download-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let A=b.getAttribute("data-download-artifact");if(!A||((Te=(be=(Se=n.features)==null?void 0:Se.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Te.call(be,{type:"download",artifactId:A}))===!0)return;let R=D.getArtifactById(A),B=R==null?void 0:R.markdown,z=(R==null?void 0:R.title)||"artifact";if(!B){let Xe=b.closest("[data-open-artifact]"),$=Xe==null?void 0:Xe.closest("[data-message-id]"),Me=$==null?void 0:$.getAttribute("data-message-id");if(Me){let fe=D.getMessages().find(Re=>Re.id===Me);if(fe!=null&&fe.rawContent)try{let Re=JSON.parse(fe.rawContent);B=(ze=Re==null?void 0:Re.props)==null?void 0:ze.markdown,z=((pt=Re==null?void 0:Re.props)==null?void 0:pt.title)||z}catch{}}}if(!B)return;let O=new Blob([B],{type:"text/markdown"}),ge=URL.createObjectURL(O),ve=document.createElement("a");ve.href=ge,ve.download=`${z}.md`,ve.click(),URL.revokeObjectURL(ge)}),oe.addEventListener("click",l=>{var R,B,z;let b=l.target.closest("[data-open-artifact]");if(!b)return;let A=b.getAttribute("data-open-artifact");!A||((z=(B=(R=n.features)==null?void 0:R.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:z.call(B,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),dn=!1,D.selectArtifact(A),An())}),oe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Sn=null,wt=null,pn=null,Wn=null,mr=()=>{};function rr(){Wn==null||Wn(),Wn=null}let gr=()=>{var B;if(!Sn||!wt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),b=((B=e.ownerDocument.defaultView)!=null?B:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||b){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let A=Sn.firstElementChild;if(!A||A===wt)return;let L=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${L}px`,wt.style.zIndex="5";let R=A.offsetWidth-L/2;wt.style.left=`${Math.max(0,R)}px`},Kn=()=>{},An=()=>{var b,A,L,R,B;if(!at||!Fn(n))return;bs(e,n),xs(e,n),Kn();let l=(R=(L=(A=(b=n.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?R:520,m=F.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),at.update($n),dn?(at.setMobileOpen(!1),at.element.classList.add("persona-hidden"),(B=at.backdrop)==null||B.classList.add("persona-hidden")):$n.artifacts.length>0&&(at.element.classList.remove("persona-hidden"),at.setMobileOpen(!0)),mr()};if(Fn(n)){F.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(_),at=nd(n,{onSelect:b=>{var A;return(A=ur.current)==null?void 0:A.selectArtifact(b)},onDismiss:()=>{dn=!0,An()}}),at.element.classList.add("persona-hidden"),Sn=m,m.appendChild(l),m.appendChild(at.element),at.backdrop&&F.appendChild(at.backdrop),F.appendChild(m),mr=()=>{var A,L,R,B;if(!Sn||!at)return;if(!(((R=(L=(A=n.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:R.resizable)===!0)){pn==null||pn(),pn=null,rr(),wt&&(wt.remove(),wt=null),at.element.style.removeProperty("width"),at.element.style.removeProperty("maxWidth");return}if(!wt){let z=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,ge=(B=O.defaultView)!=null?B:window,ve=Se=>{var $,Me;if(!at||Se.button!==0||e.classList.contains("persona-artifact-narrow-host")||ge.innerWidth<=640)return;Se.preventDefault(),rr();let be=Se.clientX,Te=at.element.getBoundingClientRect().width,ze=(Me=($=n.features)==null?void 0:$.artifacts)==null?void 0:Me.layout,pt=Pe=>{let fe=Sn.getBoundingClientRect().width,Re=e.classList.contains("persona-artifact-appearance-seamless"),Ct=Re?0:ad(Sn,ge),bt=Re?0:z.getBoundingClientRect().width||6,Yt=Te-(Pe.clientX-be),sn=id(Yt,fe,Ct,bt,ze==null?void 0:ze.resizableMinWidth,ze==null?void 0:ze.resizableMaxWidth);at.element.style.width=`${sn}px`,at.element.style.maxWidth="none",gr()},Xe=()=>{O.removeEventListener("pointermove",pt),O.removeEventListener("pointerup",Xe),O.removeEventListener("pointercancel",Xe),Wn=null;try{z.releasePointerCapture(Se.pointerId)}catch{}};Wn=Xe,O.addEventListener("pointermove",pt),O.addEventListener("pointerup",Xe),O.addEventListener("pointercancel",Xe);try{z.setPointerCapture(Se.pointerId)}catch{}};z.addEventListener("pointerdown",ve),wt=z,Sn.insertBefore(z,at.element),pn=()=>{z.removeEventListener("pointerdown",ve)}}if(wt){let z=$n.artifacts.length>0&&!dn;wt.classList.toggle("persona-hidden",!z),gr()}},Kn=()=>{var ge,ve,Se,be,Te,ze,pt,Xe,$,Me,Pe,fe,Re,Ct;if(!x||!at||((ve=(ge=n.launcher)==null?void 0:ge.sidebarMode)!=null?ve:!1)||en(n)&&Jn(n).reveal==="emerge")return;let A=(Se=e.ownerDocument.defaultView)!=null?Se:window,L=(Te=(be=n.launcher)==null?void 0:be.mobileFullscreen)!=null?Te:!0,R=(pt=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?pt:640;if(L&&A.innerWidth<=R||!sd(n,x))return;let B=(Me=($=(Xe=n.launcher)==null?void 0:Xe.width)!=null?$:n.launcherWidth)!=null?Me:Nn,z=(Ct=(Re=(fe=(Pe=n.features)==null?void 0:Pe.artifacts)==null?void 0:fe.layout)==null?void 0:Re.expandedPanelWidth)!=null?Ct:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!dn?(F.style.width=z,F.style.maxWidth=z):(F.style.width=B,F.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(wn=new ResizeObserver(()=>{An()}),wn.observe(F))}else F.appendChild(_);e.appendChild(q);let Zn=()=>{var bt,Yt,sn,we,hn,an,Vn,rt,ut,yn,lr,Ue,At,Wr,Rr,Go,Xo,Ko,Rs,Hs,Ut,Zo,vo;let l=en(n),m=(Yt=(bt=n.launcher)==null?void 0:bt.sidebarMode)!=null?Yt:!1,b=l||m||((we=(sn=n.launcher)==null?void 0:sn.fullHeight)!=null?we:!1),A=((hn=n.launcher)==null?void 0:hn.enabled)===!1,L=(Vn=(an=n.theme)==null?void 0:an.components)==null?void 0:Vn.panel,R=ps(n),B=(bn,Dn)=>{var Yr;return bn==null||bn===""?Dn:(Yr=Po(R,bn))!=null?Yr:bn},z=(rt=e.ownerDocument.defaultView)!=null?rt:window,O=(yn=(ut=n.launcher)==null?void 0:ut.mobileFullscreen)!=null?yn:!0,ge=(Ue=(lr=n.launcher)==null?void 0:lr.mobileBreakpoint)!=null?Ue:640,ve=z.innerWidth<=ge,Se=O&&ve&&x,be=(Wr=(At=n.launcher)==null?void 0:At.position)!=null?Wr:"bottom-left",Te=be==="bottom-left"||be==="top-left",ze=(Go=(Rr=n.launcher)==null?void 0:Rr.zIndex)!=null?Go:vn,pt=m||Se?"none":"1px solid var(--persona-border)",Xe=Se?"none":m?Te?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Se&&(Xe="none",pt="none");let $=m||Se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Me=B(L==null?void 0:L.border,pt),Pe=B(L==null?void 0:L.shadow,Xe),fe=B(L==null?void 0:L.borderRadius,$);if(e.style.cssText="",q.style.cssText="",F.style.cssText="",_.style.cssText="",V.style.cssText="",st.style.cssText="",Se){q.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"),q.style.cssText=`
23
23
  position: fixed !important;
24
24
  inset: 0 !important;
25
25
  width: 100% !important;
@@ -29,7 +29,7 @@ import{Marked as Bd}from"marked";var Dd=e=>{if(e)return e},Qo=e=>{var s,o;let r=
29
29
  padding: 0 !important;
30
30
  display: flex !important;
31
31
  flex-direction: column !important;
32
- z-index: ${qe} !important;
32
+ z-index: ${ze} !important;
33
33
  background-color: var(--persona-surface, #ffffff) !important;
34
34
  `,F.style.cssText=`
35
35
  position: relative !important;
@@ -44,7 +44,7 @@ import{Marked as Bd}from"marked";var Dd=e=>{if(e)return e},Qo=e=>{var s,o;let r=
44
44
  padding: 0 !important;
45
45
  box-shadow: none !important;
46
46
  border-radius: 0 !important;
47
- `,j.style.cssText=`
47
+ `,_.style.cssText=`
48
48
  display: flex !important;
49
49
  flex-direction: column !important;
50
50
  flex: 1 1 0% !important;
@@ -55,19 +55,19 @@ import{Marked as Bd}from"marked";var Dd=e=>{if(e)return e},Qo=e=>{var s,o;let r=
55
55
  overflow: hidden !important;
56
56
  border-radius: 0 !important;
57
57
  border: none !important;
58
- `,U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",ot.style.flexShrink="0",W=!0;return}let He=(Go=(Yo=n==null?void 0:n.launcher)==null?void 0:Yo.width)!=null?Go:n==null?void 0:n.launcherWidth,wt=He!=null?He:Bn;if(!g&&!l)T&&b?(F.style.width="100%",F.style.maxWidth="100%"):(F.style.width=wt,F.style.maxWidth=wt);else if(l)if(Un(n).reveal==="emerge"){let Hn=Un(n).width;F.style.width=Hn,F.style.maxWidth=Hn}else F.style.width="100%",F.style.maxWidth="100%";if(Gn(),F.style.boxShadow=Re,F.style.borderRadius=me,j.style.border=Le,j.style.borderRadius=me,l&&!Ae&&(I==null?void 0:I.border)===void 0&&(j.style.border="none",Un(n).side==="right"?j.style.borderLeft="1px solid var(--persona-border)":j.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",T&&(e.style.width="100%"),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%",T&&(q.style.overflow="hidden"),F.style.display="flex",F.style.flexDirection="column",F.style.flex="1 1 0%",F.style.minHeight="0",F.style.maxHeight="100%",F.style.height="100%",F.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",ot.style.flexShrink="0"),q.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&&!T&&!l&&((Ls=Vn[ye])!=null?Ls:Vn["bottom-right"]).split(" ").forEach(Hn=>q.classList.add(Hn)),g){let yn=(qt=(Is=n.launcher)==null?void 0:Is.sidebarWidth)!=null?qt:"420px";q.style.cssText=`
58
+ `,V.style.flex="1 1 0%",V.style.minHeight="0",V.style.overflowY="auto",st.style.flexShrink="0",W=!0;return}let Re=(Ko=(Xo=n==null?void 0:n.launcher)==null?void 0:Xo.width)!=null?Ko:n==null?void 0:n.launcherWidth,Ct=Re!=null?Re:Nn;if(!m&&!l)A&&b?(F.style.width="100%",F.style.maxWidth="100%"):(F.style.width=Ct,F.style.maxWidth=Ct);else if(l)if(Jn(n).reveal==="emerge"){let Dn=Jn(n).width;F.style.width=Dn,F.style.maxWidth=Dn}else F.style.width="100%",F.style.maxWidth="100%";if(Kn(),F.style.boxShadow=Pe,F.style.borderRadius=fe,_.style.border=Me,_.style.borderRadius=fe,l&&!Se&&(L==null?void 0:L.border)===void 0&&(_.style.border="none",Jn(n).side==="right"?_.style.borderLeft="1px solid var(--persona-border)":_.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),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%",A&&(q.style.overflow="hidden"),F.style.display="flex",F.style.flexDirection="column",F.style.flex="1 1 0%",F.style.minHeight="0",F.style.maxHeight="100%",F.style.height="100%",F.style.overflow="hidden",_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.overflow="hidden",V.style.flex="1 1 0%",V.style.minHeight="0",V.style.overflowY="auto",st.style.flexShrink="0"),q.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!A&&!l&&((Rs=Yn[be])!=null?Rs:Yn["bottom-right"]).split(" ").forEach(Dn=>q.classList.add(Dn)),m){let bn=(Ut=(Hs=n.launcher)==null?void 0:Hs.sidebarWidth)!=null?Ut:"420px";q.style.cssText=`
59
59
  position: fixed !important;
60
60
  top: 0 !important;
61
61
  bottom: 0 !important;
62
- width: ${yn} !important;
62
+ width: ${bn} !important;
63
63
  height: 100vh !important;
64
64
  max-height: 100vh !important;
65
65
  margin: 0 !important;
66
66
  padding: 0 !important;
67
67
  display: flex !important;
68
68
  flex-direction: column !important;
69
- z-index: ${qe} !important;
70
- ${Me?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
69
+ z-index: ${ze} !important;
70
+ ${Te?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
71
71
  `,F.style.cssText=`
72
72
  position: relative !important;
73
73
  display: flex !important;
@@ -79,9 +79,9 @@ import{Marked as Bd}from"marked";var Dd=e=>{if(e)return e},Qo=e=>{var s,o;let r=
79
79
  min-height: 0 !important;
80
80
  margin: 0 !important;
81
81
  padding: 0 !important;
82
- box-shadow: ${Re} !important;
83
- border-radius: ${me} !important;
84
- `,F.style.setProperty("width","100%","important"),F.style.setProperty("max-width","100%","important"),j.style.cssText=`
82
+ box-shadow: ${Pe} !important;
83
+ border-radius: ${fe} !important;
84
+ `,F.style.setProperty("width","100%","important"),F.style.setProperty("max-width","100%","important"),_.style.cssText=`
85
85
  display: flex !important;
86
86
  flex-direction: column !important;
87
87
  flex: 1 1 0% !important;
@@ -90,29 +90,29 @@ import{Marked as Bd}from"marked";var Dd=e=>{if(e)return e},Qo=e=>{var s,o;let r=
90
90
  min-height: 0 !important;
91
91
  max-height: 100% !important;
92
92
  overflow: hidden !important;
93
- border-radius: ${me} !important;
94
- border: ${Le} !important;
95
- `,ot.style.cssText=`
93
+ border-radius: ${fe} !important;
94
+ border: ${Me} !important;
95
+ `,st.style.cssText=`
96
96
  flex-shrink: 0 !important;
97
97
  border-top: none !important;
98
98
  padding: 8px 16px 12px 16px !important;
99
- `}if(!T&&!l){let yn="max-height: -moz-available !important; max-height: stretch !important;",Hn=g?"":"padding-top: 1.25em !important;",Jr=g?"":`z-index: ${(bo=(Xo=n.launcher)==null?void 0:Xo.zIndex)!=null?bo:xn} !important;`;q.style.cssText+=yn+Hn+Jr}};Xn(),Dr(e,n),fs(e,n),hs(e,n);let At=[],Ft=null,Ot=null;At.push(()=>{Ft==null||Ft(),Ft=null,Ot==null||Ot(),Ot=null}),Cn&&At.push(()=>{Cn==null||Cn.disconnect(),Cn=null}),At.push(()=>{dn==null||dn(),dn=null,tr(),St&&(St.remove(),St=null),st==null||st.element.style.removeProperty("width"),st==null||st.element.style.removeProperty("maxWidth")}),ne&&At.push(()=>{ce!==null&&(cancelAnimationFrame(ce),ce=null),be==null||be.destroy(),be=null,se==null||se.destroy(),se=null,Ie=null});let An=null,ur=()=>{An&&(An(),An=null),n.colorScheme==="auto"&&(An=zs(()=>{Dr(e,n)}))};ur(),At.push(()=>{An&&(An(),An=null)});let On=Fc(_e),En=null,D,$n=!1,Wn=Ac(),gr=0,gn=cs(),Tn=0,oe=null,_n=!1,Or=1,lo=8,$r=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},co=(ja=(_a=n.voiceRecognition)==null?void 0:_a.autoResume)!=null?ja:!1,Rn=l=>{o.emit("voice:state",{active:Qe.active,source:l,timestamp:Date.now()})},mn=()=>{m(l=>({...l,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},$o=()=>{var T,I;if(((T=n.voiceRecognition)==null?void 0:T.enabled)===!1)return;let l=ca(i.voiceState),g=!!l.active,b=Number((I=l.timestamp)!=null?I:0);Qe.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-b<lu&&setTimeout(()=>{var H,B;Qe.active||(Qe.manuallyDeactivated=!1,((B=(H=n.voiceRecognition)==null?void 0:H.provider)==null?void 0:B.type)==="runtype"?D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Rn("restore"),D.isVoiceActive()&&hr()}):Mr("restore"))},1e3)},_o=()=>D?Kc(D.getMessages()).filter(l=>!l.__skipPersist):[];function po(l){if(!(a!=null&&a.save))return;let b={messages:l?Kc(l):D?_o():[],metadata:i};try{let T=a.save(b);T instanceof Promise&&T.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)}}let nr=null,jo=()=>q.querySelector("#persona-scroll-container")||U,_r=()=>{nr!==null&&(cancelAnimationFrame(nr),nr=null),_n=!1},jr=()=>{oe!==null&&(cancelAnimationFrame(oe),oe=null),_r()},rr=()=>{if(!_t()||ze){dt.parentNode&&dt.remove(),dt.style.display="none";return}dt.parentNode!==j&&j.appendChild(dt),Ze();let l=Po(U)>0;dt.style.display=gn.isFollowing()||!l?"none":""},uo=()=>{gn.pause()&&(jr(),rr())},mr=()=>{gn.resume(),rr()},fr=(l=!1)=>{gn.isFollowing()&&(!l&&!$n||(jr(),oe=requestAnimationFrame(()=>{oe=null,gn.isFollowing()&&zo(jo(),l?220:140)})))},zo=(l,g=500)=>{let b=l.scrollTop,T=Po(l),I=T-b;if(Math.abs(I)<1){Tn=l.scrollTop;return}_r();let H=performance.now();_n=!0;let B=O=>1-Math.pow(1-O,3),z=O=>{if(!gn.isFollowing()){_r();return}let ue=Po(l);ue!==T&&(T=ue,I=T-b);let Ce=O-H,Ae=Math.min(Ce/g,1),ye=B(Ae),Me=b+I*ye;l.scrollTop=Me,Tn=l.scrollTop,Ae<1?nr=requestAnimationFrame(z):(l.scrollTop=T,Tn=l.scrollTop,nr=null,_n=!1)};nr=requestAnimationFrame(z)},qo=l=>{let g=new Map;l.forEach(b=>{let T=$r.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!T&&b.role==="assistant"&&o.emit("assistant:message",b),b.role==="assistant"&&(T!=null&&T.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(T?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),$r.clear(),g.forEach((b,T)=>{$r.set(T,b)})},Er=(l,g,b)=>{var Ae,ye,Me,qe,ut,Ke;let T=document.createElement("div"),H=(()=>{var Le;let $=s.find(Re=>Re.renderLoadingIndicator);if($!=null&&$.renderLoadingIndicator)return $.renderLoadingIndicator;if((Le=n.loadingIndicator)!=null&&Le.render)return n.loadingIndicator.render})(),B=($,Le)=>Le==null?!1:typeof Le=="string"?($.textContent=Le,!0):($.appendChild(Le),!0),z=new Set;if(g.forEach($=>{var Ut,on;z.add($.id);let Le=Sc($,gr),Re=Ec(Wn,$.id,Le);if(Re){T.appendChild(Re.cloneNode(!0));return}let me=null,He=s.find(Se=>!!($.variant==="reasoning"&&Se.renderReasoning||$.variant==="tool"&&Se.renderToolCall||$.variant==="approval"&&Se.renderApproval||!$.variant&&Se.renderMessage)),wt=(Ut=n.layout)==null?void 0:Ut.messages;if(He)if($.variant==="reasoning"&&$.reasoning&&He.renderReasoning){if(!Q)return;me=He.renderReasoning({message:$,defaultRenderer:()=>Ys($,n),config:n})}else if($.variant==="tool"&&$.toolCall&&He.renderToolCall){if(!we)return;me=He.renderToolCall({message:$,defaultRenderer:()=>Gs($,n),config:n})}else if($.variant==="approval"&&$.approval&&He.renderApproval){if(n.approval===!1)return;me=He.renderApproval({message:$,defaultRenderer:()=>Xs($,n),config:n})}else He.renderMessage&&(me=He.renderMessage({message:$,defaultRenderer:()=>{let Se=No($,b,wt,n.messageActions,Te,{loadingIndicatorRenderer:H,widgetConfig:n});return $.role!=="user"&&Qs(Se,$,n,D),Se},config:n}));if(!me&&$.role==="assistant"&&!$.variant&&n.enableComponentStreaming!==!1&&sa($)){let fn=aa($);if(fn){let sn=oa(fn,{config:n,message:$,transform:b});if(sn)if(n.wrapComponentDirectiveInBubble!==!1){let nt=document.createElement("div");if(nt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),nt.id=`bubble-${$.id}`,nt.setAttribute("data-message-id",$.id),$.content&&$.content.trim()){let gt=document.createElement("div");gt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gt.innerHTML=b({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),nt.appendChild(gt)}nt.appendChild(sn),me=nt}else{let nt=document.createElement("div");if(nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",nt.id=`bubble-${$.id}`,nt.setAttribute("data-message-id",$.id),nt.setAttribute("data-persona-component-directive","true"),$.content&&$.content.trim()){let gt=document.createElement("div");gt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gt.innerHTML=b({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),nt.appendChild(gt)}nt.appendChild(sn),me=nt}}}if(!me)if($.variant==="reasoning"&&$.reasoning){if(!Q)return;me=Ys($,n)}else if($.variant==="tool"&&$.toolCall){if(!we)return;me=Gs($,n)}else if($.variant==="approval"&&$.approval){if(n.approval===!1)return;me=Xs($,n)}else{let Se=(on=n.layout)==null?void 0:on.messages;Se!=null&&Se.renderUserMessage&&$.role==="user"?me=Se.renderUserMessage({message:$,config:n,streaming:!!$.streaming}):Se!=null&&Se.renderAssistantMessage&&$.role==="assistant"?me=Se.renderAssistantMessage({message:$,config:n,streaming:!!$.streaming}):me=No($,b,Se,n.messageActions,Te,{loadingIndicatorRenderer:H,widgetConfig:n}),$.role!=="user"&&me&&Qs(me,$,n,D)}let vt=document.createElement("div");vt.className="persona-flex",vt.id=`wrapper-${$.id}`,vt.setAttribute("data-wrapper-id",$.id),$.role==="user"&&vt.classList.add("persona-justify-end"),(me==null?void 0:me.getAttribute("data-persona-component-directive"))==="true"&&vt.classList.add("persona-w-full"),vt.appendChild(me),Tc(Wn,$.id,Le,vt),T.appendChild(vt)}),(ye=(Ae=n.features)==null?void 0:Ae.toolCallDisplay)!=null&&ye.grouped){let $=[],Le=[];g.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&we){Le.push(Re);return}Le.length>1&&$.push(Le),Le=[]}),Le.length>1&&$.push(Le),$.forEach((Re,me)=>{var sn,zn;let He=Re.map(nt=>Array.from(T.children).find(gt=>gt instanceof HTMLElement&&gt.getAttribute("data-wrapper-id")===nt.id)).filter(nt=>!!nt);if(He.length<2)return;let wt=document.createElement("div");wt.className="persona-flex",wt.id=`wrapper-tool-group-${me}-${Re[0].id}`,wt.setAttribute("data-wrapper-id",`tool-group-${me}-${Re[0].id}`);let vt=document.createElement("div");vt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",vt.setAttribute("data-persona-tool-group","true");let Ut=document.createElement("div");Ut.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let on=`Called ${Re.length} tools`,Se=(zn=(sn=n.toolCall)==null?void 0:sn.renderGroupedSummary)==null?void 0:zn.call(sn,{messages:Re,toolCalls:Re.map(nt=>nt.toolCall).filter(nt=>!!nt),defaultSummary:on,config:n});B(Ut,Se)||(Ut.textContent=on);let fn=document.createElement("div");fn.className="persona-tool-group-stack persona-flex persona-flex-col",vt.append(Ut,fn),wt.appendChild(vt),He[0].before(wt),He.forEach((nt,gt)=>{let hn=document.createElement("div");hn.className="persona-tool-group-item persona-relative",hn.setAttribute("data-persona-tool-group-item","true"),gt<He.length-1&&hn.setAttribute("data-persona-tool-group-connector","true"),hn.appendChild(nt),fn.appendChild(hn)})})}Mc(Wn,z);let O=g.some($=>$.role==="assistant"&&$.streaming),ue=g[g.length-1],Ce=(ue==null?void 0:ue.role)==="assistant"&&!ue.streaming&&ue.variant!=="approval";if($n&&g.some($=>$.role==="user")&&!O&&!Ce){let $={config:n,streaming:!0,location:"standalone",defaultRenderer:to},Le=s.find(me=>me.renderLoadingIndicator),Re=null;if(Le!=null&&Le.renderLoadingIndicator&&(Re=Le.renderLoadingIndicator($)),Re===null&&((Me=n.loadingIndicator)!=null&&Me.render)&&(Re=n.loadingIndicator.render($)),Re===null&&(Re=to()),Re){let me=document.createElement("div"),He=((qe=n.loadingIndicator)==null?void 0:qe.showBubble)!==!1;me.className=He?["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(Re);let wt=document.createElement("div");wt.className="persona-flex",wt.id="wrapper-typing-indicator",wt.setAttribute("data-wrapper-id","typing-indicator"),wt.appendChild(me),T.appendChild(wt)}}if(!$n&&g.length>0){let $=g[g.length-1],Le={config:n,lastMessage:$,messageCount:g.length},Re=s.find(He=>He.renderIdleIndicator),me=null;if(Re!=null&&Re.renderIdleIndicator&&(me=Re.renderIdleIndicator(Le)),me===null&&((ut=n.loadingIndicator)!=null&&ut.renderIdle)&&(me=n.loadingIndicator.renderIdle(Le)),me){let He=document.createElement("div"),wt=((Ke=n.loadingIndicator)==null?void 0:Ke.showBubble)!==!1;He.className=wt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(me);let vt=document.createElement("div");vt.className="persona-flex",vt.id="wrapper-idle-indicator",vt.setAttribute("data-wrapper-id","idle-indicator"),vt.appendChild(He),T.appendChild(vt)}}wc(l,T)},Tr=()=>{var O,ue,Ce,Ae,ye;if(!x)return;let l=Zt(n),g=(O=e.ownerDocument.defaultView)!=null?O:window,b=(Ce=(ue=n.launcher)==null?void 0:ue.mobileBreakpoint)!=null?Ce:640,T=(ye=(Ae=n.launcher)==null?void 0:Ae.mobileFullscreen)!=null?ye:!0,I=g.innerWidth<=b,H=T&&I&&x,B=Un(n).reveal;E?(q.style.removeProperty("display"),q.style.display=l?"flex":"",q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-95","persona-opacity-0"),F.classList.add("persona-scale-100","persona-opacity-100"),ke?ke.element.style.display="none":y&&(y.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!H?(q.style.removeProperty("display"),q.style.display="flex",q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(q.style.setProperty("display","none","important"),q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(q.style.display="",q.classList.add("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100"),F.classList.add("persona-scale-95","persona-opacity-0")),ke?ke.element.style.display=l?"none":"":y&&(y.style.display=l?"none":""))},Wt=(l,g="user")=>{var H,B;if(!x||E===l)return;let b=E;E=l,Tr();let T=(()=>{var Me,qe,ut,Ke,$,Le,Re;let z=(qe=(Me=n.launcher)==null?void 0:Me.sidebarMode)!=null?qe:!1,O=(ut=e.ownerDocument.defaultView)!=null?ut:window,ue=($=(Ke=n.launcher)==null?void 0:Ke.mobileFullscreen)!=null?$:!0,Ce=(Re=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Re:640,Ae=O.innerWidth<=Ce,ye=Zt(n)&&ue&&Ae;return z||ue&&Ae&&x||ye})();if(E&&T){if(!Ft){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Ft=qs(O,(B=(H=n.launcher)==null?void 0:H.zIndex)!=null?B:xn))}Ot||(Ot=Us(e.ownerDocument))}else E||(Ft==null||Ft(),Ft=null,Ot==null||Ot(),Ot=null);E&&(ve(),fr(!0));let I={open:E,source:g,timestamp:Date.now()};E&&!b?o.emit("widget:opened",I):!E&&b&&o.emit("widget:closed",I),o.emit("widget:state",{open:E,launcherEnabled:x,voiceActive:Qe.active,streaming:D.isStreaming()})},zr=l=>{ee.disabled=l,_&&(_.disabled=l),On.buttons.forEach(g=>{g.disabled=l}),ot.dataset.personaComposerStreaming=l?"true":"false",ot.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},qr=()=>{Qe.active||Z&&Z.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>qr(),200)});let go=()=>{var b,T,I,H,B,z,O,ue,Ce,Ae,ye;Jt.textContent=(T=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?T:"Hello \u{1F44B}",je.textContent=(H=(I=n.copy)==null?void 0:I.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",Z.placeholder=(z=(B=n.copy)==null?void 0:B.inputPlaceholder)!=null?z:"How can I help...";let l=U.querySelector("[data-persona-intro-card]");if(l){let Me=((O=n.copy)==null?void 0:O.showWelcomeCard)!==!1;l.style.display=Me?"":"none",Me?(U.classList.remove("persona-gap-3"),U.classList.add("persona-gap-6")):(U.classList.remove("persona-gap-6"),U.classList.add("persona-gap-3"))}(Ce=(ue=n.sendButton)==null?void 0:ue.useIcon)!=null&&Ce||(ee.textContent=(ye=(Ae=n.copy)==null?void 0:Ae.sendButtonLabel)!=null?ye:"Send"),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.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=>{m(g=>({...g,sessionId:l}))}}),D=new Mo(n,{onMessagesChanged(l){Er(re,l,L),D&&(l.some(I=>I.role==="user")?On.render([],D,Z,l):On.render(n.suggestionChips,D,Z,l,n.suggestionChipsConfig)),fr(!$n),qo(l);let g=[...l].reverse().find(T=>T.role==="user"),b=Qe.lastUserMessageId;g&&g.id!==b&&(Qe.lastUserMessageId=g.id,o.emit("user:message",g)),Qe.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),po(l)},onStatusChanged(l){var T;let g=(T=n.statusIndicator)!=null?T:{};Tt(Dt,(I=>{var H,B,z,O;return I==="idle"?(H=g.idleText)!=null?H:ln.idle:I==="connecting"?(B=g.connectingText)!=null?B:ln.connecting:I==="connected"?(z=g.connectedText)!=null?z:ln.connected:I==="error"?(O=g.errorText)!=null?O:ln.error:ln[I]})(l),g,l)},onStreamingChanged(l){$n=l,zr(l),D&&Er(re,D.getMessages(),L),l||fr(!0)},onVoiceStatusChanged(l){var g,b;if(((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype")switch(l){case"listening":break;case"processing":Be(),Vo();break;case"speaking":Be(),X();break;default:l==="idle"&&D.isBargeInActive()?(Be(),hr(),_==null||_.setAttribute("aria-label","End voice session")):(Qe.active=!1,Be(),Rn("system"),mn());break}},onArtifactsState(l){Fn=l,Sn()}}),cr.current=D,((qa=(za=n.voiceRecognition)==null?void 0:za.provider)==null?void 0:qa.type)==="runtype")try{D.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&D.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),se&&D.setSSEEventCallback((l,g)=>{se==null||se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),u&&u.then(l=>{var g;l&&(l.metadata&&(i=ca(l.metadata),A.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 mo=l=>{var I;l.preventDefault();let g=Z.value.trim(),b=(I=Ue==null?void 0:Ue.hasAttachments())!=null?I:!1;if(!g&&!b)return;let T;b&&(T=[],T.push(...Ue.getContentParts()),g&&T.push(Ns(g))),Z.value="",Z.style.height="auto",D.sendMessage(g,{contentParts:T}),b&&Ue.clearAttachments()},fo=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),ee.click())},ho=async l=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!Ue)return;let g=du(l.clipboardData);g.length!==0&&(l.preventDefault(),await Ue.handleFiles(g))},pn=null,Mn=!1,or=null,Ve=null,yo=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Mr=(l="user")=>{var H,B,z,O,ue,Ce,Ae;if(Mn||D.isStreaming())return;let g=yo();if(!g)return;pn=new g;let T=(B=((H=n.voiceRecognition)!=null?H:{}).pauseDuration)!=null?B:2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let I=Z.value;pn.onresult=ye=>{let Me="",qe="";for(let Ke=0;Ke<ye.results.length;Ke++){let $=ye.results[Ke],Le=$[0].transcript;$.isFinal?Me+=Le+" ":qe=Le}let ut=I+Me+qe;Z.value=ut,or&&clearTimeout(or),(Me||qe)&&(or=window.setTimeout(()=>{let Ke=Z.value.trim();Ke&&pn&&Mn&&(jn(),Z.value="",Z.style.height="auto",D.sendMessage(Ke,{viaVoice:!0}))},T))},pn.onerror=ye=>{ye.error!=="no-speech"&&jn()},pn.onend=()=>{if(Mn){let ye=Z.value.trim();ye&&ye!==I.trim()&&(Z.value="",Z.style.height="auto",D.sendMessage(ye,{viaVoice:!0})),jn()}};try{if(pn.start(),Mn=!0,Qe.active=!0,l!=="system"&&(Qe.manuallyDeactivated=!1),Rn(l),mn(),_){let ye=(z=n.voiceRecognition)!=null?z:{};Ve={backgroundColor:_.style.backgroundColor,color:_.style.color,borderColor:_.style.borderColor,iconName:(O=ye.iconName)!=null?O:"mic",iconSize:parseFloat((Ae=(Ce=ye.iconSize)!=null?Ce:(ue=n.sendButton)==null?void 0:ue.size)!=null?Ae:"40")||24};let Me=ye.recordingBackgroundColor,qe=ye.recordingIconColor,ut=ye.recordingBorderColor;if(_.classList.add("persona-voice-recording"),_.style.backgroundColor=Me!=null?Me:"var(--persona-voice-recording-bg, #ef4444)",_.style.color=qe!=null?qe:"var(--persona-voice-recording-indicator, #ffffff)",qe){let Ke=_.querySelector("svg");Ke&&Ke.setAttribute("stroke",qe)}ut&&(_.style.borderColor=ut),_.setAttribute("aria-label","Stop voice recognition")}}catch{jn("system")}},jn=(l="user")=>{if(Mn){if(Mn=!1,or&&(clearTimeout(or),or=null),pn){try{pn.stop()}catch{}pn=null}if(Qe.active=!1,Rn(l),mn(),_){if(_.classList.remove("persona-voice-recording"),Ve){_.style.backgroundColor=Ve.backgroundColor,_.style.color=Ve.color,_.style.borderColor=Ve.borderColor;let g=_.querySelector("svg");g&&g.setAttribute("stroke",Ve.color||"currentColor"),Ve=null}_.setAttribute("aria-label","Start voice recognition")}}},Uo=(l,g)=>{var $,Le,Re,me,He,wt,vt,Ut;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),T=(($=l==null?void 0:l.provider)==null?void 0:$.type)==="runtype";if(!(b||T))return null;let H=h("div","persona-send-button-wrapper"),B=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let z=(Le=l==null?void 0:l.iconName)!=null?Le:"mic",O=(Re=g==null?void 0:g.size)!=null?Re:"40px",ue=(me=l==null?void 0:l.iconSize)!=null?me:O,Ce=parseFloat(ue)||24,Ae=(He=l==null?void 0:l.backgroundColor)!=null?He:g==null?void 0:g.backgroundColor,ye=(wt=l==null?void 0:l.iconColor)!=null?wt:g==null?void 0:g.textColor;B.style.width=ue,B.style.height=ue,B.style.minWidth=ue,B.style.minHeight=ue,B.style.fontSize="18px",B.style.lineHeight="1",ye?B.style.color=ye:B.style.color="var(--persona-text, #111827)";let qe=ge(z,Ce,ye||"currentColor",1.5);qe?B.appendChild(qe):B.textContent="\u{1F3A4}",Ae?B.style.backgroundColor=Ae:B.style.backgroundColor="",l!=null&&l.borderWidth&&(B.style.borderWidth=l.borderWidth,B.style.borderStyle="solid"),l!=null&&l.borderColor&&(B.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(B.style.paddingLeft=l.paddingX,B.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(B.style.paddingTop=l.paddingY,B.style.paddingBottom=l.paddingY),H.appendChild(B);let ut=(vt=l==null?void 0:l.tooltipText)!=null?vt:"Start voice recognition";if(((Ut=l==null?void 0:l.showTooltip)!=null?Ut:!1)&&ut){let on=h("div","persona-send-button-tooltip");on.textContent=ut,H.appendChild(on)}return{micButton:B,micButtonWrapper:H}},Ur=()=>{var g,b,T,I,H;if(!_||Ve)return;let l=(g=n.voiceRecognition)!=null?g:{};Ve={backgroundColor:_.style.backgroundColor,color:_.style.color,borderColor:_.style.borderColor,iconName:(b=l.iconName)!=null?b:"mic",iconSize:parseFloat((H=(I=l.iconSize)!=null?I:(T=n.sendButton)==null?void 0:T.size)!=null?H:"40")||24}},Vr=(l,g)=>{var H,B,z,O,ue;if(!_)return;let b=_.querySelector("svg");b&&b.remove();let T=(ue=Ve==null?void 0:Ve.iconSize)!=null?ue:parseFloat((O=(z=(H=n.voiceRecognition)==null?void 0:H.iconSize)!=null?z:(B=n.sendButton)==null?void 0:B.size)!=null?O:"40")||24,I=ge(l,T,g,1.5);I&&_.appendChild(I)},kr=()=>{_&&_.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},hr=()=>{var I;if(!_)return;Ur();let l=(I=n.voiceRecognition)!=null?I:{},g=l.recordingBackgroundColor,b=l.recordingIconColor,T=l.recordingBorderColor;if(kr(),_.classList.add("persona-voice-recording"),_.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",_.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let H=_.querySelector("svg");H&&H.setAttribute("stroke",b)}T&&(_.style.borderColor=T),_.setAttribute("aria-label","Stop voice recognition")},Vo=()=>{var z,O,ue,Ce,Ae,ye,Me,qe;if(!_)return;Ur();let l=(z=n.voiceRecognition)!=null?z:{},g=D.getVoiceInterruptionMode(),b=(O=l.processingIconName)!=null?O:"loader",T=(Ce=(ue=l.processingIconColor)!=null?ue:Ve==null?void 0:Ve.color)!=null?Ce:"",I=(ye=(Ae=l.processingBackgroundColor)!=null?Ae:Ve==null?void 0:Ve.backgroundColor)!=null?ye:"",H=(qe=(Me=l.processingBorderColor)!=null?Me:Ve==null?void 0:Ve.borderColor)!=null?qe:"";kr(),_.classList.add("persona-voice-processing"),_.style.backgroundColor=I,_.style.borderColor=H;let B=T||"currentColor";_.style.color=B,Vr(b,B),_.setAttribute("aria-label","Processing voice input"),g==="none"&&(_.style.cursor="default")},X=()=>{var ue,Ce,Ae,ye,Me,qe,ut,Ke,$,Le,Re,me;if(!_)return;Ur();let l=(ue=n.voiceRecognition)!=null?ue:{},g=D.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",T=(Ce=l.speakingIconName)!=null?Ce:b,I=(qe=l.speakingIconColor)!=null?qe:g==="barge-in"?(ye=(Ae=l.recordingIconColor)!=null?Ae:Ve==null?void 0:Ve.color)!=null?ye:"":(Me=Ve==null?void 0:Ve.color)!=null?Me:"",H=($=l.speakingBackgroundColor)!=null?$:g==="barge-in"?(ut=l.recordingBackgroundColor)!=null?ut:"var(--persona-voice-recording-bg, #ef4444)":(Ke=Ve==null?void 0:Ve.backgroundColor)!=null?Ke:"",B=(me=l.speakingBorderColor)!=null?me:g==="barge-in"?(Le=l.recordingBorderColor)!=null?Le:"":(Re=Ve==null?void 0:Ve.borderColor)!=null?Re:"";kr(),_.classList.add("persona-voice-speaking"),_.style.backgroundColor=H,_.style.borderColor=B;let z=I||"currentColor";_.style.color=z,Vr(T,z);let O=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";_.setAttribute("aria-label",O),g==="none"&&(_.style.cursor="default"),g==="barge-in"&&_.classList.add("persona-voice-recording")},Be=()=>{var l,g,b;_&&(kr(),Ve&&(_.style.backgroundColor=(l=Ve.backgroundColor)!=null?l:"",_.style.color=(g=Ve.color)!=null?g:"",_.style.borderColor=(b=Ve.borderColor)!=null?b:"",Vr(Ve.iconName,Ve.color||"currentColor"),Ve=null),_.style.cursor="",_.setAttribute("aria-label","Start voice recognition"))},Ge=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let b=D.getVoiceStatus(),T=D.getVoiceInterruptionMode();if(T==="none"&&(b==="processing"||b==="speaking"))return;if(T==="cancel"&&(b==="processing"||b==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,mn(),Rn("user"),Be()});return}D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Qe.manuallyDeactivated=!D.isVoiceActive(),mn(),Rn("user"),D.isVoiceActive()?hr():Be()});return}if(Mn){let b=Z.value.trim();Qe.manuallyDeactivated=!0,mn(),jn("user"),b&&(Z.value="",Z.style.height="auto",D.sendMessage(b))}else Qe.manuallyDeactivated=!1,mn(),Mr("user")};zt=Ge,_&&(_.addEventListener("click",Ge),At.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),Be()):jn("system"),_&&_.removeEventListener("click",Ge)}));let Rt=o.on("assistant:complete",()=>{co&&(Qe.active||Qe.manuallyDeactivated||co==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!Qe.active&&!Qe.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Rn("auto"),D.isVoiceActive()&&hr()}):Mr("auto"))},600))});At.push(Rt);let bt=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});At.push(bt);let it=()=>{Wt(!E,"user")},ke=null,y=null;if(x){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>Ho(n,it).element,onToggle:it});g&&(y=g)}y||(ke=Ho(n,it))}ke?e.appendChild(ke.element):y&&e.appendChild(y),Tr(),On.render(n.suggestionChips,D,Z,void 0,n.suggestionChipsConfig),go(),zr(D.isStreaming()),fr(!0),$o(),k&&(x?E&&setTimeout(()=>qr(),200):setTimeout(()=>qr(),0));let ve=()=>{var O,ue,Ce,Ae,ye,Me,qe,ut,Ke,$,Le,Re,me,He,wt,vt,Ut,on,Se,fn,sn,zn;let l=Zt(n),g=(ue=(O=n.launcher)==null?void 0:O.sidebarMode)!=null?ue:!1,b=l||g||((Ae=(Ce=n.launcher)==null?void 0:Ce.fullHeight)!=null?Ae:!1),T=(ye=e.ownerDocument.defaultView)!=null?ye:window,I=(qe=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?qe:!0,H=(Ke=(ut=n.launcher)==null?void 0:ut.mobileBreakpoint)!=null?Ke:640,B=T.innerWidth<=H,z=I&&B&&x;try{if(z){Xn(),Dr(e,n);return}if(W&&(W=!1,Xn(),Dr(e,n)),!x&&!l){F.style.height="",F.style.width="";return}if(!g&&!l){let nt=(Le=($=n==null?void 0:n.launcher)==null?void 0:$.width)!=null?Le:n==null?void 0:n.launcherWidth,gt=nt!=null?nt:Bn;F.style.width=gt,F.style.maxWidth=gt}if(Gn(),!b){let nt=T.innerHeight,gt=64,hn=(me=(Re=n.launcher)==null?void 0:Re.heightOffset)!=null?me:0,sr=Math.max(200,nt-gt),Je=Math.min(640,sr),Et=Math.max(200,Je-hn);F.style.height=`${Et}px`}}finally{if(Ze(),Tr(),E&&x){let gt=((He=e.ownerDocument.defaultView)!=null?He:window).innerWidth<=((vt=(wt=n.launcher)==null?void 0:wt.mobileBreakpoint)!=null?vt:640),hn=(on=(Ut=n.launcher)==null?void 0:Ut.sidebarMode)!=null?on:!1,sr=(fn=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?fn:!0,Je=Zt(n)&&sr&&gt,Et=hn||sr&&gt&&x||Je;if(Et&&!Ot){let Lr=e.getRootNode(),Ir=Lr instanceof ShadowRoot?Lr.host:e.closest(".persona-host");Ir&&!Ft&&(Ft=qs(Ir,(zn=(sn=n.launcher)==null?void 0:sn.zIndex)!=null?zn:xn)),Ot=Us(e.ownerDocument)}else Et||(Ft==null||Ft(),Ft=null,Ot==null||Ot(),Ot=null)}}};ve();let P=(Ua=e.ownerDocument.defaultView)!=null?Ua:window;if(P.addEventListener("resize",ve),At.push(()=>P.removeEventListener("resize",ve)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ze()});l.observe(ot),At.push(()=>l.disconnect())}Tn=U.scrollTop;let S=()=>{let l=U.scrollTop,{action:g,nextLastScrollTop:b}=ds({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:Tn,nearBottom:Wo(U,lo),userScrollThreshold:Or,isAutoScrolling:_n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Tn=b,g==="resume"){mr();return}g==="pause"&&uo()};U.addEventListener("scroll",S,{passive:!0}),At.push(()=>U.removeEventListener("scroll",S));let Y=l=>{let g=ps({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:Wo(U,lo),resumeWhenNearBottom:!0});g==="pause"?uo():g==="resume"&&mr()};U.addEventListener("wheel",Y,{passive:!0}),At.push(()=>U.removeEventListener("wheel",Y)),dt.addEventListener("click",()=>{U.scrollTop=U.scrollHeight,Tn=U.scrollTop,mr(),fr(!0)}),At.push(()=>dt.remove()),At.push(()=>{jr()});let N=()=>{le&&(En&&(le.removeEventListener("click",En),En=null),x?(le.style.display="",En=()=>{Wt(!1,"user")},le.addEventListener("click",En)):le.style.display="none")};N(),(()=>{let{clearChatButton:l}=ie;l&&l.addEventListener("click",()=>{D.clearMessages(),Wn.clear(),mr();try{localStorage.removeItem(ao),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ao}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ao)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),a!=null&&a.clear)try{let b=a.clear();b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}i={},A.syncFromMetadata(),se==null||se.clear(),be==null||be.update()})})(),ct&&ct.addEventListener("submit",mo),Z==null||Z.addEventListener("keydown",fo),Z==null||Z.addEventListener("paste",ho),At.push(()=>{ct&&ct.removeEventListener("submit",mo),Z==null||Z.removeEventListener("keydown",fo),Z==null||Z.removeEventListener("paste",ho)}),At.push(()=>{D.cancel()}),ke?At.push(()=>{ke==null||ke.destroy()}):y&&At.push(()=>{y==null||y.remove()});let xe={update(l){var 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,Ni,Fi,Oi,$i,_i,ji,zi,qi,Ui,Vi,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,Nl,Fl,Ol,$l,_l,jl,zl,ql,Ul,Vl,Jl,Yl,Gl,Xl,Kl;let g=n.toolCall,b=n.messageActions,T=(Za=n.layout)==null?void 0:Za.messages,I=n.colorScheme,H=n.loadingIndicator,B=n.iterationDisplay,z=(Qa=n.features)==null?void 0:Qa.showReasoning,O=(ei=n.features)==null?void 0:ei.showToolCalls,ue=(ti=n.features)==null?void 0:ti.toolCallDisplay,Ce=(ni=n.features)==null?void 0:ni.reasoningDisplay;n={...n,...l},Xn(),Dr(e,n),fs(e,n),hs(e,n),Sn(),n.colorScheme!==I&&ur();let Ae=ys.getForInstance(n.plugins);s.length=0,s.push(...Ae),x=(oi=(ri=n.launcher)==null?void 0:ri.enabled)!=null?oi:!0,C=(ai=(si=n.launcher)==null?void 0:si.autoExpand)!=null?ai:!1,Q=(li=(ii=n.features)==null?void 0:ii.showReasoning)!=null?li:!0,we=(di=(ci=n.features)==null?void 0:ci.showToolCalls)!=null?di:!0,Ee=(ui=(pi=n.features)==null?void 0:pi.scrollToBottom)!=null?ui:{},yt(),rr();let ye=ne;if(ne=(mi=(gi=n.features)==null?void 0:gi.showEventStreamToggle)!=null?mi:!1,ne&&!ye){if(se||(Ie=new Oo(fe),se=new Fo(Pe,Ie),Ie.open().then(()=>se==null?void 0:se.restore()).catch(()=>{}),D.setSSEEventCallback((V,pt)=>{se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:V,timestamp:Date.now(),payload:JSON.stringify(pt)})})),!et&&rt){let V=(hi=(fi=n.features)==null?void 0:fi.eventStream)==null?void 0:hi.classNames,pt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(V!=null&&V.toggleButton?" "+V.toggleButton:"");et=h("button",pt),et.style.width="28px",et.style.height="28px",et.style.color=vn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let Ht=ge("activity","18px","currentColor",1.5);Ht&&et.appendChild(Ht);let Ye=ie.clearChatButtonWrapper,mt=ie.closeButtonWrapper,Vt=Ye||mt;Vt&&Vt.parentNode===rt?rt.insertBefore(et,Vt):rt.appendChild(et),et.addEventListener("click",()=>{ze?Nn():Qn()})}}else!ne&&ye&&(Nn(),et&&(et.remove(),et=null),se==null||se.clear(),Ie==null||Ie.destroy(),se=null,Ie=null);if(((yi=n.launcher)==null?void 0:yi.enabled)===!1&&ke&&(ke.destroy(),ke=null),((bi=n.launcher)==null?void 0:bi.enabled)===!1&&y&&(y.remove(),y=null),((xi=n.launcher)==null?void 0:xi.enabled)!==!1&&!ke&&!y){let V=s.find(pt=>pt.renderLauncher);if(V!=null&&V.renderLauncher){let pt=V.renderLauncher({config:n,defaultRenderer:()=>Ho(n,it).element,onToggle:it});pt&&(y=pt,e.appendChild(y))}y||(ke=Ho(n,it),e.appendChild(ke.element))}ke&&ke.update(n),It&&((vi=n.launcher)==null?void 0:vi.title)!==void 0&&(It.textContent=n.launcher.title),Pt&&((Ci=n.launcher)==null?void 0:Ci.subtitle)!==void 0&&(Pt.textContent=n.launcher.subtitle);let Me=(wi=n.layout)==null?void 0:wi.header;if((Me==null?void 0:Me.layout)!==M&&rt){let V=Me?Bo(n,Me,{showClose:x,onClose:()=>Wt(!1,"user")}):vr({config:n,showClose:x,onClose:()=>Wt(!1,"user")});rt.replaceWith(V.header),rt=V.header,De=V.iconHolder,It=V.headerTitle,Pt=V.headerSubtitle,le=V.closeButton,M=Me==null?void 0:Me.layout}else if(Me&&(De&&(De.style.display=Me.showIcon===!1?"none":""),It&&(It.style.display=Me.showTitle===!1?"none":""),Pt&&(Pt.style.display=Me.showSubtitle===!1?"none":""),le&&(le.style.display=Me.showCloseButton===!1?"none":""),ie.clearChatButtonWrapper)){let V=Me.showClearChat;if(V!==void 0){ie.clearChatButtonWrapper.style.display=V?"":"none";let{closeButtonWrapper:pt}=ie;pt&&!pt.classList.contains("persona-absolute")&&(V?pt.classList.remove("persona-ml-auto"):pt.classList.add("persona-ml-auto"))}}let ut=((Si=n.layout)==null?void 0:Si.showHeader)!==!1;rt&&(rt.style.display=ut?"":"none");let Ke=((Ai=n.layout)==null?void 0:Ai.showFooter)!==!1;ot&&(ot.style.display=Ke?"":"none"),Ze(),rr(),x!==w?x?Wt(C,"auto"):(E=!0,Tr()):C!==R&&Wt(C,"auto"),R=C,w=x,ve(),N();let Re=JSON.stringify(l.toolCall)!==JSON.stringify(g),me=JSON.stringify(n.messageActions)!==JSON.stringify(b),He=JSON.stringify((Ei=n.layout)==null?void 0:Ei.messages)!==JSON.stringify(T),wt=((Ti=n.loadingIndicator)==null?void 0:Ti.render)!==(H==null?void 0:H.render)||((Mi=n.loadingIndicator)==null?void 0:Mi.renderIdle)!==(H==null?void 0:H.renderIdle)||((ki=n.loadingIndicator)==null?void 0:ki.showBubble)!==(H==null?void 0:H.showBubble),vt=n.iterationDisplay!==B,Ut=((Ii=(Li=n.features)==null?void 0:Li.showReasoning)!=null?Ii:!0)!==(z!=null?z:!0)||((Wi=(Pi=n.features)==null?void 0:Pi.showToolCalls)!=null?Wi:!0)!==(O!=null?O:!0)||JSON.stringify((Ri=n.features)==null?void 0:Ri.toolCallDisplay)!==JSON.stringify(ue)||JSON.stringify((Hi=n.features)==null?void 0:Hi.reasoningDisplay)!==JSON.stringify(Ce);(Re||me||He||wt||vt||Ut)&&D&&(gr++,Er(re,D.getMessages(),L));let Se=(Bi=n.launcher)!=null?Bi:{},fn=(Di=Se.headerIconHidden)!=null?Di:!1,sn=(Fi=(Ni=n.layout)==null?void 0:Ni.header)==null?void 0:Fi.showIcon,zn=fn||sn===!1,nt=Se.headerIconName,gt=(Oi=Se.headerIconSize)!=null?Oi:"48px";if(De){let V=j.querySelector(".persona-border-b-persona-divider"),pt=V==null?void 0:V.querySelector(".persona-flex-col");if(zn)De.style.display="none",V&&pt&&!V.contains(pt)&&V.insertBefore(pt,V.firstChild);else{if(De.style.display="",De.style.height=gt,De.style.width=gt,V&&pt&&(V.contains(De)?De.nextSibling!==pt&&(De.remove(),V.insertBefore(De,pt)):V.insertBefore(De,pt)),nt){let Ye=parseFloat(gt)||24,mt=ge(nt,Ye*.6,"#ffffff",2);mt?De.replaceChildren(mt):De.textContent=($i=Se.agentIconText)!=null?$i:"\u{1F4AC}"}else if(Se.iconUrl){let Ye=De.querySelector("img");if(Ye)Ye.src=Se.iconUrl,Ye.style.height=gt,Ye.style.width=gt;else{let mt=document.createElement("img");mt.src=Se.iconUrl,mt.alt="",mt.className="persona-rounded-xl persona-object-cover",mt.style.height=gt,mt.style.width=gt,De.replaceChildren(mt)}}else{let Ye=De.querySelector("svg"),mt=De.querySelector("img");(Ye||mt)&&De.replaceChildren(),De.textContent=(_i=Se.agentIconText)!=null?_i:"\u{1F4AC}"}let Ht=De.querySelector("img");Ht&&(Ht.style.height=gt,Ht.style.width=gt)}}let hn=(zi=(ji=n.layout)==null?void 0:ji.header)==null?void 0:zi.showTitle,sr=(Ui=(qi=n.layout)==null?void 0:qi.header)==null?void 0:Ui.showSubtitle;if(It&&(It.style.display=hn===!1?"none":""),Pt&&(Pt.style.display=sr===!1?"none":""),le){((Ji=(Vi=n.layout)==null?void 0:Vi.header)==null?void 0:Ji.showCloseButton)===!1?le.style.display="none":le.style.display="";let pt=(Yi=Se.closeButtonSize)!=null?Yi:"32px",Ht=(Gi=Se.closeButtonPlacement)!=null?Gi:"inline";le.style.height=pt,le.style.width=pt;let{closeButtonWrapper:Ye}=ie,mt=Ht==="top-right",Vt=Ye==null?void 0:Ye.classList.contains("persona-absolute");if(Ye&&mt!==Vt)if(Ye.remove(),mt)Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(Ye);else{let tt=(Ki=(Xi=Se.clearChat)==null?void 0:Xi.placement)!=null?Ki:"inline",Kt=(Qi=(Zi=Se.clearChat)==null?void 0:Zi.enabled)!=null?Qi:!0;Ye.className=Kt&&tt==="inline"?"":"persona-ml-auto";let bn=j.querySelector(".persona-border-b-persona-divider");bn&&bn.appendChild(Ye)}if(le.style.color=Se.closeButtonColor||vn.actionIconColor,Se.closeButtonBackgroundColor?(le.style.backgroundColor=Se.closeButtonBackgroundColor,le.classList.remove("hover:persona-bg-gray-100")):(le.style.backgroundColor="",le.classList.add("hover:persona-bg-gray-100")),Se.closeButtonBorderWidth||Se.closeButtonBorderColor){let tt=Se.closeButtonBorderWidth||"0px",Kt=Se.closeButtonBorderColor||"transparent";le.style.border=`${tt} solid ${Kt}`,le.classList.remove("persona-border-none")}else le.style.border="",le.classList.add("persona-border-none");Se.closeButtonBorderRadius?(le.style.borderRadius=Se.closeButtonBorderRadius,le.classList.remove("persona-rounded-full")):(le.style.borderRadius="",le.classList.add("persona-rounded-full")),Se.closeButtonPaddingX?(le.style.paddingLeft=Se.closeButtonPaddingX,le.style.paddingRight=Se.closeButtonPaddingX):(le.style.paddingLeft="",le.style.paddingRight=""),Se.closeButtonPaddingY?(le.style.paddingTop=Se.closeButtonPaddingY,le.style.paddingBottom=Se.closeButtonPaddingY):(le.style.paddingTop="",le.style.paddingBottom="");let an=(el=Se.closeButtonIconName)!=null?el:"x",qn=(tl=Se.closeButtonIconText)!=null?tl:"\xD7";le.innerHTML="";let un=ge(an,"20px","currentColor",2);un?le.appendChild(un):le.textContent=qn;let $t=(nl=Se.closeButtonTooltipText)!=null?nl:"Close chat",Ln=(rl=Se.closeButtonShowTooltip)!=null?rl:!0;if(le.setAttribute("aria-label",$t),Ye&&(Ye._cleanupTooltip&&(Ye._cleanupTooltip(),delete Ye._cleanupTooltip),Ln&&$t)){let tt=null,Kt=()=>{if(tt||!le)return;let Wr=le.ownerDocument,Co=Wr.body;if(!Co)return;tt=Kn(Wr,"div","persona-clear-chat-tooltip"),tt.textContent=$t;let wo=Kn(Wr,"div");wo.className="persona-clear-chat-tooltip-arrow",tt.appendChild(wo);let Rr=le.getBoundingClientRect();tt.style.position="fixed",tt.style.zIndex=String(br),tt.style.left=`${Rr.left+Rr.width/2}px`,tt.style.top=`${Rr.top-8}px`,tt.style.transform="translate(-50%, -100%)",Co.appendChild(tt)},bn=()=>{tt&&tt.parentNode&&(tt.parentNode.removeChild(tt),tt=null)};Ye.addEventListener("mouseenter",Kt),Ye.addEventListener("mouseleave",bn),le.addEventListener("focus",Kt),le.addEventListener("blur",bn),Ye._cleanupTooltip=()=>{bn(),Ye&&(Ye.removeEventListener("mouseenter",Kt),Ye.removeEventListener("mouseleave",bn)),le&&(le.removeEventListener("focus",Kt),le.removeEventListener("blur",bn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Et}=ie;if(Je){let V=(ol=Se.clearChat)!=null?ol:{},pt=(sl=V.enabled)!=null?sl:!0,Ht=(il=(al=n.layout)==null?void 0:al.header)==null?void 0:il.showClearChat,Ye=Ht!==void 0?Ht:pt,mt=(ll=V.placement)!=null?ll:"inline";if(Et){Et.style.display=Ye?"":"none";let{closeButtonWrapper:Vt}=ie;Vt&&!Vt.classList.contains("persona-absolute")&&(Ye?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let an=mt==="top-right",qn=Et.classList.contains("persona-absolute");if(an!==qn&&Ye){if(Et.remove(),an)Et.className="persona-absolute persona-top-4 persona-z-50",Et.style.right="48px",j.style.position="relative",j.appendChild(Et);else{Et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Et.style.right="";let $t=j.querySelector(".persona-border-b-persona-divider"),Ln=ie.closeButtonWrapper;$t&&Ln&&Ln.parentElement===$t?$t.insertBefore(Et,Ln):$t&&$t.appendChild(Et)}let un=ie.closeButtonWrapper;un&&!un.classList.contains("persona-absolute")&&(an?un.classList.add("persona-ml-auto"):un.classList.remove("persona-ml-auto"))}}if(Ye){let Vt=(cl=V.size)!=null?cl:"32px";Je.style.height=Vt,Je.style.width=Vt;let an=(dl=V.iconName)!=null?dl:"refresh-cw",qn=(pl=V.iconColor)!=null?pl:"";Je.style.color=qn||vn.actionIconColor,Je.innerHTML="";let un=ge(an,"20px","currentColor",2);if(un&&Je.appendChild(un),V.backgroundColor?(Je.style.backgroundColor=V.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),V.borderWidth||V.borderColor){let tt=V.borderWidth||"0px",Kt=V.borderColor||"transparent";Je.style.border=`${tt} solid ${Kt}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");V.borderRadius?(Je.style.borderRadius=V.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),V.paddingX?(Je.style.paddingLeft=V.paddingX,Je.style.paddingRight=V.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),V.paddingY?(Je.style.paddingTop=V.paddingY,Je.style.paddingBottom=V.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let $t=(ul=V.tooltipText)!=null?ul:"Clear chat",Ln=(gl=V.showTooltip)!=null?gl:!0;if(Je.setAttribute("aria-label",$t),Et&&(Et._cleanupTooltip&&(Et._cleanupTooltip(),delete Et._cleanupTooltip),Ln&&$t)){let tt=null,Kt=()=>{if(tt||!Je)return;let Wr=Je.ownerDocument,Co=Wr.body;if(!Co)return;tt=Kn(Wr,"div","persona-clear-chat-tooltip"),tt.textContent=$t;let wo=Kn(Wr,"div");wo.className="persona-clear-chat-tooltip-arrow",tt.appendChild(wo);let Rr=Je.getBoundingClientRect();tt.style.position="fixed",tt.style.zIndex=String(br),tt.style.left=`${Rr.left+Rr.width/2}px`,tt.style.top=`${Rr.top-8}px`,tt.style.transform="translate(-50%, -100%)",Co.appendChild(tt)},bn=()=>{tt&&tt.parentNode&&(tt.parentNode.removeChild(tt),tt=null)};Et.addEventListener("mouseenter",Kt),Et.addEventListener("mouseleave",bn),Je.addEventListener("focus",Kt),Je.addEventListener("blur",bn),Et._cleanupTooltip=()=>{bn(),Et&&(Et.removeEventListener("mouseenter",Kt),Et.removeEventListener("mouseleave",bn)),Je&&(Je.removeEventListener("focus",Kt),Je.removeEventListener("blur",bn))}}}}let Lr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[bs],Ir=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[so.message,so.messageAndClick];A=xs({parsers:Lr,handlers:Ir,getSessionMetadata:p,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),L=Zc(n,A,J),D.updateConfig(n),Er(re,D.getMessages(),L),On.render(n.suggestionChips,D,Z,void 0,n.suggestionChipsConfig),go(),zr(D.isStreaming());let Jo=((ml=n.voiceRecognition)==null?void 0:ml.enabled)===!0,Yo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Go=((hl=(fl=n.voiceRecognition)==null?void 0:fl.provider)==null?void 0:hl.type)==="runtype";if(Jo&&(Yo||Go))if(!_||!We){let V=Uo(n.voiceRecognition,n.sendButton);V&&(_=V.micButton,We=V.micButtonWrapper,tn.insertBefore(We,kt),_.addEventListener("click",Ge),_.disabled=D.isStreaming())}else{let V=(yl=n.voiceRecognition)!=null?yl:{},pt=(bl=n.sendButton)!=null?bl:{},Ht=(xl=V.iconName)!=null?xl:"mic",Ye=(vl=pt.size)!=null?vl:"40px",mt=(Cl=V.iconSize)!=null?Cl:Ye,Vt=parseFloat(mt)||24;_.style.width=mt,_.style.height=mt,_.style.minWidth=mt,_.style.minHeight=mt;let an=(Sl=(wl=V.iconColor)!=null?wl:pt.textColor)!=null?Sl:"currentColor";_.innerHTML="";let qn=ge(Ht,Vt,an,2);qn?_.appendChild(qn):_.textContent="\u{1F3A4}";let un=(Al=V.backgroundColor)!=null?Al:pt.backgroundColor;un?_.style.backgroundColor=un:_.style.backgroundColor="",an?_.style.color=an:_.style.color="var(--persona-text, #111827)",V.borderWidth?(_.style.borderWidth=V.borderWidth,_.style.borderStyle="solid"):(_.style.borderWidth="",_.style.borderStyle=""),V.borderColor?_.style.borderColor=V.borderColor:_.style.borderColor="",V.paddingX?(_.style.paddingLeft=V.paddingX,_.style.paddingRight=V.paddingX):(_.style.paddingLeft="",_.style.paddingRight=""),V.paddingY?(_.style.paddingTop=V.paddingY,_.style.paddingBottom=V.paddingY):(_.style.paddingTop="",_.style.paddingBottom="");let $t=We==null?void 0:We.querySelector(".persona-send-button-tooltip"),Ln=(El=V.tooltipText)!=null?El:"Start voice recognition";if(((Tl=V.showTooltip)!=null?Tl:!1)&&Ln)if($t)$t.textContent=Ln,$t.style.display="";else{let Kt=document.createElement("div");Kt.className="persona-send-button-tooltip",Kt.textContent=Ln,We==null||We.insertBefore(Kt,_)}else $t&&($t.style.display="none");We.style.display="",_.disabled=D.isStreaming()}else _&&We&&(We.style.display="none",((kl=(Ml=n.voiceRecognition)==null?void 0:Ml.provider)==null?void 0:kl.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():Mn&&jn());if(((Ll=n.attachments)==null?void 0:Ll.enabled)===!0)if(!ft||!de){let V=(Il=n.attachments)!=null?Il:{},Ht=(Wl=((Pl=n.sendButton)!=null?Pl:{}).size)!=null?Wl:"40px";te||(te=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),te.style.display="none",ct.insertBefore(te,Z)),$e||($e=document.createElement("input"),$e.type="file",$e.accept=((Rl=V.allowedTypes)!=null?Rl:ar).join(","),$e.multiple=((Hl=V.maxFiles)!=null?Hl:4)>1,$e.style.display="none",$e.setAttribute("aria-label","Attach files"),ct.insertBefore($e,Z)),ft=h("div","persona-send-button-wrapper"),de=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),de.type="button",de.setAttribute("aria-label",(Bl=V.buttonTooltipText)!=null?Bl:"Attach file");let Ye=(Dl=V.buttonIconName)!=null?Dl:"paperclip",mt=Ht,Vt=parseFloat(mt)||40,an=Math.round(Vt*.6);de.style.width=mt,de.style.height=mt,de.style.minWidth=mt,de.style.minHeight=mt,de.style.fontSize="18px",de.style.lineHeight="1",de.style.backgroundColor="transparent",de.style.color="var(--persona-primary, #111827)",de.style.border="none",de.style.borderRadius="6px",de.style.transition="background-color 0.15s ease",de.addEventListener("mouseenter",()=>{de.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),de.addEventListener("mouseleave",()=>{de.style.backgroundColor="transparent"});let qn=ge(Ye,an,"currentColor",1.5);qn?de.appendChild(qn):de.textContent="\u{1F4CE}",de.addEventListener("click",Ln=>{Ln.preventDefault(),$e==null||$e.click()}),ft.appendChild(de);let un=(Nl=V.buttonTooltipText)!=null?Nl:"Attach file",$t=h("div","persona-send-button-tooltip");$t.textContent=un,ft.appendChild($t),Qt.append(ft),!Ue&&$e&&te&&(Ue=Qr.fromConfig(V),Ue.setPreviewsContainer(te),$e.addEventListener("change",async()=>{Ue&&($e!=null&&$e.files)&&(await Ue.handleFileSelect($e.files),$e.value="")}))}else{ft.style.display="";let V=(Fl=n.attachments)!=null?Fl:{};$e&&($e.accept=((Ol=V.allowedTypes)!=null?Ol:ar).join(","),$e.multiple=(($l=V.maxFiles)!=null?$l:4)>1),Ue&&Ue.updateConfig({allowedTypes:V.allowedTypes,maxFileSize:V.maxFileSize,maxFiles:V.maxFiles})}else ft&&(ft.style.display="none"),Ue&&Ue.clearAttachments();let qt=(_l=n.sendButton)!=null?_l:{},Xo=(jl=qt.useIcon)!=null?jl:!1,bo=(zl=qt.iconText)!=null?zl:"\u2191",yn=qt.iconName,Hn=(ql=qt.tooltipText)!=null?ql:"Send message",Jr=(Ul=qt.showTooltip)!=null?Ul:!1,xo=(Vl=qt.size)!=null?Vl:"40px",Ko=qt.backgroundColor,Pr=qt.textColor;if(Xo){if(ee.style.width=xo,ee.style.height=xo,ee.style.minWidth=xo,ee.style.minHeight=xo,ee.style.fontSize="18px",ee.style.lineHeight="1",ee.innerHTML="",Pr?ee.style.color=Pr:ee.style.color="var(--persona-button-primary-fg, #ffffff)",yn){let V=parseFloat(xo)||24,pt=(Pr==null?void 0:Pr.trim())||"currentColor",Ht=ge(yn,V,pt,2);Ht?ee.appendChild(Ht):ee.textContent=bo}else ee.textContent=bo;ee.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ko?(ee.style.backgroundColor=Ko,ee.classList.remove("persona-bg-persona-primary")):(ee.style.backgroundColor="",ee.classList.add("persona-bg-persona-primary"))}else ee.textContent=(Yl=(Jl=n.copy)==null?void 0:Jl.sendButtonLabel)!=null?Yl:"Send",ee.style.width="",ee.style.height="",ee.style.minWidth="",ee.style.minHeight="",ee.style.fontSize="",ee.style.lineHeight="",ee.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Ko?(ee.style.backgroundColor=Ko,ee.classList.remove("persona-bg-persona-accent")):ee.classList.add("persona-bg-persona-accent"),Pr?ee.style.color=Pr:ee.classList.add("persona-text-white");qt.borderWidth?(ee.style.borderWidth=qt.borderWidth,ee.style.borderStyle="solid"):(ee.style.borderWidth="",ee.style.borderStyle=""),qt.borderColor?ee.style.borderColor=qt.borderColor:ee.style.borderColor="",qt.paddingX?(ee.style.paddingLeft=qt.paddingX,ee.style.paddingRight=qt.paddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),qt.paddingY?(ee.style.paddingTop=qt.paddingY,ee.style.paddingBottom=qt.paddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let vo=kt==null?void 0:kt.querySelector(".persona-send-button-tooltip");if(Jr&&Hn)if(vo)vo.textContent=Hn,vo.style.display="";else{let V=document.createElement("div");V.className="persona-send-button-tooltip",V.textContent=Hn,kt==null||kt.insertBefore(V,ee)}else vo&&(vo.style.display="none");let Zo=(Gl=n.layout)==null?void 0:Gl.contentMaxWidth;Zo?(re.style.maxWidth=Zo,re.style.marginLeft="auto",re.style.marginRight="auto",re.style.width="100%",ct&&(ct.style.maxWidth=Zo,ct.style.marginLeft="auto",ct.style.marginRight="auto"),_e&&(_e.style.maxWidth=Zo,_e.style.marginLeft="auto",_e.style.marginRight="auto")):(re.style.maxWidth="",re.style.marginLeft="",re.style.marginRight="",re.style.width="",ct&&(ct.style.maxWidth="",ct.style.marginLeft="",ct.style.marginRight=""),_e&&(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight=""));let yr=(Xl=n.statusIndicator)!=null?Xl:{},Rd=(Kl=yr.visible)!=null?Kl:!0;if(Dt.style.display=Rd?"":"none",D){let V=D.getStatus();Tt(Dt,(Ht=>{var Ye,mt,Vt,an;return Ht==="idle"?(Ye=yr.idleText)!=null?Ye:ln.idle:Ht==="connecting"?(mt=yr.connectingText)!=null?mt:ln.connecting:Ht==="connected"?(Vt=yr.connectedText)!=null?Vt:ln.connected:Ht==="error"?(an=yr.errorText)!=null?an:ln.error:ln[Ht]})(V),yr,V)}Dt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Hd=yr.align==="left"?"persona-text-left":yr.align==="center"?"persona-text-center":"persona-text-right";Dt.classList.add(Hd)},open(){x&&Wt(!0,"api")},close(){x&&Wt(!1,"api")},toggle(){x&&Wt(!E,"api")},clearChat(){cn=!1,D.clearMessages(),Wn.clear(),mr();try{localStorage.removeItem(ao),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ao}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ao)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(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}i={},A.syncFromMetadata(),se==null||se.clear(),be==null||be.update()},setMessage(l){return!Z||D.isStreaming()?!1:(!E&&x&&Wt(!0,"system"),Z.value=l,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let g=(l==null?void 0:l.trim())||Z.value.trim();return g?(!E&&x&&Wt(!0,"system"),Z.value="",Z.style.height="auto",D.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return D.isStreaming()?!1:((b=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(D.isVoiceActive()||(!E&&x&&Wt(!0,"system"),Qe.manuallyDeactivated=!1,mn(),D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Rn("user"),D.isVoiceActive()&&hr()})),!0):Mn?!0:yo()?(!E&&x&&Wt(!0,"system"),Qe.manuallyDeactivated=!1,mn(),Mr("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(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,mn(),Rn("user"),Be()}),!0):!1:Mn?(Qe.manuallyDeactivated=!0,mn(),jn("user"),!0):!1},injectMessage(l){return!E&&x&&Wt(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!E&&x&&Wt(!0,"system");let g=D.injectAssistantMessage(l);return G&&(G=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),g},injectUserMessage(l){return!E&&x&&Wt(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!E&&x&&Wt(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!E&&x&&Wt(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!E&&x&&Wt(!0,"system"),D.injectTestEvent(l)},async connectStream(l,g){return D.connectStream(l,g)},__pushEventStreamEvent(l){se&&se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ne||!se||Qn()},hideEventStream(){ze&&Nn()},isEventStreamVisible(){return ze},showArtifacts(){Dn(n)&&(cn=!1,Sn(),st==null||st.setMobileOpen(!0))},hideArtifacts(){Dn(n)&&(cn=!0,Sn())},upsertArtifact(l){return Dn(n)?(cn=!1,D.upsertArtifact(l)):null},selectArtifact(l){Dn(n)&&D.selectArtifact(l)},clearArtifacts(){Dn(n)&&D.clearArtifacts()},focusInput(){return x&&!E||!Z?!1:(Z.focus(),!0)},async resolveApproval(l,g){let T=D.getMessages().find(I=>{var H;return I.variant==="approval"&&((H=I.approval)==null?void 0:H.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(T.approval,g)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){m(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return x&&E},isVoiceActive(){return Qe.active},getState(){return{open:x&&E,launcherEnabled:x,voiceActive:Qe.active,streaming:D.isStreaming()}},showCSATFeedback(l){!E&&x&&Wt(!0,"system");let g=re.querySelector(".persona-feedback-container");g&&g.remove();let b=ia({onSubmit:async(T,I)=>{var H;D.isClientTokenMode()&&await D.submitCSATFeedback(T,I),(H=l==null?void 0:l.onSubmit)==null||H.call(l,T,I)},onDismiss:l==null?void 0:l.onDismiss,...l});re.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&x&&Wt(!0,"system");let g=re.querySelector(".persona-feedback-container");g&&g.remove();let b=la({onSubmit:async(T,I)=>{var H;D.isClientTokenMode()&&await D.submitNPSFeedback(T,I),(H=l==null?void 0:l.onSubmit)==null||H.call(l,T,I)},onDismiss:l==null?void 0:l.onDismiss,...l});re.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return D.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return D.submitNPSFeedback(l,g)},destroy(){At.forEach(l=>l()),q.remove(),ke==null||ke.destroy(),y==null||y.remove(),En&&le.removeEventListener("click",En)}};if((((Va=t==null?void 0:t.debugTools)!=null?Va:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:xe,getMessages:xe.getMessages,getStatus:xe.getStatus,getMetadata:xe.getPersistentMetadata,updateMetadata:xe.updatePersistentMetadata,clearHistory:()=>xe.clearChat(),setVoiceActive:b=>b?xe.startVoiceRecognition():xe.stopVoiceRecognition()};window.AgentWidgetBrowser=g,At.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=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&xe.focusInput()};if(window.addEventListener("persona:focusInput",g),At.push(()=>{window.removeEventListener("persona:focusInput",g)}),ne){let z=ue=>{let Ce=ue.detail;(!(Ce!=null&&Ce.instanceId)||Ce.instanceId===l)&&xe.showEventStream()},O=ue=>{let Ce=ue.detail;(!(Ce!=null&&Ce.instanceId)||Ce.instanceId===l)&&xe.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),At.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let b=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&xe.showArtifacts()},T=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&xe.hideArtifacts()},I=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==l||O!=null&&O.artifact&&xe.upsertArtifact(O.artifact)},H=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==l||typeof(O==null?void 0:O.id)=="string"&&xe.selectArtifact(O.id)},B=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&xe.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",T),window.addEventListener("persona:upsertArtifact",I),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",B),At.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",T),window.removeEventListener("persona:upsertArtifact",I),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",B)})}let xt=pu(n.persistState);if(xt&&x){let l=uu(xt.storage),g=`${xt.keyPrefix}widget-open`,b=`${xt.keyPrefix}widget-voice`,T=`${xt.keyPrefix}widget-voice-mode`;if(l){let I=((Ja=xt.persist)==null?void 0:Ja.openState)&&l.getItem(g)==="true",H=((Ya=xt.persist)==null?void 0:Ya.voiceState)&&l.getItem(b)==="true",B=((Ga=xt.persist)==null?void 0:Ga.voiceState)&&l.getItem(T)==="true";if(I&&setTimeout(()=>{xe.open(),setTimeout(()=>{var z;if(H||B)xe.startVoiceRecognition();else if((z=xt.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Xa=xt.persist)!=null&&Xa.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(Ka=xt.persist)!=null&&Ka.voiceState&&(o.on("voice:state",z=>{l.setItem(b,z.active?"true":"false")}),o.on("user:message",z=>{l.setItem(T,z.viaVoice?"true":"false")})),xt.clearOnChatClear){let z=()=>{l.removeItem(g),l.removeItem(b),l.removeItem(T)},O=()=>z();window.addEventListener("persona:clear-chat",O),At.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return c&&x&&setTimeout(()=>{xe.open()},0),xe};var gu=(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},Qc=(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"},ma=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=""},ed=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",ma(e)},pa=e=>{e.style.transition=""},ua=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=""},ga=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},vs=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},mu=(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))},fu=(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)},td=(e,r,t,n,s,o,a)=>{var v,A,x,C,k,R;let i=Un(o),u=i.reveal==="push";mu(e,r,t,n,u),fu(e,r,t,n,i.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,d=(A=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?A:!0,p=(C=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileBreakpoint)!=null?C:640,m=c!=null?c.innerWidth<=p:!1;if(d&&m&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ua(r),pa(n),ed(n),ga(t),vs(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=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?R:xn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),ed(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ua(r),pa(n),ga(t),vs(s,n);let w=i.animate?"transform 180ms ease":"none",M=i.side==="right"?"translateX(100%)":"translateX(-100%)",W=a?"translateX(0)":M;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=W,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",pa(n),ma(n),vs(s,n);let w=gu(i.width,e.clientWidth),M=Math.max(0,e.clientWidth),W=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${M+w}px`,r.style.transition=W,r.style.transform=E,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${M}px`,t.style.maxWidth=`${M}px`,t.style.minWidth=`${M}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="",ua(r),ma(n),ga(t),vs(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let M=a?i.width:"0px",W=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${M}`,n.style.width=M,n.style.maxWidth=M,n.style.minWidth=M,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||E?"hidden":"visible",n.style.transition=W,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")}},hu=(e,r)=>{let t=e.ownerDocument.createElement("div");return Qc(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Qc(t,n)},destroy(){t.remove()}}},yu=(e,r)=>{var k,R,w,M;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),u=t.createElement("div"),c=t.createElement("aside"),d=t.createElement("div"),p=(R=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)==null||R?(M=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?M:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),n.insertBefore(a,e),u.appendChild(e);let m=null,f=()=>{m==null||m.disconnect(),m=null},v=()=>{f(),Un(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(m=new ResizeObserver(()=>{td(a,i,u,c,d,r,p)}),m.observe(a))},A=()=>{td(a,i,u,c,d,r,p),v()},x=a.ownerDocument.defaultView,C=()=>{A()};return x==null||x.addEventListener("resize",C),Un(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),A(),{mode:"docked",host:d,shell:a,syncWidgetState(W){let E=W.launcherEnabled?W.open:!0;p!==E&&(p=E,A())},updateConfig(W){var E,G;r=W,((G=(E=r==null?void 0:r.launcher)==null?void 0:E.enabled)!=null?G:!0)===!1&&(p=!0),A()},destroy(){x==null||x.removeEventListener("resize",C),f(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Cs=(e,r)=>Zt(r)?yu(e,r):hu(e,r);var fa={},bu=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},xu=()=>{try{if(typeof fa!="undefined"&&fa.url)return new URL("../widget.css",fa.url).href}catch{}return null},nd=(e,r)=>{let t=xu(),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)}},rd=e=>{var x;let r=bu(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Cs(r,s),a,i=[],u=(C,k)=>{var W,E;let w=!((E=(W=k==null?void 0:k.launcher)==null?void 0:W.enabled)!=null?E:!0)||Zt(k),M=n.createElement("div");if(M.setAttribute("data-persona-root","true"),w&&(M.style.height="100%",M.style.display="flex",M.style.flexDirection="column",M.style.flex="1",M.style.minHeight="0"),t){let G=C.attachShadow({mode:"open"});G.appendChild(M),nd(G,n)}else C.appendChild(M),nd(C,n);return r.id&&M.setAttribute("data-persona-instance",r.id),M},c=()=>{o.syncWidgetState(a.getState())},d=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let C=u(o.host,s);a=da(C,s,{debugTools:e.debugTools}),d()},m=()=>{i.forEach(C=>C()),i=[],a.destroy()};p(),(x=e.onReady)==null||x.call(e);let f=C=>{m(),o.destroy(),o=Cs(r,C),s=C,p()},v={update(C){var M,W,E,G,K,J;let k={...s,...C,launcher:{...(M=s==null?void 0:s.launcher)!=null?M:{},...(W=C==null?void 0:C.launcher)!=null?W:{},dock:{...(G=(E=s==null?void 0:s.launcher)==null?void 0:E.dock)!=null?G:{},...(J=(K=C==null?void 0:C.launcher)==null?void 0:K.dock)!=null?J:{}}}},R=Zt(s),w=Zt(k);if(R!==w){f(k);return}s=k,o.updateConfig(s),a.update(C),c()},destroy(){m(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},A=new Proxy(v,{get(C,k,R){if(k==="host")return o.host;if(k in C)return Reflect.get(C,k,R);let w=a[k];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=A),A};var ld=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),vu=new Set(["button","a","input","select","textarea","details","summary"]),Cu=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ha=/\b(product|card|item|listing|result)\b/i,ba=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,wu=3e3,Su=100;function cd(e){let r=typeof e.className=="string"?e.className:"";if(ha.test(r)||e.id&&ha.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&ha.test(n.value))return!0}return!1}function dd(e){var r;return ba.test(((r=e.textContent)!=null?r:"").trim())}function pd(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 Au(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function od(e){let r=e.match(ba);return r?r[0]:null}function sd(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 Eu(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 Tu="commerce-card",Mu="result-card";function ad(e){return!cd(e)||!dd(e)||!pd(e)&&!Au(e)?0:5200}function id(e){var n;return!cd(e)||dd(e)||!pd(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 ud=[{id:Tu,scoreElement(e){return ad(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||ba.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,d;if(ad(e)===0)return null;let{title:t,href:n}=sd(e),s=(d=(c=od(((u=e.textContent)!=null?u:"").trim()))!=null?c:od(r.text))!=null?d:"",o=Eu(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
100
- `)}},{id:Mu,scoreElement(e){return id(e)},formatSummary(e,r){if(id(e)===0)return null;let{title:t,href:n}=sd(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
101
- `)}}];function ku(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Lu(e){var d,p,m,f,v,A,x,C,k,R,w,M,W;let r=(d=e.options)!=null?d:{},t=(m=(p=r.maxElements)!=null?p:e.maxElements)!=null?m:80,n=(v=(f=r.excludeSelector)!=null?f:e.excludeSelector)!=null?v:".persona-host",s=(x=(A=r.maxTextLength)!=null?A:e.maxTextLength)!=null?x:200,o=(k=(C=r.visibleOnly)!=null?C:e.visibleOnly)!=null?k:!0,a=(R=r.root)!=null?R:e.root,i=(w=r.mode)!=null?w:"structured",u=(M=r.maxCandidates)!=null?M:Math.max(500,t*10),c=(W=e.rules)!=null?W:ud;return i==="simple"&&e.rules&&e.rules.length>0?(ku(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:u,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function ya(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Iu=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Pu(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"||vu.has(r)||t&&Cu.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function gd(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 Wu(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let u=e.getAttribute("role");u&&(r.role=u);for(let c=0;c<e.attributes.length;c++){let d=e.attributes[c];d.name.startsWith("data-")&&(r[d.name]=d.value)}return r}function md(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${ya(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Iu){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${ya(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=>ya(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(i>=0){let u=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function Ru(e){return e==="static"?Su:wu}function fd(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:md(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:Pu(e),attributes:Wu(e)}}function Hu(e,r,t,n){let s=Ru(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 Bu(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 Du(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,d=c.tagName.toLowerCase();if(ld.has(d)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!gd(c)){i=a.nextNode();continue}let p=fd(c,e.maxTextLength),m=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(x=>x==="role");if(!m&&!f){i=a.nextNode();continue}if(n.has(p.selector)){i=a.nextNode();continue}n.add(p.selector);let{score:v,formattingRule:A}=Hu(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:v,formattingRule:A}),o+=1}i=a.nextNode()}s.sort((c,d)=>{let p=c.enriched.interactivity==="static"?1:0,m=d.enriched.interactivity==="static"?1:0;return p!==m?p-m:d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex});let u=[];for(let c of s){if(u.length>=e.maxElements)break;Bu(u,c)||u.push(c)}return u.sort((c,d)=>{let p=c.enriched.interactivity==="static"?1:0,m=d.enriched.interactivity==="static"?1:0;return p!==m?p-m:p===1&&d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex}),u.map(c=>{var m;let d;if((m=c.formattingRule)!=null&&m.formatSummary){let f=c.formattingRule.formatSummary(c.el,c.enriched,t);f&&(d=f)}let p={...c.enriched};return d&&(p.formattedSummary=d),p})}function Nu(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let u=o,c=u.tagName.toLowerCase();if(ld.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!gd(u)){o=s.nextNode();continue}let d=fd(u,e.maxTextLength),p=d.text.length>0,m=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(f=>f==="role");if(!p&&!m){o=s.nextNode();continue}n.has(d.selector)||(n.add(d.selector),t.push(d))}o=s.nextNode()}let a=[],i=[];for(let u of t)u.interactivity!=="static"?a.push(u):i.push(u);return[...a,...i].slice(0,e.maxElements)}function Fu(e={}){var n;let r=Lu(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?Nu(r,t):Du(r,t):[]}var ws=100;function Ou(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:
99
+ `}if(!A&&!l){let bn="max-height: -moz-available !important; max-height: stretch !important;",Dn=m?"":"padding-top: 1.25em !important;",Yr=m?"":`z-index: ${(vo=(Zo=n.launcher)==null?void 0:Zo.zIndex)!=null?vo:vn} !important;`;q.style.cssText+=bn+Dn+Yr}};Zn(),Or(e,n),bs(e,n),xs(e,n);let vt=[],$t=null,_t=null;vt.push(()=>{$t==null||$t(),$t=null,_t==null||_t(),_t=null}),wn&&vt.push(()=>{wn==null||wn.disconnect(),wn=null}),vt.push(()=>{pn==null||pn(),pn=null,rr(),wt&&(wt.remove(),wt=null),at==null||at.element.style.removeProperty("width"),at==null||at.element.style.removeProperty("maxWidth")}),re&&vt.push(()=>{de!==null&&(cancelAnimationFrame(de),de=null),xe==null||xe.destroy(),xe=null,ae==null||ae.destroy(),ae=null,ke=null});let En=null,fr=()=>{En&&(En(),En=null),n.colorScheme==="auto"&&(En=Us(()=>{Or(e,n)}))};fr(),vt.push(()=>{En&&(En(),En=null)});let _n=Zc(Oe),Tn=null,D,jn=!1,Rn=Fc(),hr=0,gn=us(),Mn=0,ee=null,zn=!1,or=!1,jo=1,co=8,jr=new Map,Ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},po=(ti=(ei=n.voiceRecognition)==null?void 0:ei.autoResume)!=null?ti:!1,Hn=l=>{o.emit("voice:state",{active:Ze.active,source:l,timestamp:Date.now()})},fn=()=>{g(l=>({...l,voiceState:{active:Ze.active,timestamp:Date.now(),manuallyDeactivated:Ze.manuallyDeactivated}}))},zo=()=>{var A,L;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=ua(i.voiceState),m=!!l.active,b=Number((L=l.timestamp)!=null?L:0);Ze.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-b<Su&&setTimeout(()=>{var R,B;Ze.active||(Ze.manuallyDeactivated=!1,((B=(R=n.voiceRecognition)==null?void 0:R.provider)==null?void 0:B.type)==="runtype"?D.toggleVoice().then(()=>{Ze.active=D.isVoiceActive(),Hn("restore"),D.isVoiceActive()&&xr()}):Ir("restore"))},1e3)},qo=()=>D?pd(D.getMessages()).filter(l=>!l.__skipPersist):[];function uo(l){if(!(a!=null&&a.save))return;let b={messages:l?pd(l):D?qo():[],metadata:i};try{let A=a.save(b);A instanceof Promise&&A.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let sr=null,Vo=()=>q.querySelector("#persona-scroll-container")||V,zr=()=>{sr!==null&&(cancelAnimationFrame(sr),sr=null),zn=!1},mo=()=>{ee!==null&&(cancelAnimationFrame(ee),ee=null),or=!1,zr()},ar=()=>{if(!zt()||je){ct.parentNode&&ct.remove(),ct.style.display="none";return}ct.parentNode!==_&&_.appendChild(ct),Ke();let l=Ro(V)>0;ct.style.display=gn.isFollowing()||!l?"none":""},go=()=>{gn.pause()&&(mo(),ar())},yr=()=>{gn.resume(),ar()},br=(l=!1)=>{gn.isFollowing()&&(!l&&!jn||(ee!==null&&(cancelAnimationFrame(ee),ee=null),or=!0,ee=requestAnimationFrame(()=>{ee=null,or=!1,gn.isFollowing()&&Uo(Vo(),l?220:140)})))},Uo=(l,m=500)=>{let b=l.scrollTop,A=Ro(l),L=A-b;if(Math.abs(L)<1){Mn=l.scrollTop;return}zr();let R=performance.now();zn=!0;let B=O=>1-Math.pow(1-O,3),z=O=>{if(!gn.isFollowing()){zr();return}let ge=Ro(l);ge!==A&&(A=ge,L=A-b);let ve=O-R,Se=Math.min(ve/m,1),be=B(Se),Te=b+L*be;l.scrollTop=Te,Mn=l.scrollTop,Se<1?sr=requestAnimationFrame(z):(l.scrollTop=A,Mn=l.scrollTop,sr=null,zn=!1)};sr=requestAnimationFrame(z)},Jo=l=>{let m=new Map;l.forEach(b=>{let A=jr.get(b.id);m.set(b.id,{streaming:b.streaming,role:b.role}),!A&&b.role==="assistant"&&o.emit("assistant:message",b),b.role==="assistant"&&(A!=null&&A.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(A?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),jr.clear(),m.forEach((b,A)=>{jr.set(A,b)})},kr=(l,m,b)=>{var Se,be,Te,ze,pt,Xe;let A=document.createElement("div"),R=(()=>{var Me;let $=s.find(Pe=>Pe.renderLoadingIndicator);if($!=null&&$.renderLoadingIndicator)return $.renderLoadingIndicator;if((Me=n.loadingIndicator)!=null&&Me.render)return n.loadingIndicator.render})(),B=($,Me)=>Me==null?!1:typeof Me=="string"?($.textContent=Me,!0):($.appendChild(Me),!0),z=new Set;if(m.forEach($=>{var Yt,sn;z.add($.id);let Me=Nc($,hr),Pe=Oc(Rn,$.id,Me);if(Pe){A.appendChild(Pe.cloneNode(!0));return}let fe=null,Re=s.find(we=>!!($.variant==="reasoning"&&we.renderReasoning||$.variant==="tool"&&we.renderToolCall||$.variant==="approval"&&we.renderApproval||!$.variant&&we.renderMessage)),Ct=(Yt=n.layout)==null?void 0:Yt.messages;if(Re)if($.variant==="reasoning"&&$.reasoning&&Re.renderReasoning){if(!Q)return;fe=Re.renderReasoning({message:$,defaultRenderer:()=>Ks($,n),config:n})}else if($.variant==="tool"&&$.toolCall&&Re.renderToolCall){if(!Ce)return;fe=Re.renderToolCall({message:$,defaultRenderer:()=>Zs($,n),config:n})}else if($.variant==="approval"&&$.approval&&Re.renderApproval){if(n.approval===!1)return;fe=Re.renderApproval({message:$,defaultRenderer:()=>Qs($,n),config:n})}else Re.renderMessage&&(fe=Re.renderMessage({message:$,defaultRenderer:()=>{let we=Oo($,b,Ct,n.messageActions,Ee,{loadingIndicatorRenderer:R,widgetConfig:n});return $.role!=="user"&&na(we,$,n,D),we},config:n}));if(!fe&&$.role==="assistant"&&!$.variant&&n.enableComponentStreaming!==!1&&la($)){let hn=ca($);if(hn){let an=ia(hn,{config:n,message:$,transform:b});if(an)if(n.wrapComponentDirectiveInBubble!==!1){let rt=document.createElement("div");if(rt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),rt.id=`bubble-${$.id}`,rt.setAttribute("data-message-id",$.id),$.content&&$.content.trim()){let ut=document.createElement("div");ut.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ut.innerHTML=b({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),rt.appendChild(ut)}rt.appendChild(an),fe=rt}else{let rt=document.createElement("div");if(rt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",rt.id=`bubble-${$.id}`,rt.setAttribute("data-message-id",$.id),rt.setAttribute("data-persona-component-directive","true"),$.content&&$.content.trim()){let ut=document.createElement("div");ut.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ut.innerHTML=b({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),rt.appendChild(ut)}rt.appendChild(an),fe=rt}}}if(!fe)if($.variant==="reasoning"&&$.reasoning){if(!Q)return;fe=Ks($,n)}else if($.variant==="tool"&&$.toolCall){if(!Ce)return;fe=Zs($,n)}else if($.variant==="approval"&&$.approval){if(n.approval===!1)return;fe=Qs($,n)}else{let we=(sn=n.layout)==null?void 0:sn.messages;we!=null&&we.renderUserMessage&&$.role==="user"?fe=we.renderUserMessage({message:$,config:n,streaming:!!$.streaming}):we!=null&&we.renderAssistantMessage&&$.role==="assistant"?fe=we.renderAssistantMessage({message:$,config:n,streaming:!!$.streaming}):fe=Oo($,b,we,n.messageActions,Ee,{loadingIndicatorRenderer:R,widgetConfig:n}),$.role!=="user"&&fe&&na(fe,$,n,D)}let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${$.id}`,bt.setAttribute("data-wrapper-id",$.id),$.role==="user"&&bt.classList.add("persona-justify-end"),(fe==null?void 0:fe.getAttribute("data-persona-component-directive"))==="true"&&bt.classList.add("persona-w-full"),bt.appendChild(fe),$c(Rn,$.id,Me,bt),A.appendChild(bt)}),(be=(Se=n.features)==null?void 0:Se.toolCallDisplay)!=null&&be.grouped){let $=[],Me=[];m.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ce){Me.push(Pe);return}Me.length>1&&$.push(Me),Me=[]}),Me.length>1&&$.push(Me),$.forEach((Pe,fe)=>{var an,Vn;let Re=Pe.map(rt=>Array.from(A.children).find(ut=>ut instanceof HTMLElement&&ut.getAttribute("data-wrapper-id")===rt.id)).filter(rt=>!!rt);if(Re.length<2)return;let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id=`wrapper-tool-group-${fe}-${Pe[0].id}`,Ct.setAttribute("data-wrapper-id",`tool-group-${fe}-${Pe[0].id}`);let bt=document.createElement("div");bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",bt.setAttribute("data-persona-tool-group","true");let Yt=document.createElement("div");Yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let sn=`Called ${Pe.length} tools`,we=(Vn=(an=n.toolCall)==null?void 0:an.renderGroupedSummary)==null?void 0:Vn.call(an,{messages:Pe,toolCalls:Pe.map(rt=>rt.toolCall).filter(rt=>!!rt),defaultSummary:sn,config:n});B(Yt,we)||(Yt.textContent=sn);let hn=document.createElement("div");hn.className="persona-tool-group-stack persona-flex persona-flex-col",bt.append(Yt,hn),Ct.appendChild(bt),Re[0].before(Ct),Re.forEach((rt,ut)=>{let yn=document.createElement("div");yn.className="persona-tool-group-item persona-relative",yn.setAttribute("data-persona-tool-group-item","true"),ut<Re.length-1&&yn.setAttribute("data-persona-tool-group-connector","true"),yn.appendChild(rt),hn.appendChild(yn)})})}_c(Rn,z);let O=m.some($=>$.role==="assistant"&&$.streaming),ge=m[m.length-1],ve=(ge==null?void 0:ge.role)==="assistant"&&!ge.streaming&&ge.variant!=="approval";if(jn&&m.some($=>$.role==="user")&&!O&&!ve){let $={config:n,streaming:!0,location:"standalone",defaultRenderer:no},Me=s.find(fe=>fe.renderLoadingIndicator),Pe=null;if(Me!=null&&Me.renderLoadingIndicator&&(Pe=Me.renderLoadingIndicator($)),Pe===null&&((Te=n.loadingIndicator)!=null&&Te.render)&&(Pe=n.loadingIndicator.render($)),Pe===null&&(Pe=no()),Pe){let fe=document.createElement("div"),Re=((ze=n.loadingIndicator)==null?void 0:ze.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(Pe);let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id="wrapper-typing-indicator",Ct.setAttribute("data-wrapper-id","typing-indicator"),Ct.appendChild(fe),A.appendChild(Ct)}}if(!jn&&m.length>0){let $=m[m.length-1],Me={config:n,lastMessage:$,messageCount:m.length},Pe=s.find(Re=>Re.renderIdleIndicator),fe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(fe=Pe.renderIdleIndicator(Me)),fe===null&&((pt=n.loadingIndicator)!=null&&pt.renderIdle)&&(fe=n.loadingIndicator.renderIdle(Me)),fe){let Re=document.createElement("div"),Ct=((Xe=n.loadingIndicator)==null?void 0:Xe.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 bt=document.createElement("div");bt.className="persona-flex",bt.id="wrapper-idle-indicator",bt.setAttribute("data-wrapper-id","idle-indicator"),bt.appendChild(Re),A.appendChild(bt)}}Dc(l,A)},Lr=()=>{var O,ge,ve,Se,be;if(!x)return;let l=en(n),m=(O=e.ownerDocument.defaultView)!=null?O:window,b=(ve=(ge=n.launcher)==null?void 0:ge.mobileBreakpoint)!=null?ve:640,A=(be=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?be:!0,L=m.innerWidth<=b,R=A&&L&&x,B=Jn(n).reveal;T?(q.style.removeProperty("display"),q.style.display=l?"flex":"",q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-95","persona-opacity-0"),F.classList.add("persona-scale-100","persona-opacity-100"),y?y.element.style.display="none":se&&(se.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!R?(q.style.removeProperty("display"),q.style.display="flex",q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(q.style.setProperty("display","none","important"),q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(q.style.display="",q.classList.add("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100"),F.classList.add("persona-scale-95","persona-opacity-0")),y?y.element.style.display=l?"none":"":se&&(se.style.display=l?"none":""))},Rt=(l,m="user")=>{var R,B;if(!x||T===l)return;let b=T;T=l,Lr();let A=(()=>{var Te,ze,pt,Xe,$,Me,Pe;let z=(ze=(Te=n.launcher)==null?void 0:Te.sidebarMode)!=null?ze:!1,O=(pt=e.ownerDocument.defaultView)!=null?pt:window,ge=($=(Xe=n.launcher)==null?void 0:Xe.mobileFullscreen)!=null?$:!0,ve=(Pe=(Me=n.launcher)==null?void 0:Me.mobileBreakpoint)!=null?Pe:640,Se=O.innerWidth<=ve,be=en(n)&&ge&&Se;return z||ge&&Se&&x||be})();if(T&&A){if(!$t){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&($t=Js(O,(B=(R=n.launcher)==null?void 0:R.zIndex)!=null?B:vn))}_t||(_t=Ys(e.ownerDocument))}else T||($t==null||$t(),$t=null,_t==null||_t(),_t=null);T&&(P(),br(!0));let L={open:T,source:m,timestamp:Date.now()};T&&!b?o.emit("widget:opened",L):!T&&b&&o.emit("widget:closed",L),o.emit("widget:state",{open:T,launcherEnabled:x,voiceActive:Ze.active,streaming:D.isStreaming()})},qr=l=>{te.disabled=l,j&&(j.disabled=l),_n.buttons.forEach(m=>{m.disabled=l}),st.dataset.personaComposerStreaming=l?"true":"false",st.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Vr=()=>{Ze.active||Z&&Z.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Vr(),200)});let fo=()=>{var b,A,L,R,B,z,O,ge,ve,Se,be;Xt.textContent=(A=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?A:"Hello \u{1F44B}",$e.textContent=(R=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",Z.placeholder=(z=(B=n.copy)==null?void 0:B.inputPlaceholder)!=null?z:"How can I help...";let l=V.querySelector("[data-persona-intro-card]");if(l){let Te=((O=n.copy)==null?void 0:O.showWelcomeCard)!==!1;l.style.display=Te?"":"none",Te?(V.classList.remove("persona-gap-3"),V.classList.add("persona-gap-6")):(V.classList.remove("persona-gap-6"),V.classList.add("persona-gap-3"))}(ve=(ge=n.sendButton)==null?void 0:ge.useIcon)!=null&&ve||(te.textContent=(be=(Se=n.copy)==null?void 0:Se.sendButtonLabel)!=null?be:"Send"),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.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=>{g(m=>({...m,sessionId:l}))}}),D=new Lo(n,{onMessagesChanged(l){kr(oe,l,I),D&&(l.some(L=>L.role==="user")?_n.render([],D,Z,l):_n.render(n.suggestionChips,D,Z,l,n.suggestionChipsConfig)),br(!jn),Jo(l);let m=[...l].reverse().find(A=>A.role==="user"),b=Ze.lastUserMessageId;m&&m.id!==b&&(Ze.lastUserMessageId=m.id,o.emit("user:message",m)),Ze.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),uo(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};Et(Nt,(L=>{var R,B,z,O;return L==="idle"?(R=m.idleText)!=null?R:cn.idle:L==="connecting"?(B=m.connectingText)!=null?B:cn.connecting:L==="connected"?(z=m.connectedText)!=null?z:cn.connected:L==="error"?(O=m.errorText)!=null?O:cn.error:cn[L]})(l),m,l)},onStreamingChanged(l){jn=l,qr(l),D&&kr(oe,D.getMessages(),I),l||br(!0)},onVoiceStatusChanged(l){var m,b;if(((b=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype")switch(l){case"listening":break;case"processing":_e(),X();break;case"speaking":_e(),Ve();break;default:l==="idle"&&D.isBargeInActive()?(_e(),xr(),j==null||j.setAttribute("aria-label","End voice session")):(Ze.active=!1,_e(),Hn("system"),fn());break}},onArtifactsState(l){$n=l,An()}}),ur.current=D,((ri=(ni=n.voiceRecognition)==null?void 0:ni.provider)==null?void 0:ri.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)}),ae&&D.setSSEEventCallback((l,m)=>{ae==null||ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=ua(l.metadata),E.syncFromMetadata()),(m=l.messages)!=null&&m.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ho=l=>{var L;l.preventDefault();let m=Z.value.trim(),b=(L=We==null?void 0:We.hasAttachments())!=null?L:!1;if(!m&&!b)return;let A;b&&(A=[],A.push(...We.getContentParts()),m&&A.push(os(m))),Z.value="",Z.style.height="auto",D.sendMessage(m,{contentParts:A}),b&&We.clearAttachments()},yo=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),te.click())},bo=async l=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!We)return;let m=Eu(l.clipboardData);m.length!==0&&(l.preventDefault(),await We.handleFiles(m))},un=null,kn=!1,ir=null,qe=null,xo=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ir=(l="user")=>{var R,B,z,O,ge,ve,Se;if(kn||D.isStreaming())return;let m=xo();if(!m)return;un=new m;let A=(B=((R=n.voiceRecognition)!=null?R:{}).pauseDuration)!=null?B:2e3;un.continuous=!0,un.interimResults=!0,un.lang="en-US";let L=Z.value;un.onresult=be=>{let Te="",ze="";for(let Xe=0;Xe<be.results.length;Xe++){let $=be.results[Xe],Me=$[0].transcript;$.isFinal?Te+=Me+" ":ze=Me}let pt=L+Te+ze;Z.value=pt,ir&&clearTimeout(ir),(Te||ze)&&(ir=window.setTimeout(()=>{let Xe=Z.value.trim();Xe&&un&&kn&&(qn(),Z.value="",Z.style.height="auto",D.sendMessage(Xe,{viaVoice:!0}))},A))},un.onerror=be=>{be.error!=="no-speech"&&qn()},un.onend=()=>{if(kn){let be=Z.value.trim();be&&be!==L.trim()&&(Z.value="",Z.style.height="auto",D.sendMessage(be,{viaVoice:!0})),qn()}};try{if(un.start(),kn=!0,Ze.active=!0,l!=="system"&&(Ze.manuallyDeactivated=!1),Hn(l),fn(),j){let be=(z=n.voiceRecognition)!=null?z:{};qe={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(O=be.iconName)!=null?O:"mic",iconSize:parseFloat((Se=(ve=be.iconSize)!=null?ve:(ge=n.sendButton)==null?void 0:ge.size)!=null?Se:"40")||24};let Te=be.recordingBackgroundColor,ze=be.recordingIconColor,pt=be.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=Te!=null?Te:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=ze!=null?ze:"var(--persona-voice-recording-indicator, #ffffff)",ze){let Xe=j.querySelector("svg");Xe&&Xe.setAttribute("stroke",ze)}pt&&(j.style.borderColor=pt),j.setAttribute("aria-label","Stop voice recognition")}}catch{qn("system")}},qn=(l="user")=>{if(kn){if(kn=!1,ir&&(clearTimeout(ir),ir=null),un){try{un.stop()}catch{}un=null}if(Ze.active=!1,Hn(l),fn(),j){if(j.classList.remove("persona-voice-recording"),qe){j.style.backgroundColor=qe.backgroundColor,j.style.color=qe.color,j.style.borderColor=qe.borderColor;let m=j.querySelector("svg");m&&m.setAttribute("stroke",qe.color||"currentColor"),qe=null}j.setAttribute("aria-label","Start voice recognition")}}},Yo=(l,m)=>{var $,Me,Pe,fe,Re,Ct,bt,Yt;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=(($=l==null?void 0:l.provider)==null?void 0:$.type)==="runtype";if(!(b||A))return null;let R=h("div","persona-send-button-wrapper"),B=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let z=(Me=l==null?void 0:l.iconName)!=null?Me:"mic",O=(Pe=m==null?void 0:m.size)!=null?Pe:"40px",ge=(fe=l==null?void 0:l.iconSize)!=null?fe:O,ve=parseFloat(ge)||24,Se=(Re=l==null?void 0:l.backgroundColor)!=null?Re:m==null?void 0:m.backgroundColor,be=(Ct=l==null?void 0:l.iconColor)!=null?Ct:m==null?void 0:m.textColor;B.style.width=ge,B.style.height=ge,B.style.minWidth=ge,B.style.minHeight=ge,B.style.fontSize="18px",B.style.lineHeight="1",be?B.style.color=be:B.style.color="var(--persona-text, #111827)";let ze=me(z,ve,be||"currentColor",1.5);ze?B.appendChild(ze):B.textContent="\u{1F3A4}",Se?B.style.backgroundColor=Se:B.style.backgroundColor="",l!=null&&l.borderWidth&&(B.style.borderWidth=l.borderWidth,B.style.borderStyle="solid"),l!=null&&l.borderColor&&(B.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(B.style.paddingLeft=l.paddingX,B.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(B.style.paddingTop=l.paddingY,B.style.paddingBottom=l.paddingY),R.appendChild(B);let pt=(bt=l==null?void 0:l.tooltipText)!=null?bt:"Start voice recognition";if(((Yt=l==null?void 0:l.showTooltip)!=null?Yt:!1)&&pt){let sn=h("div","persona-send-button-tooltip");sn.textContent=pt,R.appendChild(sn)}return{micButton:B,micButtonWrapper:R}},Ur=()=>{var m,b,A,L,R;if(!j||qe)return;let l=(m=n.voiceRecognition)!=null?m:{};qe={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(b=l.iconName)!=null?b:"mic",iconSize:parseFloat((R=(L=l.iconSize)!=null?L:(A=n.sendButton)==null?void 0:A.size)!=null?R:"40")||24}},Jr=(l,m)=>{var R,B,z,O,ge;if(!j)return;let b=j.querySelector("svg");b&&b.remove();let A=(ge=qe==null?void 0:qe.iconSize)!=null?ge:parseFloat((O=(z=(R=n.voiceRecognition)==null?void 0:R.iconSize)!=null?z:(B=n.sendButton)==null?void 0:B.size)!=null?O:"40")||24,L=me(l,A,m,1.5);L&&j.appendChild(L)},Pr=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},xr=()=>{var L;if(!j)return;Ur();let l=(L=n.voiceRecognition)!=null?L:{},m=l.recordingBackgroundColor,b=l.recordingIconColor,A=l.recordingBorderColor;if(Pr(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let R=j.querySelector("svg");R&&R.setAttribute("stroke",b)}A&&(j.style.borderColor=A),j.setAttribute("aria-label","Stop voice recognition")},X=()=>{var z,O,ge,ve,Se,be,Te,ze;if(!j)return;Ur();let l=(z=n.voiceRecognition)!=null?z:{},m=D.getVoiceInterruptionMode(),b=(O=l.processingIconName)!=null?O:"loader",A=(ve=(ge=l.processingIconColor)!=null?ge:qe==null?void 0:qe.color)!=null?ve:"",L=(be=(Se=l.processingBackgroundColor)!=null?Se:qe==null?void 0:qe.backgroundColor)!=null?be:"",R=(ze=(Te=l.processingBorderColor)!=null?Te:qe==null?void 0:qe.borderColor)!=null?ze:"";Pr(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=L,j.style.borderColor=R;let B=A||"currentColor";j.style.color=B,Jr(b,B),j.setAttribute("aria-label","Processing voice input"),m==="none"&&(j.style.cursor="default")},Ve=()=>{var ge,ve,Se,be,Te,ze,pt,Xe,$,Me,Pe,fe;if(!j)return;Ur();let l=(ge=n.voiceRecognition)!=null?ge:{},m=D.getVoiceInterruptionMode(),b=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(ve=l.speakingIconName)!=null?ve:b,L=(ze=l.speakingIconColor)!=null?ze:m==="barge-in"?(be=(Se=l.recordingIconColor)!=null?Se:qe==null?void 0:qe.color)!=null?be:"":(Te=qe==null?void 0:qe.color)!=null?Te:"",R=($=l.speakingBackgroundColor)!=null?$:m==="barge-in"?(pt=l.recordingBackgroundColor)!=null?pt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=qe==null?void 0:qe.backgroundColor)!=null?Xe:"",B=(fe=l.speakingBorderColor)!=null?fe:m==="barge-in"?(Me=l.recordingBorderColor)!=null?Me:"":(Pe=qe==null?void 0:qe.borderColor)!=null?Pe:"";Pr(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=R,j.style.borderColor=B;let z=L||"currentColor";j.style.color=z,Jr(A,z);let O=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",O),m==="none"&&(j.style.cursor="default"),m==="barge-in"&&j.classList.add("persona-voice-recording")},_e=()=>{var l,m,b;j&&(Pr(),qe&&(j.style.backgroundColor=(l=qe.backgroundColor)!=null?l:"",j.style.color=(m=qe.color)!=null?m:"",j.style.borderColor=(b=qe.borderColor)!=null?b:"",Jr(qe.iconName,qe.color||"currentColor"),qe=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},Tt=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let b=D.getVoiceStatus(),A=D.getVoiceInterruptionMode();if(A==="none"&&(b==="processing"||b==="speaking"))return;if(A==="cancel"&&(b==="processing"||b==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{Ze.active=!1,Ze.manuallyDeactivated=!0,fn(),Hn("user"),_e()});return}D.toggleVoice().then(()=>{Ze.active=D.isVoiceActive(),Ze.manuallyDeactivated=!D.isVoiceActive(),fn(),Hn("user"),D.isVoiceActive()?xr():_e()});return}if(kn){let b=Z.value.trim();Ze.manuallyDeactivated=!0,fn(),qn("user"),b&&(Z.value="",Z.style.height="auto",D.sendMessage(b))}else Ze.manuallyDeactivated=!1,fn(),Ir("user")};Vt=Tt,j&&(j.addEventListener("click",Tt),vt.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),_e()):qn("system"),j&&j.removeEventListener("click",Tt)}));let yt=o.on("assistant:complete",()=>{po&&(Ze.active||Ze.manuallyDeactivated||po==="assistant"&&!Ze.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!Ze.active&&!Ze.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.toggleVoice().then(()=>{Ze.active=D.isVoiceActive(),Hn("auto"),D.isVoiceActive()&&xr()}):Ir("auto"))},600))});vt.push(yt);let St=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});vt.push(St);let et=()=>{Rt(!T,"user")},y=null,se=null;if(x){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>Do(n,et).element,onToggle:et});m&&(se=m)}se||(y=Do(n,et))}y?e.appendChild(y.element):se&&e.appendChild(se),Lr(),_n.render(n.suggestionChips,D,Z,void 0,n.suggestionChipsConfig),fo(),qr(D.isStreaming()),br(!0),zo(),k&&(x?T&&setTimeout(()=>Vr(),200):setTimeout(()=>Vr(),0));let P=()=>{var O,ge,ve,Se,be,Te,ze,pt,Xe,$,Me,Pe,fe,Re,Ct,bt,Yt,sn,we,hn,an,Vn;let l=en(n),m=(ge=(O=n.launcher)==null?void 0:O.sidebarMode)!=null?ge:!1,b=l||m||((Se=(ve=n.launcher)==null?void 0:ve.fullHeight)!=null?Se:!1),A=(be=e.ownerDocument.defaultView)!=null?be:window,L=(ze=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?ze:!0,R=(Xe=(pt=n.launcher)==null?void 0:pt.mobileBreakpoint)!=null?Xe:640,B=A.innerWidth<=R,z=L&&B&&x;try{if(z){Zn(),Or(e,n);return}if(W&&(W=!1,Zn(),Or(e,n)),!x&&!l){F.style.height="",F.style.width="";return}if(!m&&!l){let rt=(Me=($=n==null?void 0:n.launcher)==null?void 0:$.width)!=null?Me:n==null?void 0:n.launcherWidth,ut=rt!=null?rt:Nn;F.style.width=ut,F.style.maxWidth=ut}if(Kn(),!b){let rt=A.innerHeight,ut=64,yn=(fe=(Pe=n.launcher)==null?void 0:Pe.heightOffset)!=null?fe:0,lr=Math.max(200,rt-ut),Ue=Math.min(640,lr),At=Math.max(200,Ue-yn);F.style.height=`${At}px`}}finally{if(Ke(),Lr(),T&&x){let ut=((Re=e.ownerDocument.defaultView)!=null?Re:window).innerWidth<=((bt=(Ct=n.launcher)==null?void 0:Ct.mobileBreakpoint)!=null?bt:640),yn=(sn=(Yt=n.launcher)==null?void 0:Yt.sidebarMode)!=null?sn:!1,lr=(hn=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?hn:!0,Ue=en(n)&&lr&&ut,At=yn||lr&&ut&&x||Ue;if(At&&!_t){let Wr=e.getRootNode(),Rr=Wr instanceof ShadowRoot?Wr.host:e.closest(".persona-host");Rr&&!$t&&($t=Js(Rr,(Vn=(an=n.launcher)==null?void 0:an.zIndex)!=null?Vn:vn)),_t=Ys(e.ownerDocument)}else At||($t==null||$t(),$t=null,_t==null||_t(),_t=null)}}};P();let S=(oi=e.ownerDocument.defaultView)!=null?oi:window;if(S.addEventListener("resize",P),vt.push(()=>S.removeEventListener("resize",P)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ke()});l.observe(st),vt.push(()=>l.disconnect())}Mn=V.scrollTop;let Y=()=>{let l=V.scrollTop,{action:m,nextLastScrollTop:b}=ms({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:Mn,nearBottom:Ho(V,co),userScrollThreshold:jo,isAutoScrolling:zn||or,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Mn=b,m==="resume"){yr();return}m==="pause"&&go()};V.addEventListener("scroll",Y,{passive:!0}),vt.push(()=>V.removeEventListener("scroll",Y));let N=l=>{let m=gs({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:Ho(V,co),resumeWhenNearBottom:!0});m==="pause"?go():m==="resume"&&yr()};V.addEventListener("wheel",N,{passive:!0}),vt.push(()=>V.removeEventListener("wheel",N)),ct.addEventListener("click",()=>{V.scrollTop=V.scrollHeight,Mn=V.scrollTop,yr(),br(!0)}),vt.push(()=>ct.remove()),vt.push(()=>{mo()});let pe=()=>{ce&&(Tn&&(ce.removeEventListener("click",Tn),Tn=null),x?(ce.style.display="",Tn=()=>{Rt(!1,"user")},ce.addEventListener("click",Tn)):ce.style.display="none")};pe(),(()=>{let{clearChatButton:l}=le;l&&l.addEventListener("click",()=>{D.clearMessages(),Rn.clear(),yr();try{localStorage.removeItem(io),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${io}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==io)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let b=a.clear();b instanceof Promise&&b.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}i={},E.syncFromMetadata(),ae==null||ae.clear(),xe==null||xe.update()})})(),lt&&lt.addEventListener("submit",ho),Z==null||Z.addEventListener("keydown",yo),Z==null||Z.addEventListener("paste",bo);let tt="persona-attachment-drop-active",Ht=0,nn=()=>{Ht=0,_.classList.remove(tt)},Ft=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&We!==null},Kt=l=>{!Ss(l.dataTransfer)||!Ft()||(Ht++,Ht===1&&_.classList.add(tt))},Ge=l=>{!Ss(l.dataTransfer)||!Ft()||(Ht--,Ht<=0&&nn())},Mt=l=>{!Ss(l.dataTransfer)||!Ft()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Zt=l=>{var b;if(!Ss(l.dataTransfer)||!Ft())return;l.preventDefault(),l.stopPropagation(),nn();let m=Array.from((b=l.dataTransfer.files)!=null?b:[]);m.length!==0&&We.handleFiles(m)},Ot=!0;_.addEventListener("dragenter",Kt,Ot),_.addEventListener("dragleave",Ge,Ot),e.addEventListener("dragover",Mt,Ot),e.addEventListener("drop",Zt,Ot);let Lt=e.ownerDocument,Ln=l=>{Ft()&&l.preventDefault()},Aa=l=>{Ft()&&l.preventDefault()};Lt.addEventListener("dragover",Ln),Lt.addEventListener("drop",Aa),vt.push(()=>{lt&&lt.removeEventListener("submit",ho),Z==null||Z.removeEventListener("keydown",yo),Z==null||Z.removeEventListener("paste",bo)}),vt.push(()=>{_.removeEventListener("dragenter",Kt,Ot),_.removeEventListener("dragleave",Ge,Ot),e.removeEventListener("dragover",Mt,Ot),e.removeEventListener("drop",Zt,Ot),Lt.removeEventListener("dragover",Ln),Lt.removeEventListener("drop",Aa),nn()}),vt.push(()=>{D.cancel()}),y?vt.push(()=>{y==null||y.destroy()}):se&&vt.push(()=>{se==null||se.remove()});let Jt={update(l){var pi,ui,mi,gi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Fi,Oi,$i,_i,ji,zi,qi,Vi,Ui,Ji,Yi,Gi,Xi,Ki,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,zl,ql,Vl,Ul,Jl,Yl,Gl,Xl,Kl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc;let m=n.toolCall,b=n.messageActions,A=(pi=n.layout)==null?void 0:pi.messages,L=n.colorScheme,R=n.loadingIndicator,B=n.iterationDisplay,z=(ui=n.features)==null?void 0:ui.showReasoning,O=(mi=n.features)==null?void 0:mi.showToolCalls,ge=(gi=n.features)==null?void 0:gi.toolCallDisplay,ve=(fi=n.features)==null?void 0:fi.reasoningDisplay;n={...n,...l},Zn(),Or(e,n),bs(e,n),xs(e,n),An(),n.colorScheme!==L&&fr();let Se=vs.getForInstance(n.plugins);s.length=0,s.push(...Se),x=(yi=(hi=n.launcher)==null?void 0:hi.enabled)!=null?yi:!0,C=(xi=(bi=n.launcher)==null?void 0:bi.autoExpand)!=null?xi:!1,Q=(Ci=(vi=n.features)==null?void 0:vi.showReasoning)!=null?Ci:!0,Ce=(Si=(wi=n.features)==null?void 0:wi.showToolCalls)!=null?Si:!0,Ae=(Ei=(Ai=n.features)==null?void 0:Ai.scrollToBottom)!=null?Ei:{},ht(),ar();let be=re;if(re=(Mi=(Ti=n.features)==null?void 0:Ti.showEventStreamToggle)!=null?Mi:!1,re&&!be){if(ae||(ke=new _o(he),ae=new $o(Le,ke),ke.open().then(()=>ae==null?void 0:ae.restore()).catch(()=>{}),D.setSSEEventCallback((U,dt)=>{ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:U,timestamp:Date.now(),payload:JSON.stringify(dt)})})),!Qe&&ot){let U=(Li=(ki=n.features)==null?void 0:ki.eventStream)==null?void 0:Li.classNames,dt="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:"");Qe=h("button",dt),Qe.style.width="28px",Qe.style.height="28px",Qe.style.color=Cn.actionIconColor,Qe.type="button",Qe.setAttribute("aria-label","Event Stream"),Qe.title="Event Stream";let Bt=me("activity","18px","currentColor",1.5);Bt&&Qe.appendChild(Bt);let Je=le.clearChatButtonWrapper,mt=le.closeButtonWrapper,Gt=Je||mt;Gt&&Gt.parentNode===ot?ot.insertBefore(Qe,Gt):ot.appendChild(Qe),Qe.addEventListener("click",()=>{je?On():tr()})}}else!re&&be&&(On(),Qe&&(Qe.remove(),Qe=null),ae==null||ae.clear(),ke==null||ke.destroy(),ae=null,ke=null);if(((Ii=n.launcher)==null?void 0:Ii.enabled)===!1&&y&&(y.destroy(),y=null),((Pi=n.launcher)==null?void 0:Pi.enabled)===!1&&se&&(se.remove(),se=null),((Wi=n.launcher)==null?void 0:Wi.enabled)!==!1&&!y&&!se){let U=s.find(dt=>dt.renderLauncher);if(U!=null&&U.renderLauncher){let dt=U.renderLauncher({config:n,defaultRenderer:()=>Do(n,et).element,onToggle:et});dt&&(se=dt,e.appendChild(se))}se||(y=Do(n,et),e.appendChild(y.element))}y&&y.update(n),Pt&&((Ri=n.launcher)==null?void 0:Ri.title)!==void 0&&(Pt.textContent=n.launcher.title),Wt&&((Hi=n.launcher)==null?void 0:Hi.subtitle)!==void 0&&(Wt.textContent=n.launcher.subtitle);let Te=(Bi=n.layout)==null?void 0:Bi.header;if((Te==null?void 0:Te.layout)!==M&&ot){let U=Te?No(n,Te,{showClose:x,onClose:()=>Rt(!1,"user")}):Sr({config:n,showClose:x,onClose:()=>Rt(!1,"user")});ot.replaceWith(U.header),ot=U.header,He=U.iconHolder,Pt=U.headerTitle,Wt=U.headerSubtitle,ce=U.closeButton,M=Te==null?void 0:Te.layout}else if(Te&&(He&&(He.style.display=Te.showIcon===!1?"none":""),Pt&&(Pt.style.display=Te.showTitle===!1?"none":""),Wt&&(Wt.style.display=Te.showSubtitle===!1?"none":""),ce&&(ce.style.display=Te.showCloseButton===!1?"none":""),le.clearChatButtonWrapper)){let U=Te.showClearChat;if(U!==void 0){le.clearChatButtonWrapper.style.display=U?"":"none";let{closeButtonWrapper:dt}=le;dt&&!dt.classList.contains("persona-absolute")&&(U?dt.classList.remove("persona-ml-auto"):dt.classList.add("persona-ml-auto"))}}let pt=((Di=n.layout)==null?void 0:Di.showHeader)!==!1;ot&&(ot.style.display=pt?"":"none");let Xe=((Ni=n.layout)==null?void 0:Ni.showFooter)!==!1;st&&(st.style.display=Xe?"":"none"),Ke(),ar(),x!==w?x?Rt(C,"auto"):(T=!0,Lr()):C!==H&&Rt(C,"auto"),H=C,w=x,P(),pe();let Pe=JSON.stringify(l.toolCall)!==JSON.stringify(m),fe=JSON.stringify(n.messageActions)!==JSON.stringify(b),Re=JSON.stringify((Fi=n.layout)==null?void 0:Fi.messages)!==JSON.stringify(A),Ct=((Oi=n.loadingIndicator)==null?void 0:Oi.render)!==(R==null?void 0:R.render)||(($i=n.loadingIndicator)==null?void 0:$i.renderIdle)!==(R==null?void 0:R.renderIdle)||((_i=n.loadingIndicator)==null?void 0:_i.showBubble)!==(R==null?void 0:R.showBubble),bt=n.iterationDisplay!==B,Yt=((zi=(ji=n.features)==null?void 0:ji.showReasoning)!=null?zi:!0)!==(z!=null?z:!0)||((Vi=(qi=n.features)==null?void 0:qi.showToolCalls)!=null?Vi:!0)!==(O!=null?O:!0)||JSON.stringify((Ui=n.features)==null?void 0:Ui.toolCallDisplay)!==JSON.stringify(ge)||JSON.stringify((Ji=n.features)==null?void 0:Ji.reasoningDisplay)!==JSON.stringify(ve);(Pe||fe||Re||Ct||bt||Yt)&&D&&(hr++,kr(oe,D.getMessages(),I));let we=(Yi=n.launcher)!=null?Yi:{},hn=(Gi=we.headerIconHidden)!=null?Gi:!1,an=(Ki=(Xi=n.layout)==null?void 0:Xi.header)==null?void 0:Ki.showIcon,Vn=hn||an===!1,rt=we.headerIconName,ut=(Zi=we.headerIconSize)!=null?Zi:"48px";if(He){let U=_.querySelector(".persona-border-b-persona-divider"),dt=U==null?void 0:U.querySelector(".persona-flex-col");if(Vn)He.style.display="none",U&&dt&&!U.contains(dt)&&U.insertBefore(dt,U.firstChild);else{if(He.style.display="",He.style.height=ut,He.style.width=ut,U&&dt&&(U.contains(He)?He.nextSibling!==dt&&(He.remove(),U.insertBefore(He,dt)):U.insertBefore(He,dt)),rt){let Je=parseFloat(ut)||24,mt=me(rt,Je*.6,"#ffffff",2);mt?He.replaceChildren(mt):He.textContent=(Qi=we.agentIconText)!=null?Qi:"\u{1F4AC}"}else if(we.iconUrl){let Je=He.querySelector("img");if(Je)Je.src=we.iconUrl,Je.style.height=ut,Je.style.width=ut;else{let mt=document.createElement("img");mt.src=we.iconUrl,mt.alt="",mt.className="persona-rounded-xl persona-object-cover",mt.style.height=ut,mt.style.width=ut,He.replaceChildren(mt)}}else{let Je=He.querySelector("svg"),mt=He.querySelector("img");(Je||mt)&&He.replaceChildren(),He.textContent=(el=we.agentIconText)!=null?el:"\u{1F4AC}"}let Bt=He.querySelector("img");Bt&&(Bt.style.height=ut,Bt.style.width=ut)}}let yn=(nl=(tl=n.layout)==null?void 0:tl.header)==null?void 0:nl.showTitle,lr=(ol=(rl=n.layout)==null?void 0:rl.header)==null?void 0:ol.showSubtitle;if(Pt&&(Pt.style.display=yn===!1?"none":""),Wt&&(Wt.style.display=lr===!1?"none":""),ce){((al=(sl=n.layout)==null?void 0:sl.header)==null?void 0:al.showCloseButton)===!1?ce.style.display="none":ce.style.display="";let dt=(il=we.closeButtonSize)!=null?il:"32px",Bt=(ll=we.closeButtonPlacement)!=null?ll:"inline";ce.style.height=dt,ce.style.width=dt;let{closeButtonWrapper:Je}=le,mt=Bt==="top-right",Gt=Je==null?void 0:Je.classList.contains("persona-absolute");if(Je&&mt!==Gt)if(Je.remove(),mt)Je.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",_.style.position="relative",_.appendChild(Je);else{let nt=(dl=(cl=we.clearChat)==null?void 0:cl.placement)!=null?dl:"inline",Qt=(ul=(pl=we.clearChat)==null?void 0:pl.enabled)!=null?ul:!0;Je.className=Qt&&nt==="inline"?"":"persona-ml-auto";let xn=_.querySelector(".persona-border-b-persona-divider");xn&&xn.appendChild(Je)}if(ce.style.color=we.closeButtonColor||Cn.actionIconColor,we.closeButtonBackgroundColor?(ce.style.backgroundColor=we.closeButtonBackgroundColor,ce.classList.remove("hover:persona-bg-gray-100")):(ce.style.backgroundColor="",ce.classList.add("hover:persona-bg-gray-100")),we.closeButtonBorderWidth||we.closeButtonBorderColor){let nt=we.closeButtonBorderWidth||"0px",Qt=we.closeButtonBorderColor||"transparent";ce.style.border=`${nt} solid ${Qt}`,ce.classList.remove("persona-border-none")}else ce.style.border="",ce.classList.add("persona-border-none");we.closeButtonBorderRadius?(ce.style.borderRadius=we.closeButtonBorderRadius,ce.classList.remove("persona-rounded-full")):(ce.style.borderRadius="",ce.classList.add("persona-rounded-full")),we.closeButtonPaddingX?(ce.style.paddingLeft=we.closeButtonPaddingX,ce.style.paddingRight=we.closeButtonPaddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),we.closeButtonPaddingY?(ce.style.paddingTop=we.closeButtonPaddingY,ce.style.paddingBottom=we.closeButtonPaddingY):(ce.style.paddingTop="",ce.style.paddingBottom="");let ln=(ml=we.closeButtonIconName)!=null?ml:"x",Un=(gl=we.closeButtonIconText)!=null?gl:"\xD7";ce.innerHTML="";let mn=me(ln,"20px","currentColor",2);mn?ce.appendChild(mn):ce.textContent=Un;let jt=(fl=we.closeButtonTooltipText)!=null?fl:"Close chat",In=(hl=we.closeButtonShowTooltip)!=null?hl:!0;if(ce.setAttribute("aria-label",jt),Je&&(Je._cleanupTooltip&&(Je._cleanupTooltip(),delete Je._cleanupTooltip),In&&jt)){let nt=null,Qt=()=>{if(nt||!ce)return;let Br=ce.ownerDocument,So=Br.body;if(!So)return;nt=Qn(Br,"div","persona-clear-chat-tooltip"),nt.textContent=jt;let Ao=Qn(Br,"div");Ao.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ao);let Dr=ce.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Cr),nt.style.left=`${Dr.left+Dr.width/2}px`,nt.style.top=`${Dr.top-8}px`,nt.style.transform="translate(-50%, -100%)",So.appendChild(nt)},xn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Je.addEventListener("mouseenter",Qt),Je.addEventListener("mouseleave",xn),ce.addEventListener("focus",Qt),ce.addEventListener("blur",xn),Je._cleanupTooltip=()=>{xn(),Je&&(Je.removeEventListener("mouseenter",Qt),Je.removeEventListener("mouseleave",xn)),ce&&(ce.removeEventListener("focus",Qt),ce.removeEventListener("blur",xn))}}}let{clearChatButton:Ue,clearChatButtonWrapper:At}=le;if(Ue){let U=(yl=we.clearChat)!=null?yl:{},dt=(bl=U.enabled)!=null?bl:!0,Bt=(vl=(xl=n.layout)==null?void 0:xl.header)==null?void 0:vl.showClearChat,Je=Bt!==void 0?Bt:dt,mt=(Cl=U.placement)!=null?Cl:"inline";if(At){At.style.display=Je?"":"none";let{closeButtonWrapper:Gt}=le;Gt&&!Gt.classList.contains("persona-absolute")&&(Je?Gt.classList.remove("persona-ml-auto"):Gt.classList.add("persona-ml-auto"));let ln=mt==="top-right",Un=At.classList.contains("persona-absolute");if(ln!==Un&&Je){if(At.remove(),ln)At.className="persona-absolute persona-top-4 persona-z-50",At.style.right="48px",_.style.position="relative",_.appendChild(At);else{At.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",At.style.right="";let jt=_.querySelector(".persona-border-b-persona-divider"),In=le.closeButtonWrapper;jt&&In&&In.parentElement===jt?jt.insertBefore(At,In):jt&&jt.appendChild(At)}let mn=le.closeButtonWrapper;mn&&!mn.classList.contains("persona-absolute")&&(ln?mn.classList.add("persona-ml-auto"):mn.classList.remove("persona-ml-auto"))}}if(Je){let Gt=(wl=U.size)!=null?wl:"32px";Ue.style.height=Gt,Ue.style.width=Gt;let ln=(Sl=U.iconName)!=null?Sl:"refresh-cw",Un=(Al=U.iconColor)!=null?Al:"";Ue.style.color=Un||Cn.actionIconColor,Ue.innerHTML="";let mn=me(ln,"20px","currentColor",2);if(mn&&Ue.appendChild(mn),U.backgroundColor?(Ue.style.backgroundColor=U.backgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),U.borderWidth||U.borderColor){let nt=U.borderWidth||"0px",Qt=U.borderColor||"transparent";Ue.style.border=`${nt} solid ${Qt}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");U.borderRadius?(Ue.style.borderRadius=U.borderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),U.paddingX?(Ue.style.paddingLeft=U.paddingX,Ue.style.paddingRight=U.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),U.paddingY?(Ue.style.paddingTop=U.paddingY,Ue.style.paddingBottom=U.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let jt=(El=U.tooltipText)!=null?El:"Clear chat",In=(Tl=U.showTooltip)!=null?Tl:!0;if(Ue.setAttribute("aria-label",jt),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),In&&jt)){let nt=null,Qt=()=>{if(nt||!Ue)return;let Br=Ue.ownerDocument,So=Br.body;if(!So)return;nt=Qn(Br,"div","persona-clear-chat-tooltip"),nt.textContent=jt;let Ao=Qn(Br,"div");Ao.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ao);let Dr=Ue.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Cr),nt.style.left=`${Dr.left+Dr.width/2}px`,nt.style.top=`${Dr.top-8}px`,nt.style.transform="translate(-50%, -100%)",So.appendChild(nt)},xn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};At.addEventListener("mouseenter",Qt),At.addEventListener("mouseleave",xn),Ue.addEventListener("focus",Qt),Ue.addEventListener("blur",xn),At._cleanupTooltip=()=>{xn(),At&&(At.removeEventListener("mouseenter",Qt),At.removeEventListener("mouseleave",xn)),Ue&&(Ue.removeEventListener("focus",Qt),Ue.removeEventListener("blur",xn))}}}}let Wr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Cs],Rr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ao.message,ao.messageAndClick];E=ws({parsers:Wr,handlers:Rr,getSessionMetadata:p,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),I=ud(n,E,J),D.updateConfig(n),kr(oe,D.getMessages(),I),_n.render(n.suggestionChips,D,Z,void 0,n.suggestionChipsConfig),fo(),qr(D.isStreaming());let Go=((Ml=n.voiceRecognition)==null?void 0:Ml.enabled)===!0,Xo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ko=((Ll=(kl=n.voiceRecognition)==null?void 0:kl.provider)==null?void 0:Ll.type)==="runtype";if(Go&&(Xo||Ko))if(!j||!Ie){let U=Yo(n.voiceRecognition,n.sendButton);U&&(j=U.micButton,Ie=U.micButtonWrapper,on.insertBefore(Ie,kt),j.addEventListener("click",Tt),j.disabled=D.isStreaming())}else{let U=(Il=n.voiceRecognition)!=null?Il:{},dt=(Pl=n.sendButton)!=null?Pl:{},Bt=(Wl=U.iconName)!=null?Wl:"mic",Je=(Rl=dt.size)!=null?Rl:"40px",mt=(Hl=U.iconSize)!=null?Hl:Je,Gt=parseFloat(mt)||24;j.style.width=mt,j.style.height=mt,j.style.minWidth=mt,j.style.minHeight=mt;let ln=(Dl=(Bl=U.iconColor)!=null?Bl:dt.textColor)!=null?Dl:"currentColor";j.innerHTML="";let Un=me(Bt,Gt,ln,2);Un?j.appendChild(Un):j.textContent="\u{1F3A4}";let mn=(Nl=U.backgroundColor)!=null?Nl:dt.backgroundColor;mn?j.style.backgroundColor=mn:j.style.backgroundColor="",ln?j.style.color=ln:j.style.color="var(--persona-text, #111827)",U.borderWidth?(j.style.borderWidth=U.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),U.borderColor?j.style.borderColor=U.borderColor:j.style.borderColor="",U.paddingX?(j.style.paddingLeft=U.paddingX,j.style.paddingRight=U.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),U.paddingY?(j.style.paddingTop=U.paddingY,j.style.paddingBottom=U.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let jt=Ie==null?void 0:Ie.querySelector(".persona-send-button-tooltip"),In=(Fl=U.tooltipText)!=null?Fl:"Start voice recognition";if(((Ol=U.showTooltip)!=null?Ol:!1)&&In)if(jt)jt.textContent=In,jt.style.display="";else{let Qt=document.createElement("div");Qt.className="persona-send-button-tooltip",Qt.textContent=In,Ie==null||Ie.insertBefore(Qt,j)}else jt&&(jt.style.display="none");Ie.style.display="",j.disabled=D.isStreaming()}else j&&Ie&&(Ie.style.display="none",((_l=($l=n.voiceRecognition)==null?void 0:$l.provider)==null?void 0:_l.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():kn&&qn());if(((jl=n.attachments)==null?void 0:jl.enabled)===!0)if(!gt||!ue){let U=(zl=n.attachments)!=null?zl:{},Bt=(Vl=((ql=n.sendButton)!=null?ql:{}).size)!=null?Vl:"40px";ne||(ne=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ne.style.display="none",lt.insertBefore(ne,Z)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=((Ul=U.allowedTypes)!=null?Ul:cr).join(","),Fe.multiple=((Jl=U.maxFiles)!=null?Jl:4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),lt.insertBefore(Fe,Z)),gt=h("div","persona-send-button-wrapper"),ue=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ue.type="button",ue.setAttribute("aria-label",(Yl=U.buttonTooltipText)!=null?Yl:"Attach file");let Je=(Gl=U.buttonIconName)!=null?Gl:"paperclip",mt=Bt,Gt=parseFloat(mt)||40,ln=Math.round(Gt*.6);ue.style.width=mt,ue.style.height=mt,ue.style.minWidth=mt,ue.style.minHeight=mt,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.style.backgroundColor="transparent",ue.style.color="var(--persona-primary, #111827)",ue.style.border="none",ue.style.borderRadius="6px",ue.style.transition="background-color 0.15s ease",ue.addEventListener("mouseenter",()=>{ue.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ue.addEventListener("mouseleave",()=>{ue.style.backgroundColor="transparent"});let Un=me(Je,ln,"currentColor",1.5);Un?ue.appendChild(Un):ue.textContent="\u{1F4CE}",ue.addEventListener("click",In=>{In.preventDefault(),Fe==null||Fe.click()}),gt.appendChild(ue);let mn=(Xl=U.buttonTooltipText)!=null?Xl:"Attach file",jt=h("div","persona-send-button-tooltip");jt.textContent=mn,gt.appendChild(jt),tn.append(gt),!We&&Fe&&ne&&(We=eo.fromConfig(U),We.setPreviewsContainer(ne),Fe.addEventListener("change",async()=>{We&&(Fe!=null&&Fe.files)&&(await We.handleFileSelect(Fe.files),Fe.value="")})),_.querySelector(".persona-attachment-drop-overlay")||_.appendChild(md(U.dropOverlay))}else{gt.style.display="";let U=(Kl=n.attachments)!=null?Kl:{};Fe&&(Fe.accept=((Zl=U.allowedTypes)!=null?Zl:cr).join(","),Fe.multiple=((Ql=U.maxFiles)!=null?Ql:4)>1),We&&We.updateConfig({allowedTypes:U.allowedTypes,maxFileSize:U.maxFileSize,maxFiles:U.maxFiles})}else gt&&(gt.style.display="none"),We&&We.clearAttachments(),(ec=_.querySelector(".persona-attachment-drop-overlay"))==null||ec.remove();let Ut=(tc=n.sendButton)!=null?tc:{},Zo=(nc=Ut.useIcon)!=null?nc:!1,vo=(rc=Ut.iconText)!=null?rc:"\u2191",bn=Ut.iconName,Dn=(oc=Ut.tooltipText)!=null?oc:"Send message",Yr=(sc=Ut.showTooltip)!=null?sc:!1,Co=(ac=Ut.size)!=null?ac:"40px",Qo=Ut.backgroundColor,Hr=Ut.textColor;if(Zo){if(te.style.width=Co,te.style.height=Co,te.style.minWidth=Co,te.style.minHeight=Co,te.style.fontSize="18px",te.style.lineHeight="1",te.innerHTML="",Hr?te.style.color=Hr:te.style.color="var(--persona-button-primary-fg, #ffffff)",bn){let U=parseFloat(Co)||24,dt=(Hr==null?void 0:Hr.trim())||"currentColor",Bt=me(bn,U,dt,2);Bt?te.appendChild(Bt):te.textContent=vo}else te.textContent=vo;te.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Qo?(te.style.backgroundColor=Qo,te.classList.remove("persona-bg-persona-primary")):(te.style.backgroundColor="",te.classList.add("persona-bg-persona-primary"))}else te.textContent=(lc=(ic=n.copy)==null?void 0:ic.sendButtonLabel)!=null?lc:"Send",te.style.width="",te.style.height="",te.style.minWidth="",te.style.minHeight="",te.style.fontSize="",te.style.lineHeight="",te.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",Qo?(te.style.backgroundColor=Qo,te.classList.remove("persona-bg-persona-accent")):te.classList.add("persona-bg-persona-accent"),Hr?te.style.color=Hr:te.classList.add("persona-text-white");Ut.borderWidth?(te.style.borderWidth=Ut.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),Ut.borderColor?te.style.borderColor=Ut.borderColor:te.style.borderColor="",Ut.paddingX?(te.style.paddingLeft=Ut.paddingX,te.style.paddingRight=Ut.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),Ut.paddingY?(te.style.paddingTop=Ut.paddingY,te.style.paddingBottom=Ut.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let wo=kt==null?void 0:kt.querySelector(".persona-send-button-tooltip");if(Yr&&Dn)if(wo)wo.textContent=Dn,wo.style.display="";else{let U=document.createElement("div");U.className="persona-send-button-tooltip",U.textContent=Dn,kt==null||kt.insertBefore(U,te)}else wo&&(wo.style.display="none");let es=(cc=n.layout)==null?void 0:cc.contentMaxWidth;es?(oe.style.maxWidth=es,oe.style.marginLeft="auto",oe.style.marginRight="auto",oe.style.width="100%",lt&&(lt.style.maxWidth=es,lt.style.marginLeft="auto",lt.style.marginRight="auto"),Oe&&(Oe.style.maxWidth=es,Oe.style.marginLeft="auto",Oe.style.marginRight="auto")):(oe.style.maxWidth="",oe.style.marginLeft="",oe.style.marginRight="",oe.style.width="",lt&&(lt.style.maxWidth="",lt.style.marginLeft="",lt.style.marginRight=""),Oe&&(Oe.style.maxWidth="",Oe.style.marginLeft="",Oe.style.marginRight=""));let vr=(dc=n.statusIndicator)!=null?dc:{},Yd=(pc=vr.visible)!=null?pc:!0;if(Nt.style.display=Yd?"":"none",D){let U=D.getStatus();Et(Nt,(Bt=>{var Je,mt,Gt,ln;return Bt==="idle"?(Je=vr.idleText)!=null?Je:cn.idle:Bt==="connecting"?(mt=vr.connectingText)!=null?mt:cn.connecting:Bt==="connected"?(Gt=vr.connectedText)!=null?Gt:cn.connected:Bt==="error"?(ln=vr.errorText)!=null?ln:cn.error:cn[Bt]})(U),vr,U)}Nt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Gd=vr.align==="left"?"persona-text-left":vr.align==="center"?"persona-text-center":"persona-text-right";Nt.classList.add(Gd)},open(){x&&Rt(!0,"api")},close(){x&&Rt(!1,"api")},toggle(){x&&Rt(!T,"api")},clearChat(){dn=!1,D.clearMessages(),Rn.clear(),yr();try{localStorage.removeItem(io),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${io}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==io)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},E.syncFromMetadata(),ae==null||ae.clear(),xe==null||xe.update()},setMessage(l){return!Z||D.isStreaming()?!1:(!T&&x&&Rt(!0,"system"),Z.value=l,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let m=(l==null?void 0:l.trim())||Z.value.trim();return m?(!T&&x&&Rt(!0,"system"),Z.value="",Z.style.height="auto",D.sendMessage(m),!0):!1},startVoiceRecognition(){var m,b;return D.isStreaming()?!1:((b=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype"?(D.isVoiceActive()||(!T&&x&&Rt(!0,"system"),Ze.manuallyDeactivated=!1,fn(),D.toggleVoice().then(()=>{Ze.active=D.isVoiceActive(),Hn("user"),D.isVoiceActive()&&xr()})),!0):kn?!0:xo()?(!T&&x&&Rt(!0,"system"),Ze.manuallyDeactivated=!1,fn(),Ir("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{Ze.active=!1,Ze.manuallyDeactivated=!0,fn(),Hn("user"),_e()}),!0):!1:kn?(Ze.manuallyDeactivated=!0,fn(),qn("user"),!0):!1},injectMessage(l){return!T&&x&&Rt(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!T&&x&&Rt(!0,"system");let m=D.injectAssistantMessage(l);return G&&(G=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),m},injectUserMessage(l){return!T&&x&&Rt(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!T&&x&&Rt(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!T&&x&&Rt(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!T&&x&&Rt(!0,"system"),D.injectTestEvent(l)},async connectStream(l,m){return D.connectStream(l,m)},__pushEventStreamEvent(l){ae&&ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!re||!ae||tr()},hideEventStream(){je&&On()},isEventStreamVisible(){return je},showArtifacts(){Fn(n)&&(dn=!1,An(),at==null||at.setMobileOpen(!0))},hideArtifacts(){Fn(n)&&(dn=!0,An())},upsertArtifact(l){return Fn(n)?(dn=!1,D.upsertArtifact(l)):null},selectArtifact(l){Fn(n)&&D.selectArtifact(l)},clearArtifacts(){Fn(n)&&D.clearArtifacts()},focusInput(){return x&&!T||!Z?!1:(Z.focus(),!0)},async resolveApproval(l,m){let A=D.getMessages().find(L=>{var R;return L.variant==="approval"&&((R=L.approval)==null?void 0:R.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(A.approval,m)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){g(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return x&&T},isVoiceActive(){return Ze.active},getState(){return{open:x&&T,launcherEnabled:x,voiceActive:Ze.active,streaming:D.isStreaming()}},showCSATFeedback(l){!T&&x&&Rt(!0,"system");let m=oe.querySelector(".persona-feedback-container");m&&m.remove();let b=da({onSubmit:async(A,L)=>{var R;D.isClientTokenMode()&&await D.submitCSATFeedback(A,L),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&x&&Rt(!0,"system");let m=oe.querySelector(".persona-feedback-container");m&&m.remove();let b=pa({onSubmit:async(A,L)=>{var R;D.isClientTokenMode()&&await D.submitNPSFeedback(A,L),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return D.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return D.submitNPSFeedback(l,m)},destroy(){vt.forEach(l=>l()),q.remove(),y==null||y.destroy(),se==null||se.remove(),Tn&&ce.removeEventListener("click",Tn)}};if((((si=t==null?void 0:t.debugTools)!=null?si:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:Jt,getMessages:Jt.getMessages,getStatus:Jt.getStatus,getMetadata:Jt.getPersistentMetadata,updateMetadata:Jt.updatePersistentMetadata,clearHistory:()=>Jt.clearChat(),setVoiceActive:b=>b?Jt.startVoiceRecognition():Jt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,vt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&Jt.focusInput()};if(window.addEventListener("persona:focusInput",m),vt.push(()=>{window.removeEventListener("persona:focusInput",m)}),re){let z=ge=>{let ve=ge.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&Jt.showEventStream()},O=ge=>{let ve=ge.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&Jt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),vt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let b=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&Jt.showArtifacts()},A=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&Jt.hideArtifacts()},L=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==l||O!=null&&O.artifact&&Jt.upsertArtifact(O.artifact)},R=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==l||typeof(O==null?void 0:O.id)=="string"&&Jt.selectArtifact(O.id)},B=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&Jt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",B),vt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",B)})}let Bn=Tu(n.persistState);if(Bn&&x){let l=Mu(Bn.storage),m=`${Bn.keyPrefix}widget-open`,b=`${Bn.keyPrefix}widget-voice`,A=`${Bn.keyPrefix}widget-voice-mode`;if(l){let L=((ai=Bn.persist)==null?void 0:ai.openState)&&l.getItem(m)==="true",R=((ii=Bn.persist)==null?void 0:ii.voiceState)&&l.getItem(b)==="true",B=((li=Bn.persist)==null?void 0:li.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{Jt.open(),setTimeout(()=>{var z;if(R||B)Jt.startVoiceRecognition();else if((z=Bn.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(ci=Bn.persist)!=null&&ci.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(di=Bn.persist)!=null&&di.voiceState&&(o.on("voice:state",z=>{l.setItem(b,z.active?"true":"false")}),o.on("user:message",z=>{l.setItem(A,z.viaVoice?"true":"false")})),Bn.clearOnChatClear){let z=()=>{l.removeItem(m),l.removeItem(b),l.removeItem(A)},O=()=>z();window.addEventListener("persona:clear-chat",O),vt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return c&&x&&setTimeout(()=>{Jt.open()},0),Jt};var ku=(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},gd=(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"},ya=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=""},fd=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",ya(e)},ga=e=>{e.style.transition=""},fa=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=""},ha=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},As=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Lu=(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))},Iu=(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)},hd=(e,r,t,n,s,o,a)=>{var v,E,x,C,k,H;let i=Jn(o),u=i.reveal==="push";Lu(e,r,t,n,u),Iu(e,r,t,n,i.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,d=(E=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?E:!0,p=(C=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileBreakpoint)!=null?C:640,g=c!=null?c.innerWidth<=p:!1;if(d&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),fa(r),ga(n),fd(n),ha(t),As(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((H=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?H:vn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),fd(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",fa(r),ga(n),ha(t),As(s,n);let w=i.animate?"transform 180ms ease":"none",M=i.side==="right"?"translateX(100%)":"translateX(-100%)",W=a?"translateX(0)":M;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=W,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",ga(n),ya(n),As(s,n);let w=ku(i.width,e.clientWidth),M=Math.max(0,e.clientWidth),W=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=`${M+w}px`,r.style.transition=W,r.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${M}px`,t.style.maxWidth=`${M}px`,t.style.minWidth=`${M}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="",fa(r),ya(n),ha(t),As(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let M=a?i.width:"0px",W=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 ${M}`,n.style.width=M,n.style.maxWidth=M,n.style.minWidth=M,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||T?"hidden":"visible",n.style.transition=W,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")}},Pu=(e,r)=>{let t=e.ownerDocument.createElement("div");return gd(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){gd(t,n)},destroy(){t.remove()}}},Wu=(e,r)=>{var k,H,w,M;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),u=t.createElement("div"),c=t.createElement("aside"),d=t.createElement("div"),p=(H=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)==null||H?(M=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?M:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),n.insertBefore(a,e),u.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},v=()=>{f(),Jn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{hd(a,i,u,c,d,r,p)}),g.observe(a))},E=()=>{hd(a,i,u,c,d,r,p),v()},x=a.ownerDocument.defaultView,C=()=>{E()};return x==null||x.addEventListener("resize",C),Jn(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),E(),{mode:"docked",host:d,shell:a,syncWidgetState(W){let T=W.launcherEnabled?W.open:!0;p!==T&&(p=T,E())},updateConfig(W){var T,G;r=W,((G=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)!=null?G:!0)===!1&&(p=!0),E()},destroy(){x==null||x.removeEventListener("resize",C),f(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Es=(e,r)=>en(r)?Wu(e,r):Pu(e,r);var ba={},Ru=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},Hu=()=>{try{if(typeof ba!="undefined"&&ba.url)return new URL("../widget.css",ba.url).href}catch{}return null},yd=(e,r)=>{let t=Hu(),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)}},bd=e=>{var x;let r=Ru(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Es(r,s),a,i=[],u=(C,k)=>{var W,T;let w=!((T=(W=k==null?void 0:k.launcher)==null?void 0:W.enabled)!=null?T:!0)||en(k),M=n.createElement("div");if(M.setAttribute("data-persona-root","true"),w&&(M.style.height="100%",M.style.display="flex",M.style.flexDirection="column",M.style.flex="1",M.style.minHeight="0"),t){let G=C.attachShadow({mode:"open"});G.appendChild(M),yd(G,n)}else C.appendChild(M),yd(C,n);return r.id&&M.setAttribute("data-persona-instance",r.id),M},c=()=>{o.syncWidgetState(a.getState())},d=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let C=u(o.host,s);a=ma(C,s,{debugTools:e.debugTools}),d()},g=()=>{i.forEach(C=>C()),i=[],a.destroy()};p(),(x=e.onReady)==null||x.call(e);let f=C=>{g(),o.destroy(),o=Es(r,C),s=C,p()},v={update(C){var M,W,T,G,K,J;let k={...s,...C,launcher:{...(M=s==null?void 0:s.launcher)!=null?M:{},...(W=C==null?void 0:C.launcher)!=null?W:{},dock:{...(G=(T=s==null?void 0:s.launcher)==null?void 0:T.dock)!=null?G:{},...(J=(K=C==null?void 0:C.launcher)==null?void 0:K.dock)!=null?J:{}}}},H=en(s),w=en(k);if(H!==w){f(k);return}s=k,o.updateConfig(s),a.update(C),c()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},E=new Proxy(v,{get(C,k,H){if(k==="host")return o.host;if(k in C)return Reflect.get(C,k,H);let w=a[k];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=E),E};var Sd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Bu=new Set(["button","a","input","select","textarea","details","summary"]),Du=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),xa=/\b(product|card|item|listing|result)\b/i,Ca=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Nu=3e3,Fu=100;function Ad(e){let r=typeof e.className=="string"?e.className:"";if(xa.test(r)||e.id&&xa.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&xa.test(n.value))return!0}return!1}function Ed(e){var r;return Ca.test(((r=e.textContent)!=null?r:"").trim())}function Td(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 Ou(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function xd(e){let r=e.match(Ca);return r?r[0]:null}function vd(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 $u(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 _u="commerce-card",ju="result-card";function Cd(e){return!Ad(e)||!Ed(e)||!Td(e)&&!Ou(e)?0:5200}function wd(e){var n;return!Ad(e)||Ed(e)||!Td(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 Md=[{id:_u,scoreElement(e){return Cd(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||Ca.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,d;if(Cd(e)===0)return null;let{title:t,href:n}=vd(e),s=(d=(c=xd(((u=e.textContent)!=null?u:"").trim()))!=null?c:xd(r.text))!=null?d:"",o=$u(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
100
+ `)}},{id:ju,scoreElement(e){return wd(e)},formatSummary(e,r){if(wd(e)===0)return null;let{title:t,href:n}=vd(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
101
+ `)}}];function zu(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function qu(e){var d,p,g,f,v,E,x,C,k,H,w,M,W;let r=(d=e.options)!=null?d:{},t=(g=(p=r.maxElements)!=null?p:e.maxElements)!=null?g:80,n=(v=(f=r.excludeSelector)!=null?f:e.excludeSelector)!=null?v:".persona-host",s=(x=(E=r.maxTextLength)!=null?E:e.maxTextLength)!=null?x:200,o=(k=(C=r.visibleOnly)!=null?C:e.visibleOnly)!=null?k:!0,a=(H=r.root)!=null?H:e.root,i=(w=r.mode)!=null?w:"structured",u=(M=r.maxCandidates)!=null?M:Math.max(500,t*10),c=(W=e.rules)!=null?W:Md;return i==="simple"&&e.rules&&e.rules.length>0?(zu(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:u,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function va(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Vu=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Uu(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"||Bu.has(r)||t&&Du.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function kd(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 Ju(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let u=e.getAttribute("role");u&&(r.role=u);for(let c=0;c<e.attributes.length;c++){let d=e.attributes[c];d.name.startsWith("data-")&&(r[d.name]=d.value)}return r}function Ld(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${va(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Vu){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${va(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=>va(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(i>=0){let u=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function Yu(e){return e==="static"?Fu:Nu}function Id(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:Ld(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:Uu(e),attributes:Ju(e)}}function Gu(e,r,t,n){let s=Yu(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 Xu(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 Ku(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,d=c.tagName.toLowerCase();if(Sd.has(d)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!kd(c)){i=a.nextNode();continue}let p=Id(c,e.maxTextLength),g=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(x=>x==="role");if(!g&&!f){i=a.nextNode();continue}if(n.has(p.selector)){i=a.nextNode();continue}n.add(p.selector);let{score:v,formattingRule:E}=Gu(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:v,formattingRule:E}),o+=1}i=a.nextNode()}s.sort((c,d)=>{let p=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return p!==g?p-g:d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex});let u=[];for(let c of s){if(u.length>=e.maxElements)break;Xu(u,c)||u.push(c)}return u.sort((c,d)=>{let p=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return p!==g?p-g:p===1&&d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex}),u.map(c=>{var g;let d;if((g=c.formattingRule)!=null&&g.formatSummary){let f=c.formattingRule.formatSummary(c.el,c.enriched,t);f&&(d=f)}let p={...c.enriched};return d&&(p.formattedSummary=d),p})}function Zu(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let u=o,c=u.tagName.toLowerCase();if(Sd.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!kd(u)){o=s.nextNode();continue}let d=Id(u,e.maxTextLength),p=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(f=>f==="role");if(!p&&!g){o=s.nextNode();continue}n.has(d.selector)||(n.add(d.selector),t.push(d))}o=s.nextNode()}let a=[],i=[];for(let u of t)u.interactivity!=="static"?a.push(u):i.push(u);return[...a,...i].slice(0,e.maxElements)}function Qu(e={}){var n;let r=qu(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?Zu(r,t):Ku(r,t):[]}var Ts=100;function em(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"structured",n=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
102
102
  ${a.map(i=>`- ${i.split(`
103
103
  `).join(`
104
104
  `)}`).join(`
105
- `)}`)}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,ws)}" (clickable)`);n.push(`Interactive elements:
105
+ `)}`)}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,Ts)}" (clickable)`);n.push(`Interactive elements:
106
106
  ${a.join(`
107
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,ws)}" (navigable)`);n.push(`Navigation links:
107
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Ts)}" (navigable)`);n.push(`Navigation links:
108
108
  ${a.join(`
109
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,ws)}" (input)`);n.push(`Form inputs:
109
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Ts)}" (input)`);n.push(`Form inputs:
110
110
  ${a.join(`
111
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,ws)}"`);n.push(`Content:
111
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Ts)}"`);n.push(`Content:
112
112
  ${a.join(`
113
113
  `)}`)}return n.join(`
114
114
 
115
- `)}var hd={name:"@runtypelabs/persona",version:"3.10.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 io=hd.version;function ir(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function _u(e){if(e)return{getHeaders:ir(e.getHeaders),onFeedback:ir(e.onFeedback),onCopy:ir(e.onCopy),requestMiddleware:ir(e.requestMiddleware),actionHandlers:ir(e.actionHandlers),actionParsers:ir(e.actionParsers),postprocessMessage:ir(e.postprocessMessage),contextProviders:ir(e.contextProviders),streamParser:ir(e.streamParser)}}var yd=`({ text, message }: any) => {
115
+ `)}var Pd={name:"@runtypelabs/persona",version:"3.10.1",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var lo=Pd.version;function dr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function nm(e){if(e)return{getHeaders:dr(e.getHeaders),onFeedback:dr(e.onFeedback),onCopy:dr(e.onCopy),requestMiddleware:dr(e.requestMiddleware),actionHandlers:dr(e.actionHandlers),actionParsers:dr(e.actionParsers),postprocessMessage:dr(e.postprocessMessage),contextProviders:dr(e.contextProviders),streamParser:dr(e.streamParser)}}var Wd=`({ text, message }: any) => {
116
116
  const jsonSource = (message as any).rawContent || text || message.content;
117
117
  if (!jsonSource || typeof jsonSource !== 'string') return null;
118
118
  let cleanJson = jsonSource
@@ -125,7 +125,7 @@ ${a.join(`
125
125
  if (parsed.action) return { type: parsed.action, payload: parsed };
126
126
  } catch (e) { return null; }
127
127
  return null;
128
- }`,bd=`function(ctx) {
128
+ }`,Rd=`function(ctx) {
129
129
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
130
130
  if (!jsonSource || typeof jsonSource !== 'string') return null;
131
131
  var cleanJson = jsonSource
@@ -138,7 +138,7 @@ ${a.join(`
138
138
  if (parsed.action) return { type: parsed.action, payload: parsed };
139
139
  } catch (e) { return null; }
140
140
  return null;
141
- }`,xd=`(action: any, context: any) => {
141
+ }`,Hd=`(action: any, context: any) => {
142
142
  if (action.type !== 'nav_then_click') return;
143
143
  const payload = action.payload || action.raw || {};
144
144
  const url = payload?.page;
@@ -155,7 +155,7 @@ ${a.join(`
155
155
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
156
156
  window.location.href = targetUrl;
157
157
  return { handled: true, displayText: text };
158
- }`,vd=`function(action, context) {
158
+ }`,Bd=`function(action, context) {
159
159
  if (action.type !== 'nav_then_click') return;
160
160
  var payload = action.payload || action.raw || {};
161
161
  var url = payload.page;
@@ -172,26 +172,26 @@ ${a.join(`
172
172
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
173
173
  window.location.href = targetUrl;
174
174
  return { handled: true, displayText: text };
175
- }`,ju=`(parsed: any) => {
175
+ }`,rm=`(parsed: any) => {
176
176
  if (!parsed || typeof parsed !== 'object') return null;
177
177
  if (parsed.action === 'nav_then_click') return 'Navigating...';
178
178
  if (parsed.action === 'message') return parsed.text || '';
179
179
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
180
180
  return parsed.text || null;
181
- }`,zu=`function(parsed) {
181
+ }`,om=`function(parsed) {
182
182
  if (!parsed || typeof parsed !== 'object') return null;
183
183
  if (parsed.action === 'nav_then_click') return 'Navigating...';
184
184
  if (parsed.action === 'message') return parsed.text || '';
185
185
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
186
186
  return parsed.text || null;
187
- }`;function qu(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 Ss(e){var r,t;return(t=(r=e.parserType)!=null?r:qu(e.streamParser))!=null?t:"plain"}function As(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 Es(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 Ts(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,u])=>{typeof u=="string"?t.push(`${r} ${i}: "${u}",`):typeof u=="boolean"&&t.push(`${r} ${i}: ${u},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([u])=>u!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?t.push(`${r} ${u}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${u}: ${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 xa(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 Cd(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}: {`),Cd(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function wr(e,r,t,n){t&&(e.push(`${n}${r}: {`),Cd(e,t,`${n} `),e.push(`${n}},`))}function Uu(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:_u(t.hooks)}:void 0;return r==="esm"?Vu(n,s):r==="script-installer"?Gu(n):r==="script-advanced"?Ku(n,s):r==="react-component"?Ju(n,s):r==="react-advanced"?Yu(n,s):Xu(n,s)}function Vu(e,r){let t=r==null?void 0:r.hooks,n=Ss(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&&wr(o,"theme",e.theme," "),e.launcher&&wr(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(...As(e," ")),o.push(...Es(e," ",t)),o.push(...Ts(e," ")),o.push(...Ms(e," ")),o.push(...xa(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(`
188
- `)}function Ju(e,r){let t=r==null?void 0:r.hooks,n=Ss(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&&wr(o,"theme",e.theme," "),e.launcher&&wr(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(...As(e," ")),o.push(...Es(e," ",t)),o.push(...Ts(e," ")),o.push(...Ms(e," ")),o.push(...xa(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(`
189
- `)}function Yu(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&&wr(n,"theme",e.theme," "),e.launcher&&wr(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(...As(e," ")),n.push(...Es(e," ",t)),n.push(...Ts(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(${ju}),`)),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(` ${yd}`),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(` ${yd}`),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(` ${xd}`),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(` ${xd}`),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(`
190
- `)}function wd(e){var s;let r=Ss(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,u])=>{i!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,u])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof u=="object"&&u!==null)a.avatar=u;else if(i==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([d,p])=>{d!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[d]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Gu(e){let r=wd(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${io}/dist/install.global.js" data-config='${t}'></script>`}function Xu(e,r){let t=r==null?void 0:r.hooks,n=Ss(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${io}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${io}/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&&wr(o,"theme",e.theme," "),e.launcher&&wr(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(...As(e," ")),o.push(...Es(e," ",t)),o.push(...Ts(e," ")),o.push(...Ms(e," ")),o.push(...xa(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(`
191
- `)}function Ku(e,r){let t=r==null?void 0:r.hooks,n=wd(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
187
+ }`;function sm(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:sm(e.streamParser))!=null?t:"plain"}function ks(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 Ls(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 Is(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 Ps(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,u])=>{typeof u=="string"?t.push(`${r} ${i}: "${u}",`):typeof u=="boolean"&&t.push(`${r} ${i}: ${u},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([u])=>u!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?t.push(`${r} ${u}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${u}: ${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 wa(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 Dd(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}: {`),Dd(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Er(e,r,t,n){t&&(e.push(`${n}${r}: {`),Dd(e,t,`${n} `),e.push(`${n}},`))}function am(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:nm(t.hooks)}:void 0;return r==="esm"?im(n,s):r==="script-installer"?dm(n):r==="script-advanced"?um(n,s):r==="react-component"?lm(n,s):r==="react-advanced"?cm(n,s):pm(n,s)}function im(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&&Er(o,"theme",e.theme," "),e.launcher&&Er(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(...ks(e," ")),o.push(...Ls(e," ",t)),o.push(...Is(e," ")),o.push(...Ps(e," ")),o.push(...wa(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(`
188
+ `)}function lm(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&&Er(o,"theme",e.theme," "),e.launcher&&Er(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(...ks(e," ")),o.push(...Ls(e," ",t)),o.push(...Is(e," ")),o.push(...Ps(e," ")),o.push(...wa(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(`
189
+ `)}function cm(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&&Er(n,"theme",e.theme," "),e.launcher&&Er(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(...ks(e," ")),n.push(...Ls(e," ",t)),n.push(...Is(e," ")),n.push(...Ps(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(${rm}),`)),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(` ${Wd}`),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(` ${Wd}`),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(` ${Hd}`),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(` ${Hd}`),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(`
190
+ `)}function Nd(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,u])=>{i!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,u])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof u=="object"&&u!==null)a.avatar=u;else if(i==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([d,p])=>{d!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[d]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function dm(e){let r=Nd(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${lo}/dist/install.global.js" data-config='${t}'></script>`}function pm(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@${lo}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${lo}/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&&Er(o,"theme",e.theme," "),e.launcher&&Er(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(...ks(e," ")),o.push(...Ls(e," ",t)),o.push(...Is(e," ")),o.push(...Ps(e," ")),o.push(...wa(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(`
191
+ `)}function um(e,r){let t=r==null?void 0:r.hooks,n=Nd(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
192
192
  `).map((a,i)=>i===0?a:" "+a).join(`
193
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${io}/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(${zu});`),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(` ${bd}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${bd}`),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(` ${vd}`),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(` ${vd}`),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(`
194
- `)}var Sd={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Ad=.1,Ed=.15,Td=1.5,va=24,Md=40,Zu=`
193
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${lo}/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(${om});`),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(` ${Rd}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Rd}`),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(` ${Bd}`),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(` ${Bd}`),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(`
194
+ `)}var Fd={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Od=.1,$d=.15,_d=1.5,Sa=24,jd=40,mm=`
195
195
  /* \u2500\u2500 Root \u2500\u2500 */
196
196
  .persona-dc-root {
197
197
  display: flex;
@@ -342,7 +342,7 @@ ${a.join(`
342
342
  .persona-dc-stage {
343
343
  height: 550px;
344
344
  min-height: 400px;
345
- padding: ${va}px;
345
+ padding: ${Sa}px;
346
346
  overflow: auto;
347
347
  background: #f0f1f3;
348
348
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -432,5 +432,5 @@ ${a.join(`
432
432
  min-height: 300px;
433
433
  }
434
434
  }
435
- `;function Qu(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Zu,document.head.appendChild(e)}function eg(e,r){let t=e.clientWidth-va*2-Md,n=e.clientHeight-va*2-Md;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function tg(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 ng(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Qu();let d=Math.max(0,Math.min(n,t.length-1)),p=s,m=o,f=null,v=1,A=!1,x=h("div","persona-dc-root"),C=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),R=h("div","persona-dc-toolbar-trail"),w=Bt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>lt(-1)}),M=h("div");M.style.position="relative";let W=h("button","persona-dc-title-btn");W.type="button",W.setAttribute("aria-expanded","false"),W.setAttribute("aria-haspopup","listbox");let E=h("span","persona-dc-title-text"),G=h("span","persona-dc-title-chevron"),K=ge("chevron-down",12,"currentColor",2);K&&G.appendChild(K),W.append(E,G);let J=h("div","persona-dc-dropdown");J.setAttribute("role","listbox"),J.style.display="none";let L=!1;function Q(){J.innerHTML="";for(let j=0;j<t.length;j++){let U=t[j],re=h("button","persona-dc-dropdown-item");re.type="button",re.setAttribute("role","option"),re.setAttribute("aria-current",j===d?"true":"false");let _e=h("span");if(_e.textContent=U.title,re.appendChild(_e),U.description){let Z=h("span","persona-dc-dropdown-desc");Z.textContent=U.description,re.appendChild(Z)}re.addEventListener("click",()=>{ne(),Tt(j)}),J.appendChild(re)}}function we(){L=!L,J.style.display=L?"":"none",W.setAttribute("aria-expanded",L?"true":"false"),L&&Q()}function ne(){L&&(L=!1,J.style.display="none",W.setAttribute("aria-expanded","false"))}W.addEventListener("click",j=>{j.stopPropagation(),we()});let Ee=()=>ne();document.addEventListener("click",Ee),M.append(W,J);let Oe=Bt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>lt(1)}),fe=h("span","persona-dc-counter");k.append(w,M,Oe,fe);let Ie=null;i&&(Ie=ms({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:j=>{p=j,ce.dataset.device=p,f=null,q()}}),R.appendChild(Ie.element));let Pe=null;if(a){let j=h("div","persona-dc-zoom-controls"),U=Bt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Z=f!=null?f:v;f=Math.max(Ed,Z-Ad),q()}});Pe=h("span","persona-dc-zoom-level"),Pe.title="Reset to 100%",Pe.style.cursor="pointer",Pe.addEventListener("click",()=>{f=1,q()});let re=Bt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Z=f!=null?f:v;f=Math.min(Td,Z+Ad),q()}}),_e=Bt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,q()}});j.append(U,Pe,re,_e),R.appendChild(j)}if(u){let j=h("div","persona-dc-separator");R.appendChild(j);let U=ms({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:m,onSelect:re=>{m=re,ce.dataset.colorScheme=m,Te()}});R.appendChild(U.element)}let se=h("div","persona-dc-separator");R.appendChild(se);let be=Bt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[d].url,"_blank")}});R.appendChild(be),C.append(k,R);let ze=h("div","persona-dc-stage"),ce=h("div","persona-dc-iframe-wrapper");ce.dataset.device=p,ce.dataset.colorScheme=m;let ae=h("iframe","persona-dc-iframe");ae.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ae.setAttribute("loading","lazy"),ae.title=t[d].title,ce.appendChild(ae),ze.appendChild(ce),x.append(C,ze),e.appendChild(x);function Te(){var j;try{let U=(j=ae.contentDocument)==null?void 0:j.body;if(!U)return;m==="dark"?U.classList.add("theme-dark"):U.classList.remove("theme-dark")}catch{}}ae.addEventListener("load",()=>Te());function Ne(){let j=t[d];E.textContent=j.title,fe.textContent=`${d+1} / ${t.length}`,ae.title=j.title}function lt(j){let U=((d+j)%t.length+t.length)%t.length;Tt(U)}function Tt(j){j<0||j>=t.length||(d=j,ae.src=t[d].url,Ne(),c==null||c(d,t[d]))}function q(){var re;if(A)return;let j=(re=Sd[p])!=null?re:Sd.desktop;v=eg(ze,j);let U=Math.max(Ed,Math.min(Td,f!=null?f:v));tg(ce,ae,j,U,p),Pe&&(Pe.textContent=`${Math.round(U*100)}%`)}let F=new ResizeObserver(()=>q());F.observe(ze),Ne(),ae.src=t[d].url,requestAnimationFrame(()=>q());function ie(){A||(A=!0,F.disconnect(),document.removeEventListener("click",Ee),x.remove())}return{element:x,goTo:Tt,next:()=>lt(1),prev:()=>lt(-1),getIndex:()=>d,setDevice(j){p=j,ce.dataset.device=j,Ie==null||Ie.setSelected(j),f=null,q()},setColorScheme(j){m=j,ce.dataset.colorScheme=j},setZoom(j){f=j,q()},destroy:ie}}function rg(){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 og(){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 sg(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:Zn(e.colors.primary,.95),100:Zn(e.colors.primary,.9),200:Zn(e.colors.primary,.8),300:Zn(e.colors.primary,.7),400:Zn(e.colors.primary,.6),500:e.colors.primary,600:Zn(e.colors.primary,.8),700:Zn(e.colors.primary,.7),800:Zn(e.colors.primary,.6),900:Zn(e.colors.primary,.5),950:Zn(e.colors.primary,.45)}}),{...r,palette:t}}}}function ag(){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 ig(){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 Zn(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 lg(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var cg={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"}}},kd={components:{panel:{borderRadius:"0",shadow:"none"}}},Ld={id:"shop",label:"Shopping Assistant",config:{theme:cg,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Bn},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?"]}},Id={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:kd}},Pd={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:kd}},Wd={shop:Ld,minimal:Id,fullscreen:Pd};function dg(e){return Wd[e]}var ay=rd;export{Xr as AgentWidgetClient,Mo as AgentWidgetSession,Qr as AttachmentManager,yc as DEFAULT_COMPONENTS,Os as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Bn as DEFAULT_FLOATING_LAUNCHER_WIDTH,fc as DEFAULT_PALETTE,hc as DEFAULT_SEMANTIC,Lt as DEFAULT_WIDGET_CONFIG,Wd as PRESETS,Pd as PRESET_FULLSCREEN,Id as PRESET_MINIMAL,Ld as PRESET_SHOP,up as THEME_ZONES,io as VERSION,rg as accessibilityPlugin,og as animationsPlugin,Dr as applyThemeVariables,eo as attachHeaderToContainer,sg as brandPlugin,Do as buildComposer,kc as buildDefaultHeader,vr as buildHeader,Bo as buildHeaderWithLayout,Lc as buildMinimalHeader,Fu as collectEnrichedPageContext,Cr as componentRegistry,xs as createActionManager,da as createAgentExperience,Fs as createBestAvailableVoiceProvider,Mp as createBubbleWithLayout,ia as createCSATFeedback,Vs as createComboButton,au as createComponentMiddleware,ra as createComponentStreamParser,nc as createDefaultSanitizer,ng as createDemoCarousel,Fd as createDirectivePostprocessor,Nr as createDropdownMenu,Vd as createFlexibleJsonStreamParser,Bt as createIconButton,tp as createImagePart,Rs as createJsonStreamParser,gs as createLabelButton,na as createLocalStorageAdapter,Qo as createMarkdownProcessor,Yr as createMarkdownProcessorFromConfig,Bc as createMessageActions,la as createNPSFeedback,Ps as createPlainTextParser,lg as createPlugin,Ws as createRegexJsonParser,No as createStandardBubble,Ns as createTextPart,Io as createTheme,zs as createThemeObserver,ms as createToggleGroup,to as createTypingIndicator,Zr as createVoiceProvider,Cs as createWidgetHostLayout,Hs as createXmlParser,ay as default,so as defaultActionHandlers,bs as defaultJsonActionParser,ud as defaultParseRules,is as detectColorScheme,Od as directivePostprocessor,So as escapeHtml,aa as extractComponentDirectiveFromMessage,np as fileToImagePart,Ou as formatEnrichedContext,Kr as generateAssistantMessageId,Uu as generateCodeSnippet,Xd as generateMessageId,md as generateStableSelector,Eo as generateUserMessageId,ls as getActiveTheme,Cc as getColorScheme,Zd as getDisplayText,Ic as getHeaderLayout,ep as getImageParts,dg as getPreset,sa as hasComponentDirective,Qd as hasImages,Js as headerLayouts,ig as highContrastPlugin,rd as initAgentWidget,su as isComponentDirectiveType,Zt as isDockedMountMode,ss as isVoiceSupported,Ql as markdownPostprocessor,$s as mergeWithDefaults,Kd as normalizeContent,ys as pluginRegistry,ag as reducedMotionPlugin,oa as renderComponentDirective,Hc as renderLoadingIndicatorWithFallback,Un as resolveDockConfig,Ao as resolveSanitizer,_s as resolveTokens,js as themeToCssVariables,rp as validateImageFile,bc as validateTheme};
435
+ `;function gm(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=mm,document.head.appendChild(e)}function fm(e,r){let t=e.clientWidth-Sa*2-jd,n=e.clientHeight-Sa*2-jd;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function hm(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 ym(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");gm();let d=Math.max(0,Math.min(n,t.length-1)),p=s,g=o,f=null,v=1,E=!1,x=h("div","persona-dc-root"),C=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),H=h("div","persona-dc-toolbar-trail"),w=Dt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>it(-1)}),M=h("div");M.style.position="relative";let W=h("button","persona-dc-title-btn");W.type="button",W.setAttribute("aria-expanded","false"),W.setAttribute("aria-haspopup","listbox");let T=h("span","persona-dc-title-text"),G=h("span","persona-dc-title-chevron"),K=me("chevron-down",12,"currentColor",2);K&&G.appendChild(K),W.append(T,G);let J=h("div","persona-dc-dropdown");J.setAttribute("role","listbox"),J.style.display="none";let I=!1;function Q(){J.innerHTML="";for(let _=0;_<t.length;_++){let V=t[_],oe=h("button","persona-dc-dropdown-item");oe.type="button",oe.setAttribute("role","option"),oe.setAttribute("aria-current",_===d?"true":"false");let Oe=h("span");if(Oe.textContent=V.title,oe.appendChild(Oe),V.description){let Z=h("span","persona-dc-dropdown-desc");Z.textContent=V.description,oe.appendChild(Z)}oe.addEventListener("click",()=>{re(),Et(_)}),J.appendChild(oe)}}function Ce(){I=!I,J.style.display=I?"":"none",W.setAttribute("aria-expanded",I?"true":"false"),I&&Q()}function re(){I&&(I=!1,J.style.display="none",W.setAttribute("aria-expanded","false"))}W.addEventListener("click",_=>{_.stopPropagation(),Ce()});let Ae=()=>re();document.addEventListener("click",Ae),M.append(W,J);let Ne=Dt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>it(1)}),he=h("span","persona-dc-counter");k.append(w,M,Ne,he);let ke=null;i&&(ke=ys({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:_=>{p=_,de.dataset.device=p,f=null,q()}}),H.appendChild(ke.element));let Le=null;if(a){let _=h("div","persona-dc-zoom-controls"),V=Dt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Z=f!=null?f:v;f=Math.max($d,Z-Od),q()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{f=1,q()});let oe=Dt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Z=f!=null?f:v;f=Math.min(_d,Z+Od),q()}}),Oe=Dt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,q()}});_.append(V,Le,oe,Oe),H.appendChild(_)}if(u){let _=h("div","persona-dc-separator");H.appendChild(_);let V=ys({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:oe=>{g=oe,de.dataset.colorScheme=g,Ee()}});H.appendChild(V.element)}let ae=h("div","persona-dc-separator");H.appendChild(ae);let xe=Dt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[d].url,"_blank")}});H.appendChild(xe),C.append(k,H);let je=h("div","persona-dc-stage"),de=h("div","persona-dc-iframe-wrapper");de.dataset.device=p,de.dataset.colorScheme=g;let ie=h("iframe","persona-dc-iframe");ie.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ie.setAttribute("loading","lazy"),ie.title=t[d].title,de.appendChild(ie),je.appendChild(de),x.append(C,je),e.appendChild(x);function Ee(){var _;try{let V=(_=ie.contentDocument)==null?void 0:_.body;if(!V)return;g==="dark"?V.classList.add("theme-dark"):V.classList.remove("theme-dark")}catch{}}ie.addEventListener("load",()=>Ee());function Be(){let _=t[d];T.textContent=_.title,he.textContent=`${d+1} / ${t.length}`,ie.title=_.title}function it(_){let V=((d+_)%t.length+t.length)%t.length;Et(V)}function Et(_){_<0||_>=t.length||(d=_,ie.src=t[d].url,Be(),c==null||c(d,t[d]))}function q(){var oe;if(E)return;let _=(oe=Fd[p])!=null?oe:Fd.desktop;v=fm(je,_);let V=Math.max($d,Math.min(_d,f!=null?f:v));hm(de,ie,_,V,p),Le&&(Le.textContent=`${Math.round(V*100)}%`)}let F=new ResizeObserver(()=>q());F.observe(je),Be(),ie.src=t[d].url,requestAnimationFrame(()=>q());function le(){E||(E=!0,F.disconnect(),document.removeEventListener("click",Ae),x.remove())}return{element:x,goTo:Et,next:()=>it(1),prev:()=>it(-1),getIndex:()=>d,setDevice(_){p=_,de.dataset.device=_,ke==null||ke.setSelected(_),f=null,q()},setColorScheme(_){g=_,de.dataset.colorScheme=_},setZoom(_){f=_,q()},destroy:le}}function bm(){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 xm(){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 vm(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:er(e.colors.primary,.95),100:er(e.colors.primary,.9),200:er(e.colors.primary,.8),300:er(e.colors.primary,.7),400:er(e.colors.primary,.6),500:e.colors.primary,600:er(e.colors.primary,.8),700:er(e.colors.primary,.7),800:er(e.colors.primary,.6),900:er(e.colors.primary,.5),950:er(e.colors.primary,.45)}}),{...r,palette:t}}}}function Cm(){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 wm(){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 er(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 Sm(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Am={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},zd={components:{panel:{borderRadius:"0",shadow:"none"}}},qd={id:"shop",label:"Shopping Assistant",config:{theme:Am,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Nn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Vd={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:zd}},Ud={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:zd}},Jd={shop:qd,minimal:Vd,fullscreen:Ud};function Em(e){return Jd[e]}var wy=bd;export{Kr as AgentWidgetClient,Lo as AgentWidgetSession,eo as AttachmentManager,Pc as DEFAULT_COMPONENTS,js as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Nn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Lc as DEFAULT_PALETTE,Ic as DEFAULT_SEMANTIC,It as DEFAULT_WIDGET_CONFIG,Jd as PRESETS,Ud as PRESET_FULLSCREEN,Vd as PRESET_MINIMAL,qd as PRESET_SHOP,Mp as THEME_ZONES,lo as VERSION,bm as accessibilityPlugin,xm as animationsPlugin,Or as applyThemeVariables,to as attachHeaderToContainer,vm as brandPlugin,Fo as buildComposer,jc as buildDefaultHeader,Sr as buildHeader,No as buildHeaderWithLayout,zc as buildMinimalHeader,Qu as collectEnrichedPageContext,Ar as componentRegistry,ws as createActionManager,ma as createAgentExperience,_s as createBestAvailableVoiceProvider,jp as createBubbleWithLayout,da as createCSATFeedback,Gs as createComboButton,Cu as createComponentMiddleware,aa as createComponentStreamParser,hc as createDefaultSanitizer,ym as createDemoCarousel,Qd as createDirectivePostprocessor,$r as createDropdownMenu,ip as createFlexibleJsonStreamParser,Dt as createIconButton,hp as createImagePart,Ns as createJsonStreamParser,hs as createLabelButton,sa as createLocalStorageAdapter,ts as createMarkdownProcessor,Gr as createMarkdownProcessorFromConfig,Gc as createMessageActions,pa as createNPSFeedback,Bs as createPlainTextParser,Sm as createPlugin,Ds as createRegexJsonParser,Oo as createStandardBubble,os as createTextPart,Wo as createTheme,Us as createThemeObserver,ys as createToggleGroup,no as createTypingIndicator,Qr as createVoiceProvider,Es as createWidgetHostLayout,Fs as createXmlParser,wy as default,ao as defaultActionHandlers,Cs as defaultJsonActionParser,Md as defaultParseRules,ds as detectColorScheme,ep as directivePostprocessor,Eo as escapeHtml,ca as extractComponentDirectiveFromMessage,yp as fileToImagePart,em as formatEnrichedContext,Zr as generateAssistantMessageId,am as generateCodeSnippet,pp as generateMessageId,Ld as generateStableSelector,Mo as generateUserMessageId,ps as getActiveTheme,Bc as getColorScheme,mp as getDisplayText,qc as getHeaderLayout,fp as getImageParts,Em as getPreset,la as hasComponentDirective,gp as hasImages,Xs as headerLayouts,wm as highContrastPlugin,bd as initAgentWidget,vu as isComponentDirectiveType,en as isDockedMountMode,ls as isVoiceSupported,mc as markdownPostprocessor,zs as mergeWithDefaults,up as normalizeContent,vs as pluginRegistry,Cm as reducedMotionPlugin,ia as renderComponentDirective,Yc as renderLoadingIndicatorWithFallback,Jn as resolveDockConfig,To as resolveSanitizer,qs as resolveTokens,Vs as themeToCssVariables,bp as validateImageFile,Wc as validateTheme};
436
436
  //# sourceMappingURL=index.js.map