vanilla-agent 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import{marked as eo}from"marked";eo.setOptions({breaks:!0});var to=n=>eo.parse(n),wn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ao=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Qs=n=>`%%FORM_PLACEHOLDER_${n}%%`,To=(n,e)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Qs(e.length);return e.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=Qs(e.length);return e.push({token:s,type:o}),s}),r},Eo=n=>{let e=[],r=To(n,e),t=to(r);return e.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="tvw-form-directive" data-tv-form="${Ao(s)}"></div>`;t=t.replace(i,u)}),t};import{parse as no,STR as so,OBJ as oo}from"partial-json";var ln=n=>n.replace(/\\n/g,`
2
2
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),yn=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},Wo=n=>{var i,l;let e=(i=n.completedAt)!=null?i:Date.now(),r=(l=n.startedAt)!=null?l:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},ro=n=>n.status==="complete"?Wo(n):n.status==="pending"?"Waiting":"",Mo=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var io=n=>n.status==="complete"?Mo(n):"Using tool...",Lo=()=>{let n=null,e=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=t.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},dn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},vn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},bn=()=>{var e;let n=Lo();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},xn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=no(r,so|oo);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?ln(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=ln(o.text)))}catch{}return e=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Bo=n=>{let e=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?ln(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?ln(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let l=no(s,so|oo),u=o(l);u!==null&&(e=u)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Cn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Ho="https://api.travrse.ai/v1/dispatch";function ko(n){switch(n){case"json":return xn;case"regex-json":return bn;case"xml":return Cn;case"plain":default:return vn}}var qt=class{constructor(e={}){this.config=e;var r,t,o;this.apiUrl=(r=e.apiUrl)!=null?r:Ho,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:ko(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}async dispatch(e,r){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(l){let u=l instanceof Error?l:new Error(String(l));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:l}),l}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(o=>({role:o.role,content:o.rawContent||o.content,createdAt:o.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(e,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=u,o(u),u};if(i.text!==void 0){let u=l();u.content+=i.text,o(u)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r){var ne,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke,We,je,K,Se,Le,Ue,tt,xt,Mt,pt,Ct,de,$t,Lt,ve,wt,St,Bt,yt,Et,sn,on,rn,mn,Pt,Ot,nt,jt,Yt,Jt,Kt;let t=e.getReader(),o=new TextDecoder,s="",i=Date.now(),l=0,u=()=>i+l++,h=y=>{let X=y.reasoning?{...y.reasoning,chunks:[...y.reasoning.chunks]}:void 0,se=y.toolCall?{...y.toolCall,chunks:y.toolCall.chunks?[...y.toolCall.chunks]:void 0}:void 0,fe=y.tools?y.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...y,reasoning:X,toolCall:se,tools:fe}},d=y=>{r({type:"message",message:h(y)})},T=null,f={current:null},b=new Map,w=new Map,_={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},m=y=>{if(y==null)return null;try{return String(y)}catch{return null}},C=y=>{var X,se,fe,Re,Ie;return m((Ie=(Re=(fe=(se=(X=y.stepId)!=null?X:y.step_id)!=null?se:y.step)!=null?fe:y.parentId)!=null?Re:y.flowStepId)!=null?Ie:y.flow_step_id)},$=y=>{var X,se,fe,Re,Ie,ce,L;return m((L=(ce=(Ie=(Re=(fe=(se=(X=y.callId)!=null?X:y.call_id)!=null?se:y.requestId)!=null?fe:y.request_id)!=null?Re:y.toolCallId)!=null?Ie:y.tool_call_id)!=null?ce:y.stepId)!=null?L:y.step_id)},S=()=>T||(T={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},d(T),T),Y=(y,X)=>{_.lastId=X,y&&_.byStep.set(y,X)},I=(y,X)=>{var Ie;let se=(Ie=y.reasoningId)!=null?Ie:y.id,fe=C(y);if(se){let ce=String(se);return Y(fe,ce),ce}if(fe){let ce=_.byStep.get(fe);if(ce)return _.lastId=ce,ce}if(_.lastId&&!X)return _.lastId;if(!X)return null;let Re=`reason-${u()}`;return Y(fe,Re),Re},V=y=>{let X=b.get(y);if(X)return X;let se={id:`reason-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:y,status:"streaming",chunks:[]}};return b.set(y,se),d(se),se},te=(y,X)=>{j.lastId=X,y&&j.byCall.set(y,X)},A=(y,X)=>{var Ie;let se=(Ie=y.toolId)!=null?Ie:y.id,fe=$(y);if(se){let ce=String(se);return te(fe,ce),ce}if(fe){let ce=j.byCall.get(fe);if(ce)return j.lastId=ce,ce}if(j.lastId&&!X)return j.lastId;if(!X)return null;let Re=`tool-${u()}`;return te(fe,Re),Re},ie=y=>{let X=w.get(y);if(X)return X;let se={id:`tool-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:y,status:"pending"}};return w.set(y,se),d(se),se},J=y=>{if(typeof y=="number"&&Number.isFinite(y))return y;if(typeof y=="string"){let X=Number(y);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let se=Date.parse(y);if(!Number.isNaN(se))return se}return Date.now()},z=y=>{if(typeof y=="string")return y;if(y==null)return"";try{return JSON.stringify(y)}catch{return String(y)}},G=new Map,le=new Map;for(;;){let{done:y,value:X}=await t.read();if(y)break;s+=o.decode(X,{stream:!0});let se=s.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},dn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},vn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},bn=()=>{var e;let n=Lo();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},xn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=no(r,so|oo);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?ln(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=ln(o.text)))}catch{}return e=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Bo=n=>{let e=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?ln(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?ln(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let l=no(s,so|oo),u=o(l);u!==null&&(e=u)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Cn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Ho="https://api.travrse.ai/v1/dispatch";function ko(n){switch(n){case"json":return xn;case"regex-json":return bn;case"xml":return Cn;case"plain":default:return vn}}var qt=class{constructor(e={}){this.config=e;var r,t,o;this.apiUrl=(r=e.apiUrl)!=null?r:Ho,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:ko(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}async dispatch(e,r){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(l){let u=l instanceof Error?l:new Error(String(l));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:l}),l}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(o=>({role:o.role,content:o.rawContent||o.content,createdAt:o.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(e,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=u,o(u),u};if(i.text!==void 0){let u=l();u.content+=i.text,o(u)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r){var se,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke,We,je,K,Se,Le,Ue,tt,xt,Mt,pt,Ct,de,$t,Lt,ve,wt,St,Bt,yt,Et,sn,on,rn,mn,Pt,Ot,nt,jt,Yt,Jt,Kt;let t=e.getReader(),o=new TextDecoder,s="",i=Date.now(),l=0,u=()=>i+l++,h=y=>{let X=y.reasoning?{...y.reasoning,chunks:[...y.reasoning.chunks]}:void 0,ne=y.toolCall?{...y.toolCall,chunks:y.toolCall.chunks?[...y.toolCall.chunks]:void 0}:void 0,fe=y.tools?y.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...y,reasoning:X,toolCall:ne,tools:fe}},d=y=>{r({type:"message",message:h(y)})},T=null,f={current:null},b=new Map,w=new Map,_={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},m=y=>{if(y==null)return null;try{return String(y)}catch{return null}},C=y=>{var X,ne,fe,Re,Ie;return m((Ie=(Re=(fe=(ne=(X=y.stepId)!=null?X:y.step_id)!=null?ne:y.step)!=null?fe:y.parentId)!=null?Re:y.flowStepId)!=null?Ie:y.flow_step_id)},$=y=>{var X,ne,fe,Re,Ie,ce,L;return m((L=(ce=(Ie=(Re=(fe=(ne=(X=y.callId)!=null?X:y.call_id)!=null?ne:y.requestId)!=null?fe:y.request_id)!=null?Re:y.toolCallId)!=null?Ie:y.tool_call_id)!=null?ce:y.stepId)!=null?L:y.step_id)},S=()=>T||(T={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},d(T),T),Y=(y,X)=>{_.lastId=X,y&&_.byStep.set(y,X)},I=(y,X)=>{var Ie;let ne=(Ie=y.reasoningId)!=null?Ie:y.id,fe=C(y);if(ne){let ce=String(ne);return Y(fe,ce),ce}if(fe){let ce=_.byStep.get(fe);if(ce)return _.lastId=ce,ce}if(_.lastId&&!X)return _.lastId;if(!X)return null;let Re=`reason-${u()}`;return Y(fe,Re),Re},V=y=>{let X=b.get(y);if(X)return X;let ne={id:`reason-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:y,status:"streaming",chunks:[]}};return b.set(y,ne),d(ne),ne},te=(y,X)=>{j.lastId=X,y&&j.byCall.set(y,X)},A=(y,X)=>{var Ie;let ne=(Ie=y.toolId)!=null?Ie:y.id,fe=$(y);if(ne){let ce=String(ne);return te(fe,ce),ce}if(fe){let ce=j.byCall.get(fe);if(ce)return j.lastId=ce,ce}if(j.lastId&&!X)return j.lastId;if(!X)return null;let Re=`tool-${u()}`;return te(fe,Re),Re},ie=y=>{let X=w.get(y);if(X)return X;let ne={id:`tool-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:y,status:"pending"}};return w.set(y,ne),d(ne),ne},J=y=>{if(typeof y=="number"&&Number.isFinite(y))return y;if(typeof y=="string"){let X=Number(y);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let ne=Date.parse(y);if(!Number.isNaN(ne))return ne}return Date.now()},z=y=>{if(typeof y=="string")return y;if(y==null)return"";try{return JSON.stringify(y)}catch{return String(y)}},G=new Map,le=new Map;for(;;){let{done:y,value:X}=await t.read();if(y)break;s+=o.decode(X,{stream:!0});let ne=s.split(`
5
5
 
6
- `);s=(ne=se.pop())!=null?ne:"";for(let fe of se){let Re=fe.split(`
6
+ `);s=(se=ne.pop())!=null?se:"";for(let fe of ne){let Re=fe.split(`
7
7
  `),Ie="message",ce="";for(let Z of Re)Z.startsWith("event:")?Ie=Z.replace("event:","").trim():Z.startsWith("data:")&&(ce+=Z.replace("data:","").trim());if(!ce)continue;let L;try{L=JSON.parse(ce)}catch(Z){r({type:"error",error:Z instanceof Error?Z:new Error("Failed to parse chat stream payload")});continue}let st=Ie!=="message"?Ie:(P=L.type)!=null?P:"message";if(this.parseSSEEvent){f.current=T;let Z=await this.handleCustomSSEEvent(L,r,f,d,u);if(f.current&&!T&&(T=f.current),Z)continue}if(st==="reason_start"){let Z=(_e=I(L,!0))!=null?_e:`reason-${u()}`,x=V(Z);x.reasoning=(Ye=x.reasoning)!=null?Ye:{id:Z,status:"streaming",chunks:[]},x.reasoning.startedAt=(vt=x.reasoning.startedAt)!=null?vt:J((Qe=L.startedAt)!=null?Qe:L.timestamp),x.reasoning.completedAt=void 0,x.reasoning.durationMs=void 0,x.streaming=!0,x.reasoning.status="streaming",d(x)}else if(st==="reason_chunk"){let Z=(D=(bt=I(L,!1))!=null?bt:I(L,!0))!=null?D:`reason-${u()}`,x=V(Z);x.reasoning=(he=x.reasoning)!=null?he:{id:Z,status:"streaming",chunks:[]},x.reasoning.startedAt=(mt=x.reasoning.startedAt)!=null?mt:J((ht=L.startedAt)!=null?ht:L.timestamp);let g=(M=(rt=(Je=L.reasoningText)!=null?Je:L.text)!=null?rt:L.delta)!=null?M:"";if(g&&L.hidden!==!0&&x.reasoning.chunks.push(String(g)),x.reasoning.status=L.done?"complete":"streaming",L.done){x.reasoning.completedAt=J((Me=L.completedAt)!=null?Me:L.timestamp);let B=(it=x.reasoning.startedAt)!=null?it:Date.now();x.reasoning.durationMs=Math.max(0,((at=x.reasoning.completedAt)!=null?at:Date.now())-B)}x.streaming=x.reasoning.status!=="complete",d(x)}else if(st==="reason_complete"){let Z=(ft=(Tt=I(L,!1))!=null?Tt:I(L,!0))!=null?ft:`reason-${u()}`,x=b.get(Z);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=J((ke=L.completedAt)!=null?ke:L.timestamp);let B=(et=x.reasoning.startedAt)!=null?et:Date.now();x.reasoning.durationMs=Math.max(0,((qe=x.reasoning.completedAt)!=null?qe:Date.now())-B),x.streaming=!1,d(x)}let g=C(L);g&&_.byStep.delete(g)}else if(st==="tool_start"){let Z=(F=A(L,!0))!=null?F:`tool-${u()}`,x=ie(Z),g=(lt=x.toolCall)!=null?lt:{id:Z,status:"pending"};g.name=(Ke=L.toolName)!=null?Ke:g.name,g.status="running",L.args!==void 0&&(g.args=L.args),g.startedAt=(je=g.startedAt)!=null?je:J((We=L.startedAt)!=null?We:L.timestamp),g.completedAt=void 0,g.durationMs=void 0,x.toolCall=g,x.streaming=!0,d(x)}else if(st==="tool_chunk"){let Z=(Se=(K=A(L,!1))!=null?K:A(L,!0))!=null?Se:`tool-${u()}`,x=ie(Z),g=(Le=x.toolCall)!=null?Le:{id:Z,status:"running"};g.startedAt=(tt=g.startedAt)!=null?tt:J((Ue=L.startedAt)!=null?Ue:L.timestamp);let B=(pt=(Mt=(xt=L.text)!=null?xt:L.delta)!=null?Mt:L.message)!=null?pt:"";B&&(g.chunks=(Ct=g.chunks)!=null?Ct:[],g.chunks.push(String(B))),g.status="running",x.toolCall=g,x.streaming=!0,d(x)}else if(st==="tool_complete"){let Z=($t=(de=A(L,!1))!=null?de:A(L,!0))!=null?$t:`tool-${u()}`,x=ie(Z),g=(Lt=x.toolCall)!=null?Lt:{id:Z,status:"running"};if(g.status="complete",L.result!==void 0&&(g.result=L.result),typeof L.duration=="number"&&(g.duration=L.duration),g.completedAt=J((ve=L.completedAt)!=null?ve:L.timestamp),typeof L.duration=="number")g.durationMs=L.duration;else{let we=(wt=g.startedAt)!=null?wt:Date.now();g.durationMs=Math.max(0,((St=g.completedAt)!=null?St:Date.now())-we)}x.toolCall=g,x.streaming=!1,d(x);let B=$(L);B&&j.byCall.delete(B)}else if(st==="step_chunk"){let Z=L.stepType,x=L.executionType;if(Z==="tool"||x==="context")continue;let g=S(),B=(sn=(Et=(yt=(Bt=L.text)!=null?Bt:L.delta)!=null?yt:L.content)!=null?Et:L.chunk)!=null?sn:"";if(B){let Ae=((on=le.get(g.id))!=null?on:"")+B;g.rawContent=Ae,G.has(g.id)||G.set(g.id,this.createStreamParser());let Xe=G.get(g.id),Be=Ae.trim().startsWith("{")||Ae.trim().startsWith("[");if(Be&&le.set(g.id,Ae),Xe.__isPlainTextParser===!0){g.content+=B,le.delete(g.id),G.delete(g.id),g.rawContent=void 0,d(g);continue}let De=Xe.processChunk(Ae);if(De instanceof Promise)De.then(ae=>{var He;let ue=typeof ae=="string"?ae:(He=ae==null?void 0:ae.text)!=null?He:null;if(ue!==null&&ue.trim()!==""){let pe=T;pe&&pe.id===g.id&&(pe.content=ue,d(pe))}else if(!Be&&!Ae.trim().startsWith("<")){let pe=T;pe&&pe.id===g.id&&(pe.content+=B,le.delete(pe.id),G.delete(pe.id),pe.rawContent=void 0,d(pe))}}).catch(()=>{g.content+=B,le.delete(g.id),G.delete(g.id),g.rawContent=void 0,d(g)});else{let ae=typeof De=="string"?De:(rn=De==null?void 0:De.text)!=null?rn:null;ae!==null&&ae.trim()!==""?(g.content=ae,d(g)):!Be&&!Ae.trim().startsWith("<")&&(g.content+=B,le.delete(g.id),G.delete(g.id),g.rawContent=void 0,d(g))}}if(L.isComplete){let we=(Pt=(mn=L.result)==null?void 0:mn.response)!=null?Pt:g.content;if(we){let Ae=le.get(g.id),Xe=Ae!=null?Ae:z(we);g.rawContent=Xe;let Be=G.get(g.id),be=null,De=!1;if(Be&&(be=Be.getExtractedText(),be===null&&(be=dn(Xe)),be===null)){let ae=Be.processChunk(Xe);ae instanceof Promise?(De=!0,ae.then(ue=>{var pe;let He=typeof ue=="string"?ue:(pe=ue==null?void 0:ue.text)!=null?pe:null;if(He!==null){let Pe=T;Pe&&Pe.id===g.id&&(Pe.content=He,Pe.streaming=!1,G.delete(Pe.id),le.delete(Pe.id),d(Pe))}})):be=typeof ae=="string"?ae:(Ot=ae==null?void 0:ae.text)!=null?Ot:null}if(!De){be!==null&&be.trim()!==""?g.content=be:le.has(g.id)||(g.content=z(we));let ae=G.get(g.id);if(ae){let ue=(nt=ae.close)==null?void 0:nt.call(ae);ue instanceof Promise&&ue.catch(()=>{}),G.delete(g.id)}le.delete(g.id),g.streaming=!1,d(g)}}}}else if(st==="step_complete"){let Z=L.stepType,x=L.executionType;if(Z==="tool"||x==="context")continue;let g=(jt=L.result)==null?void 0:jt.response,B=S();if(g!=null){let we=G.get(B.id),Ae=!1,Xe=!1;if(we){let Be=we.getExtractedText(),be=le.get(B.id),De=be!=null?be:z(g);if(B.rawContent=De,Be!==null&&Be.trim()!=="")B.content=Be,Ae=!0;else{let ae=dn(De);if(ae!==null)B.content=ae,Ae=!0;else{let ue=we.processChunk(De);if(ue instanceof Promise)Xe=!0,ue.then(He=>{var Pe;let pe=typeof He=="string"?He:(Pe=He==null?void 0:He.text)!=null?Pe:null;if(pe!==null&&pe.trim()!==""){let ot=T;ot&&ot.id===B.id&&(ot.content=pe,ot.streaming=!1,G.delete(ot.id),le.delete(ot.id),d(ot))}else{let ot=we.getExtractedText(),gt=T;gt&&gt.id===B.id&&(ot!==null&&ot.trim()!==""?gt.content=ot:le.has(gt.id)||(gt.content=z(g)),gt.streaming=!1,G.delete(gt.id),le.delete(gt.id),d(gt))}});else{let He=typeof ue=="string"?ue:(Yt=ue==null?void 0:ue.text)!=null?Yt:null;if(He!==null&&He.trim()!=="")B.content=He,Ae=!0;else{let pe=we.getExtractedText();pe!==null&&pe.trim()!==""&&(B.content=pe,Ae=!0)}}}}}if(!Xe){if(!B.rawContent){let Be=le.get(B.id);B.rawContent=Be!=null?Be:z(g)}if(!Ae&&!le.has(B.id)&&(B.content=z(g)),we){let Be=(Jt=we.close)==null?void 0:Jt.call(we);Be instanceof Promise&&Be.catch(()=>{})}G.delete(B.id),le.delete(B.id),B.streaming=!1,d(B)}}else G.delete(B.id),le.delete(B.id),B.streaming=!1,d(B)}else if(st==="flow_complete"){let Z=(Kt=L.result)==null?void 0:Kt.response;if(Z!=null){let x=S(),g=le.get(x.id),B=g!=null?g:z(Z);x.rawContent=B;let we=z(Z),Ae=G.get(x.id);if(Ae){let be=dn(B);if(be!==null)we=be;else{let De=Ae.processChunk(B);De instanceof Promise&&De.then(ue=>{var pe;let He=typeof ue=="string"?ue:(pe=ue==null?void 0:ue.text)!=null?pe:null;if(He!==null){let Pe=T;Pe&&Pe.id===x.id&&(Pe.content=He,Pe.streaming=!1,d(Pe))}});let ae=Ae.getExtractedText();ae!==null&&(we=ae)}}G.delete(x.id),le.delete(x.id);let Xe=we!==x.content,Be=x.streaming!==!1;Xe&&(x.content=we),x.streaming=!1,(Xe||Be)&&d(x)}else if(T!==null){let x=T;G.delete(x.id),le.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}r({type:"status",status:"idle"})}else st==="error"&&L.error&&r({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};var Gt=class{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=e=>{var r,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(r=this.callbacks).onError)==null||t.call(r,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new qt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(e){this.config={...this.config,...e},this.client=new qt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,r){var l,u,h,d,T;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let o={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1};this.appendMessage(o),this.setStreaming(!0);let s=new AbortController;this.abortController=s;let i=[...this.messages];try{await this.client.dispatch({messages:i,signal:s.signal},this.handleEvent)}catch(f){let b={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f instanceof Error?(h=(u=this.callbacks).onError)==null||h.call(u,f):(T=(d=this.callbacks).onError)==null||T.call(d,new Error(String(f)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,t)=>{var u,h;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(u=r.sequence)!=null?u:0,l=(h=t.sequence)!=null?h:0;return i!==l?i-l:r.id.localeCompare(t.id)})}};var Sn=(n,e)=>{var t;let r=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let i=o.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(s))})};import*as Ro from"lucide";var ye=(n,e=24,r="currentColor",t=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ro[o];return s?Io(s,e,r,t):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function Io(n,e,r,t){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([h,d])=>{h!=="stroke"&&u.setAttribute(h,String(d))}),o.appendChild(u)}}}),o}var c=(n,e)=>{let r=document.createElement(n);return e&&(r.className=e),r};var ze={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var It={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Zt=(n,e)=>{let r=c("button");r.type="button",r.innerHTML=`
8
8
  <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
@@ -12,8 +12,8 @@ import{marked as eo}from"marked";eo.setOptions({breaks:!0});var to=n=>eo.parse(n
12
12
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,r.addEventListener("click",e);let t=s=>{var _,j,m,C,$,S,Y,I,V,te;let i=(_=s.launcher)!=null?_:{},l=r.querySelector("[data-role='launcher-title']");l&&(l.textContent=(j=i.title)!=null?j:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(m=i.subtitle)!=null?m:"Get answers fast");let h=r.querySelector(".tvw-flex-col");h&&(i.textHidden?h.style.display="none":h.style.display="");let d=r.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let A=(C=i.agentIconSize)!=null?C:"40px";if(d.style.height=A,d.style.width=A,d.innerHTML="",i.agentIconName){let ie=parseFloat(A)||24,J=ye(i.agentIconName,ie*.6,"#ffffff",2);J?(d.appendChild(J),d.style.display=""):(d.textContent=($=i.agentIconText)!=null?$:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(S=i.agentIconText)!=null?S:"\u{1F4AC}",d.style.display="")}let T=r.querySelector("[data-role='launcher-image']");if(T){let A=(Y=i.agentIconSize)!=null?Y:"40px";T.style.height=A,T.style.width=A,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(T.src=i.iconUrl,T.style.display="block"):T.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=(I=i.callToActionIconSize)!=null?I:"32px";f.style.height=A,f.style.width=A,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let ie=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,ie=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let J=parseFloat(A)||24,z=Math.max(J-ie,8),G=ye(i.callToActionIconName,z,"currentColor",2);G?f.appendChild(G):f.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}else f.textContent=(te=i.callToActionIconText)!=null?te:"\u2197"}let b=i.position&&It[i.position]?It[i.position]:It["bottom-right"],w="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${w} ${b}`},o=()=>{r.removeEventListener("click",e),r.remove()};return n&&t(n),{element:r,update:t,destroy:o}};var Ft=n=>{var ie,J,z,G,le,ne,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke,We,je;let{config:e,showClose:r=!0}=n,t=c("div","tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(ie=e==null?void 0:e.launcher)!=null?ie:{},s=(J=o.headerIconSize)!=null?J:"48px",i=(z=o.closeButtonSize)!=null?z:"32px",l=(G=o.closeButtonPlacement)!=null?G:"inline",u=(le=o.headerIconHidden)!=null?le:!1,h=o.headerIconName,d=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(d.style.height=s,d.style.width=s,!u)if(h){let K=parseFloat(s)||24,Se=ye(h,K*.6,"#ffffff",2);Se?d.replaceChildren(Se):d.textContent=(P=(ne=e==null?void 0:e.launcher)==null?void 0:ne.agentIconText)!=null?P:"\u{1F4AC}"}else if((_e=e==null?void 0:e.launcher)!=null&&_e.iconUrl){let K=c("img");K.src=e.launcher.iconUrl,K.alt="",K.className="tvw-rounded-xl tvw-object-cover",K.style.height=s,K.style.width=s,d.replaceChildren(K)}else d.textContent=(Qe=(Ye=e==null?void 0:e.launcher)==null?void 0:Ye.agentIconText)!=null?Qe:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col"),f=c("span","tvw-text-base tvw-font-semibold");f.textContent=(bt=(vt=e==null?void 0:e.launcher)==null?void 0:vt.title)!=null?bt:"Chat Assistant";let b=c("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(he=(D=e==null?void 0:e.launcher)==null?void 0:D.subtitle)!=null?he:"Here to help you get answers fast",T.append(f,b),u?t.append(T):t.append(d,T);let w=(ht=o.clearChat)!=null?ht:{},_=(mt=w.enabled)!=null?mt:!0,j=(Je=w.placement)!=null?Je:"inline",m=null,C=null;if(_){let K=(rt=w.size)!=null?rt:"32px",Se=(M=w.iconName)!=null?M:"refresh-cw",Le=(Me=w.iconColor)!=null?Me:"",Ue=(it=w.backgroundColor)!=null?it:"",tt=(at=w.borderWidth)!=null?at:"",xt=(Tt=w.borderColor)!=null?Tt:"",Mt=(ft=w.borderRadius)!=null?ft:"",pt=(ke=w.paddingX)!=null?ke:"",Ct=(et=w.paddingY)!=null?et:"",de=(qe=w.tooltipText)!=null?qe:"Clear chat",$t=(F=w.showTooltip)!=null?F:!0;C=c("div",j==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),j==="top-right"&&(C.style.right="48px"),m=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),m.style.height=K,m.style.width=K,m.type="button",m.setAttribute("aria-label",de);let Lt=ye(Se,"20px",Le||"",2);if(Lt&&m.appendChild(Lt),Le&&(m.style.color=Le,m.classList.remove("tvw-text-cw-muted")),Ue&&(m.style.backgroundColor=Ue,m.classList.remove("hover:tvw-bg-gray-100")),tt||xt){let ve=tt||"0px",wt=xt||"transparent";m.style.border=`${ve} solid ${wt}`,m.classList.remove("tvw-border-none")}if(Mt&&(m.style.borderRadius=Mt,m.classList.remove("tvw-rounded-full")),pt?(m.style.paddingLeft=pt,m.style.paddingRight=pt):(m.style.paddingLeft="",m.style.paddingRight=""),Ct?(m.style.paddingTop=Ct,m.style.paddingBottom=Ct):(m.style.paddingTop="",m.style.paddingBottom=""),C.appendChild(m),$t&&de&&m&&C){let ve=null,wt=()=>{if(ve||!m)return;ve=c("div","tvw-clear-chat-tooltip"),ve.textContent=de;let Bt=c("div");Bt.className="tvw-clear-chat-tooltip-arrow",ve.appendChild(Bt);let yt=m.getBoundingClientRect();ve.style.position="fixed",ve.style.left=`${yt.left+yt.width/2}px`,ve.style.top=`${yt.top-8}px`,ve.style.transform="translate(-50%, -100%)",document.body.appendChild(ve)},St=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};C.addEventListener("mouseenter",wt),C.addEventListener("mouseleave",St),m.addEventListener("focus",wt),m.addEventListener("blur",St),C._cleanupTooltip=()=>{St(),C&&(C.removeEventListener("mouseenter",wt),C.removeEventListener("mouseleave",St)),m&&(m.removeEventListener("focus",wt),m.removeEventListener("blur",St))}}j==="inline"&&t.appendChild(C)}let $=c("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":_&&j==="inline"?"":"tvw-ml-auto"),S=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");S.style.height=i,S.style.width=i,S.type="button";let Y=(lt=o.closeButtonTooltipText)!=null?lt:"Close chat",I=(Ke=o.closeButtonShowTooltip)!=null?Ke:!0;S.setAttribute("aria-label",Y),S.style.display=r?"":"none";let V=(We=o.closeButtonIconName)!=null?We:"x",te=(je=o.closeButtonIconText)!=null?je:"\xD7",A=ye(V,"20px",o.closeButtonColor||"",2);if(A?S.appendChild(A):S.textContent=te,o.closeButtonColor?(S.style.color=o.closeButtonColor,S.classList.remove("tvw-text-cw-muted")):(S.style.color="",S.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(S.style.backgroundColor=o.closeButtonBackgroundColor,S.classList.remove("hover:tvw-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let K=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";S.style.border=`${K} solid ${Se}`,S.classList.remove("tvw-border-none")}else S.style.border="",S.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(S.style.borderRadius=o.closeButtonBorderRadius,S.classList.remove("tvw-rounded-full")):(S.style.borderRadius="",S.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(S.style.paddingLeft=o.closeButtonPaddingX,S.style.paddingRight=o.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),o.closeButtonPaddingY?(S.style.paddingTop=o.closeButtonPaddingY,S.style.paddingBottom=o.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom=""),$.appendChild(S),I&&Y){let K=null,Se=()=>{if(K)return;K=c("div","tvw-clear-chat-tooltip"),K.textContent=Y;let Ue=c("div");Ue.className="tvw-clear-chat-tooltip-arrow",K.appendChild(Ue);let tt=S.getBoundingClientRect();K.style.position="fixed",K.style.left=`${tt.left+tt.width/2}px`,K.style.top=`${tt.top-8}px`,K.style.transform="translate(-50%, -100%)",document.body.appendChild(K)},Le=()=>{K&&K.parentNode&&(K.parentNode.removeChild(K),K=null)};$.addEventListener("mouseenter",Se),$.addEventListener("mouseleave",Le),S.addEventListener("focus",Se),S.addEventListener("blur",Le),$._cleanupTooltip=()=>{Le(),$.removeEventListener("mouseenter",Se),$.removeEventListener("mouseleave",Le),S.removeEventListener("focus",Se),S.removeEventListener("blur",Le)}}return l!=="top-right"&&t.appendChild($),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:b,closeButton:S,closeButtonWrapper:$,clearChatButton:m,clearChatButtonWrapper:C}},Qt=(n,e,r)=>{var i,l,u,h;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(l=t.closeButtonPlacement)!=null?l:"inline",s=(h=(u=t.clearChat)==null?void 0:u.placement)!=null?h:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var ao=n=>Ft({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),lo=n=>{var w,_,j,m;let{config:e,showClose:r=!0,onClose:t}=n,o=(w=e==null?void 0:e.launcher)!=null?w:{},s=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=c("span","tvw-text-base tvw-font-semibold");i.textContent=(_=o.title)!=null?_:"Chat Assistant",s.appendChild(i);let l=(j=o.closeButtonSize)!=null?j:"32px",u=c("div",""),h=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");h.style.height=l,h.style.width=l,h.type="button",h.setAttribute("aria-label","Close chat"),h.style.display=r?"":"none";let d=(m=o.closeButtonIconName)!=null?m:"x",T=ye(d,"20px",o.closeButtonColor||"",2);T?h.appendChild(T):h.textContent="\xD7",t&&h.addEventListener("click",t),u.appendChild(h),s.appendChild(u);let f=c("div");f.style.display="none";let b=c("span");return b.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:b,closeButton:h,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},co=n=>{var S,Y,I,V,te,A,ie,J;let{config:e,showClose:r=!0,onClose:t,onClearChat:o}=n,s=(S=e==null?void 0:e.launcher)!=null?S:{},i=c("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=c("div","tvw-flex tvw-items-center tvw-gap-3"),u=(Y=s.headerIconSize)!=null?Y:"56px",h=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");h.style.height=u,h.style.width=u;let d=s.headerIconName;if(d){let z=parseFloat(u)||24,G=ye(d,z*.5,"#ffffff",2);G?h.replaceChildren(G):h.textContent=(I=s.agentIconText)!=null?I:"\u{1F4AC}"}else if(s.iconUrl){let z=c("img");z.src=s.iconUrl,z.alt="",z.className="tvw-rounded-xl tvw-object-cover",z.style.height=u,z.style.width=u,h.replaceChildren(z)}else h.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col tvw-flex-1"),f=c("span","tvw-text-lg tvw-font-semibold");f.textContent=(te=s.title)!=null?te:"Chat Assistant";let b=c("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(A=s.subtitle)!=null?A:"Here to help you get answers fast",T.append(f,b),l.append(h,T);let w=(ie=s.closeButtonSize)!=null?ie:"32px",_=c("div",""),j=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");j.style.height=w,j.style.width=w,j.type="button",j.setAttribute("aria-label","Close chat"),j.style.display=r?"":"none";let m=(J=s.closeButtonIconName)!=null?J:"x",C=ye(m,"20px",s.closeButtonColor||"",2);C?j.appendChild(C):j.textContent="\xD7",t&&j.addEventListener("click",t),_.appendChild(j),l.appendChild(_),i.appendChild(l);let $=c("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return $.textContent="Online and ready to help",i.appendChild($),{header:i,iconHolder:h,headerTitle:f,headerSubtitle:b,closeButton:j,closeButtonWrapper:_,clearChatButton:null,clearChatButtonWrapper:null}},An={default:ao,minimal:lo,expanded:co},uo=n=>{var e;return(e=An[n])!=null?e:An.default},Tn=(n,e,r)=>{var i,l,u;if(e!=null&&e.render){let h=e.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),d=c("div");d.style.display="none";let T=c("span"),f=c("span"),b=c("button");b.style.display="none";let w=c("div");return w.style.display="none",{header:h,iconHolder:d,headerTitle:T,headerSubtitle:f,closeButton:b,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=uo(t)({config:n,showClose:(u=(l=e==null?void 0:e.showCloseButton)!=null?l:r==null?void 0:r.showClose)!=null?u:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var $o=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},en=n=>{var ne,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke;let{config:e}=n,r=c("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=((ne=e==null?void 0:e.voiceRecognition)==null?void 0:ne.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),u=c("form",`tvw-flex tvw-items-end ${o&&s?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);u.style.outline="none";let h=c("textarea");h.placeholder=(_e=(P=e==null?void 0:e.copy)==null?void 0:P.inputPlaceholder)!=null?_e:"Type your message\u2026",h.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",h.rows=1;let d=(Qe=(Ye=e==null?void 0:e.theme)==null?void 0:Ye.inputFontFamily)!=null?Qe:"sans-serif",T=(bt=(vt=e==null?void 0:e.theme)==null?void 0:vt.inputFontWeight)!=null?bt:"400";h.style.fontFamily=$o(d),h.style.fontWeight=T,h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.addEventListener("focus",()=>{h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.style.boxShadow="none"}),h.addEventListener("blur",()=>{h.style.border="none",h.style.outline="none"});let f=(D=e==null?void 0:e.sendButton)!=null?D:{},b=(he=f.useIcon)!=null?he:!1,w=(ht=f.iconText)!=null?ht:"\u2191",_=f.iconName,j=(mt=f.tooltipText)!=null?mt:"Send message",m=(Je=f.showTooltip)!=null?Je:!1,C=(rt=f.size)!=null?rt:"40px",$=f.backgroundColor,S=f.textColor,Y=c("div","tvw-send-button-wrapper"),I=c("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(I.type="submit",b){if(I.style.width=C,I.style.height=C,I.style.minWidth=C,I.style.minHeight=C,I.style.fontSize="18px",I.style.lineHeight="1",I.innerHTML="",_){let We=parseFloat(C)||24,je=S&&typeof S=="string"&&S.trim()?S.trim():"currentColor",K=ye(_,We,je,2);K?(I.appendChild(K),I.style.color=je):(I.textContent=w,S?I.style.color=S:I.classList.add("tvw-text-white"))}else I.textContent=w,S?I.style.color=S:I.classList.add("tvw-text-white");$?I.style.backgroundColor=$:I.classList.add("tvw-bg-cw-primary")}else I.textContent=(Me=(M=e==null?void 0:e.copy)==null?void 0:M.sendButtonLabel)!=null?Me:"Send",S?I.style.color=S:I.classList.add("tvw-text-white");if(f.borderWidth&&(I.style.borderWidth=f.borderWidth,I.style.borderStyle="solid"),f.borderColor&&(I.style.borderColor=f.borderColor),f.paddingX?(I.style.paddingLeft=f.paddingX,I.style.paddingRight=f.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),f.paddingY?(I.style.paddingTop=f.paddingY,I.style.paddingBottom=f.paddingY):(I.style.paddingTop="",I.style.paddingBottom=""),m&&j){let We=c("div","tvw-send-button-tooltip");We.textContent=j,Y.appendChild(We)}Y.appendChild(I);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},te=V.enabled===!0,A=null,ie=null,J=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(te&&J){ie=c("div","tvw-send-button-wrapper"),A=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),A.type="button",A.setAttribute("aria-label","Start voice recognition");let We=(at=V.iconName)!=null?at:"mic",je=(Tt=V.iconSize)!=null?Tt:C,K=parseFloat(je)||24,Se=(ft=V.backgroundColor)!=null?ft:$,Le=(ke=V.iconColor)!=null?ke:S;A.style.width=je,A.style.height=je,A.style.minWidth=je,A.style.minHeight=je,A.style.fontSize="18px",A.style.lineHeight="1";let Ue=Le||"currentColor",tt=ye(We,K,Ue,1.5);tt?(A.appendChild(tt),A.style.color=Ue):(A.textContent="\u{1F3A4}",A.style.color=Ue),Se?A.style.backgroundColor=Se:A.classList.add("tvw-bg-cw-primary"),Le?A.style.color=Le:!Le&&!S&&A.classList.add("tvw-text-white"),V.borderWidth&&(A.style.borderWidth=V.borderWidth,A.style.borderStyle="solid"),V.borderColor&&(A.style.borderColor=V.borderColor),V.paddingX&&(A.style.paddingLeft=V.paddingX,A.style.paddingRight=V.paddingX),V.paddingY&&(A.style.paddingTop=V.paddingY,A.style.paddingBottom=V.paddingY),ie.appendChild(A);let xt=(et=V.tooltipText)!=null?et:"Start voice recognition";if(((qe=V.showTooltip)!=null?qe:!1)&&xt){let pt=c("div","tvw-send-button-tooltip");pt.textContent=xt,ie.appendChild(pt)}}u.addEventListener("click",We=>{We.target!==I&&We.target!==Y&&We.target!==A&&We.target!==ie&&h.focus()}),u.append(h),ie&&u.append(ie),u.append(Y);let z=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),G=(F=e==null?void 0:e.statusIndicator)!=null?F:{},le=(lt=G.visible)!=null?lt:!0;return z.style.display=le?"":"none",z.textContent=(Ke=G.idleText)!=null?Ke:"Online",r.append(t,u,z),{footer:r,suggestions:t,composerForm:u,textarea:h,sendButton:I,sendButtonWrapper:Y,micButton:A,micButtonWrapper:ie,statusText:z}};var po=n=>{var u,h,d,T,f;if(!((h=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?h:!0)){let b=c("div","tvw-relative tvw-w-full tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),w=c("div","tvw-relative tvw-w-full tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0");return b.appendChild(w),{wrapper:b,panel:w}}let r=(d=n==null?void 0:n.launcher)!=null?d:{},t=r.position&&It[r.position]?It[r.position]:It["bottom-right"],o=c("div",`tvw-fixed ${t} tvw-z-50 tvw-transition`),s=c("div","tvw-relative tvw-min-h-[320px]"),i=(f=(T=n==null?void 0:n.launcher)==null?void 0:T.width)!=null?f:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,o.appendChild(s),{wrapper:o,panel:s}},go=(n,e=!0)=>{var T,f,b,w,_;let r=c("div","tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-shadow-2xl tvw-border tvw-border-cw-border"),t=(T=n==null?void 0:n.layout)==null?void 0:T.header,o=t?Tn(n,t,{showClose:e}):Ft({config:n,showClose:e}),s=c("div","tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");s.id="vanilla-agent-scroll-container";let i=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}";let u=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(_=(w=n==null?void 0:n.copy)==null?void 0:w.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",i.append(l,u);let h=c("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,h);let d=en({config:n});return Qt(r,o,n),r.append(s,d.footer),{container:r,body:s,messagesWrapper:h,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:l,introSubtitle:u,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:d.footer}};var cn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(r),n.appendChild(t),n.appendChild(o),n},Po=(n,e)=>{let r=c("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=c("img");o.src=t,o.alt=e==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},ho=(n,e)=>{let r=c("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?r.textContent=e.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Oo=(n,e="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},tn=(n,e,r)=>{var j,m,C,$,S;let t=r!=null?r:{},o=(j=t.layout)!=null?j:"bubble",s=t.avatar,i=t.timestamp,l=(m=s==null?void 0:s.show)!=null?m:!1,u=(C=i==null?void 0:i.show)!=null?C:!1,h=($=s==null?void 0:s.position)!=null?$:"left",d=(S=i==null?void 0:i.position)!=null?S:"below",T=Oo(n.role,o),f=c("div",T.join(" ")),b=document.createElement("div");if(b.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),u&&d==="inline"&&n.createdAt){let Y=ho(n,i);Y.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(Y)}if(f.appendChild(b),u&&d==="below"&&n.createdAt){let Y=ho(n,i);Y.classList.add("tvw-mt-1"),f.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=cn();f.appendChild(Y)}if(!l||n.role==="system")return f;let w=c("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),_=Po(s,n.role);return h==="right"||h==="left"&&n.role==="user"?w.append(f,_):w.append(_,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),w},No=(n,e,r)=>{let t=r!=null?r:{};return n.role==="user"&&t.renderUserMessage?t.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&t.renderAssistantMessage?t.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):tn(n,e,r)};var En=new Set,Wn=n=>{let e=n.reasoning,r=c("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return r;let t=En.has(n.id),o=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false");let s=c("div","tvw-flex tvw-flex-col tvw-text-left"),i=c("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=c("span","tvw-text-xs tvw-text-cw-primary");l.textContent=ro(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let u=c("div","tvw-flex tvw-items-center"),d=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);d?u.appendChild(d):u.textContent=t?"Hide":"Show";let T=c("div","tvw-flex tvw-items-center tvw-ml-auto");T.append(u),o.append(s,T);let f=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let b=e.chunks.join(""),w=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");w.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(w);let _=()=>{o.setAttribute("aria-expanded",t?"true":"false"),u.innerHTML="";let C=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);C?u.appendChild(C):u.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},j=()=>{t=!t,t?En.add(n.id):En.delete(n.id),_()};return o.addEventListener("pointerdown",m=>{m.preventDefault(),j()}),o.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),j())}),_(),r.append(o,f),r};var Mn=new Set,Ln=(n,e)=>{var j;let r=n.toolCall,t=(j=e==null?void 0:e.toolCall)!=null?j:{},o=c("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=Mn.has(n.id),i=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=c("div","tvw-flex tvw-flex-col tvw-text-left"),u=c("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(u.style.color=t.headerTextColor),u.textContent=io(r),l.appendChild(u);let h=c("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",T=ye(s?"chevron-up":"chevron-down",16,d,2);T?h.appendChild(T):h.textContent=s?"Hide":"Show";let f=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(h),i.append(l,f);let b=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=s?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),r.name){let m=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?m.style.color=t.contentTextColor:t.headerTextColor&&(m.style.color=t.headerTextColor),m.textContent=r.name,b.appendChild(m)}if(r.args!==void 0){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Arguments";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=yn(r.args),m.append(C,$),b.appendChild(m)}if(r.chunks&&r.chunks.length){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Activity";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=r.chunks.join(`
16
- `),m.append(C,$),b.appendChild(m)}if(r.status==="complete"&&r.result!==void 0){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Result";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=yn(r.result),m.append(C,$),b.appendChild(m)}if(r.status==="complete"&&typeof r.duration=="number"){let m=c("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${r.duration}ms`,b.appendChild(m)}let w=()=>{i.setAttribute("aria-expanded",s?"true":"false"),h.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",C=ye(s?"chevron-up":"chevron-down",16,m,2);C?h.appendChild(C):h.textContent=s?"Hide":"Show",b.style.display=s?"":"none"},_=()=>{s=!s,s?Mn.add(n.id):Mn.delete(n.id),w()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),_()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),_())}),w(),o.append(i,b),o};var mo=n=>{let e=[];return{buttons:e,render:(t,o,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(b=>b.role==="user"))return;let d=document.createDocumentFragment(),T=o?o.isStreaming():!1,f=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let w=c("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");w.type="button",w.textContent=b,w.disabled=T,l!=null&&l.fontFamily&&(w.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(w.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(w.style.paddingLeft=l.paddingX,w.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(w.style.paddingTop=l.paddingY,w.style.paddingBottom=l.paddingY),w.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(b))}),d.appendChild(w),e.push(w)}),n.appendChild(d)}}};var fo={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"}},Bn=(n,e,r,t)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,_,j;if(s.dataset.enhanced==="true")return;let i=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let l=(_=fo[i])!=null?_:fo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=c("div","tvw-space-y-1"),h=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(h.textContent=l.title,u.appendChild(h),l.description){let m=c("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,u.appendChild(m)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var I,V;let C=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");C.htmlFor=`${e.id}-${i}-${m.name}`;let $=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");$.textContent=m.label,C.appendChild($);let S=(I=m.type)!=null?I:"text",Y;S==="textarea"?(Y=document.createElement("textarea"),Y.rows=3):(Y=document.createElement("input"),Y.type=S),Y.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",Y.id=`${e.id}-${i}-${m.name}`,Y.name=m.name,Y.placeholder=(V=m.placeholder)!=null?V:"",m.required&&(Y.required=!0),C.appendChild(Y),d.appendChild(C)});let T=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=c("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(j=l.submitLabel)!=null?j:"Submit",T.appendChild(f),T.appendChild(b),d.appendChild(T),s.replaceChildren(u,d),d.addEventListener("submit",async m=>{var Y,I;m.preventDefault();let C=(Y=r.formEndpoint)!=null?Y:"/form",$=new FormData(d),S={};$.forEach((V,te)=>{S[te]=V}),S.type=i,b.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let te=await V.json();f.textContent=(I=te.message)!=null?I:"Thanks! We'll be in touch soon.",te.success&&te.nextPrompt&&await t.sendMessage(String(te.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var Hn=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var t;let r=this.plugins.get(e);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let t=new Set(e.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,u;return((l=i.priority)!=null?l:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},un=new Hn;var Ne={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},debug:!1};function kn(n){var e,r,t,o,s,i,l,u,h,d,T,f,b,w,_,j,m;return n?{...Ne,...n,theme:{...Ne.theme,...n.theme},launcher:{...Ne.launcher,...n.launcher,clearChat:{...(e=Ne.launcher)==null?void 0:e.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...Ne.copy,...n.copy},sendButton:{...Ne.sendButton,...n.sendButton},statusIndicator:{...Ne.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ne.voiceRecognition,...n.voiceRecognition},features:{...Ne.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Ne.suggestionChips,suggestionChipsConfig:{...Ne.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ne.layout,...n.layout,header:{...(o=Ne.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Ne.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(h=(u=Ne.layout)==null?void 0:u.messages)==null?void 0:h.avatar,...(T=(d=n.layout)==null?void 0:d.messages)==null?void 0:T.avatar},timestamp:{...(b=(f=Ne.layout)==null?void 0:f.messages)==null?void 0:b.timestamp,...(_=(w=n.layout)==null?void 0:w.messages)==null?void 0:_.timestamp}},slots:{...(j=Ne.layout)==null?void 0:j.slots,...(m=n.layout)==null?void 0:m.slots}}}:Ne}var wo=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:e,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(l=>{try{l(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Do=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Fo=n=>{let e=n.trim(),r=e.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(r,o+1)}return null},pn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Do(n),r=Fo(e);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},Rn=n=>typeof n=="string"?n:n==null?"":String(n),Ut={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Rn(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,t=Rn(r.element);if(t&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Rn(r.text)}}},yo=n=>Array.isArray(n)?n.map(e=>String(e)):[],gn=n=>{let e=new Set(yo(n.getMetadata().processedActionMessageIds)),r=()=>{e=new Set(yo(n.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((h,d)=>h||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let u={action:l,message:s.message};n.emit("action:detected",u);for(let h of n.handlers)if(h)try{let d=h(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let T=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:T}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:r}};var jo=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},_o=n=>n.map(e=>({...e,streaming:!1})),In=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?jo(r.getItem(n)):null},save:r=>{let t=e();if(t)try{let o={...r,messages:r.messages?_o(r.messages):void 0};t.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var $n=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,t])=>{this.register(r,t)})}},nn=new $n;import{parse as qo,STR as Uo,OBJ as zo}from"partial-json";function Yo(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function Jo(n,e){if(!Yo(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:e}}function Pn(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n;try{let o=qo(r,Uo|zo),s=Jo(o,r);s&&(n=s)}catch{}return e=r.length,n},reset:()=>{n=null,e=0}}}function Ko(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function On(n,e){let{config:r,message:t,onPropsUpdate:o}=e,s=nn.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:l=>{o&&o(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Xo(){let n=Pn();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Nn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Dn(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var zt="vanilla-agent-chat-history",Vo=30*1e3,Fn=n=>!n||typeof n!="object"?{}:{...n},vo=n=>n.map(e=>({...e,streaming:!1})),bo=(n,e)=>r=>{var s,i,l;let t=(s=r.text)!=null?s:"",o=(i=r.message.rawContent)!=null?i:null;if(e){let u=e.process({text:t,raw:o!=null?o:t,message:r.message,streaming:r.streaming});u!==null&&(t=u.text,u.persist||(r.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...r,text:t,raw:(l=o!=null?o:r.text)!=null?l:""}):wn(t)},jn=(n,e,r)=>{var ae,ue,He,pe,Pe,ot,gt,qn,Un,zn,Yn,Jn,Kn,Xn;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=kn(e);Sn(n,t);let o=un.getForInstance(t.plugins);t.components&&nn.registerAll(t.components);let s=wo(),i=(ae=t.storageAdapter)!=null?ae:In(),l={},u=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")u=a;else if(a){let p=a;p.metadata&&(l=Fn(p.metadata)),(ue=p.messages)!=null&&ue.length&&(t={...t,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let h=()=>l,d=a=>{var E;l=(E=a({...l}))!=null?E:{},Bt()},T=t.actionParsers&&t.actionParsers.length?t.actionParsers:[pn],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Ut.message,Ut.messageAndClick],b=gn({parsers:T,handlers:f,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let w=(pe=(He=t.launcher)==null?void 0:He.enabled)!=null?pe:!0,_=(ot=(Pe=t.launcher)==null?void 0:Pe.autoExpand)!=null?ot:!1,j=_,m=w,C=w?_:!0,$=bo(t,b),S=(qn=(gt=t.features)==null?void 0:gt.showReasoning)!=null?qn:!0,Y=(zn=(Un=t.features)==null?void 0:Un.showToolCalls)!=null?zn:!0,I=(Yn=t.statusIndicator)!=null?Yn:{},V=a=>{var p,E,N,k;return a==="idle"?(p=I.idleText)!=null?p:ze.idle:a==="connecting"?(E=I.connectingText)!=null?E:ze.connecting:a==="connected"?(N=I.connectedText)!=null?N:ze.connected:a==="error"?(k=I.errorText)!=null?k:ze.error:ze[a]},{wrapper:te,panel:A}=po(t),ie=go(t,w),{container:J,body:z,messagesWrapper:G,suggestions:le,textarea:ne,sendButton:P,sendButtonWrapper:_e,composerForm:Ye,statusText:Qe,introTitle:vt,introSubtitle:bt,closeButton:D,iconHolder:he,headerTitle:ht,headerSubtitle:mt,header:Je,footer:rt}=ie,M=ie.micButton,Me=ie.micButtonWrapper,it=o.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let p=Ft({config:t,showClose:w});return Qt(J,p,t),p.header},onClose:()=>nt(!1,"user")});if(a){let p=J.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Je=a)}}let at=o.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>en({config:t}).footer,onSubmit:p=>{F&&!F.isStreaming()&&F.sendMessage(p)},disabled:!1});a&&(rt.replaceWith(a),rt=a)}(()=>{var N,k;let a=(k=(N=t.layout)==null?void 0:N.slots)!=null?k:{},p=ee=>{switch(ee){case"body-top":return J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return G;case"footer-top":return le;case"composer":return Ye;case"footer-bottom":return Qe;default:return null}},E=(ee,H)=>{var v;switch(ee){case"header-left":case"header-center":case"header-right":if(ee==="header-left")Je.insertBefore(H,Je.firstChild);else if(ee==="header-right")Je.appendChild(H);else{let O=Je.querySelector(".tvw-flex-col");O?(v=O.parentNode)==null||v.insertBefore(H,O.nextSibling):Je.appendChild(H)}break;case"body-top":let U=z.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");U?U.replaceWith(H):z.insertBefore(H,z.firstChild);break;case"body-bottom":z.appendChild(H);break;case"footer-top":le.replaceWith(H);break;case"footer-bottom":Qe.replaceWith(H);break;default:break}};for(let[ee,H]of Object.entries(a))if(H)try{let v=H({config:t,defaultContent:()=>p(ee)});v&&E(ee,v)}catch(v){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ee}":`,v)}})(),A.appendChild(J),n.appendChild(te);let ft=()=>{var q,$e,xe,re,Oe,dt,oe,ct,Ht,kt,Wt,Nt;let a=($e=(q=t.launcher)==null?void 0:q.sidebarMode)!=null?$e:!1,p=a||((re=(xe=t.launcher)==null?void 0:xe.fullHeight)!=null?re:!1),E=(Oe=t.theme)!=null?Oe:{},N=(oe=(dt=t.launcher)==null?void 0:dt.position)!=null?oe:"bottom-left",k=N==="bottom-left"||N==="top-left",ee=a?"none":"1px solid var(--tvw-cw-border)",H=a?k?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",v=a?"0":"16px",U=(ct=E.panelBorder)!=null?ct:ee,O=(Ht=E.panelShadow)!=null?Ht:H,R=(kt=E.panelBorderRadius)!=null?kt:v;if(J.style.border=U,J.style.boxShadow=O,J.style.borderRadius=R,p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.height="100%",te.style.overflow="hidden",A.style.display="flex",A.style.flexDirection="column",A.style.flex="1 1 0%",A.style.minHeight="0",A.style.maxHeight="100%",A.style.height="100%",A.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",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",rt.style.flexShrink="0"),a){let Dt=(Nt=(Wt=t.launcher)==null?void 0:Wt.sidebarWidth)!=null?Nt:"420px";te.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),te.style.cssText=`
15
+ `,r.addEventListener("click",e);let t=s=>{var _,j,m,C,$,S,Y,I,V,te;let i=(_=s.launcher)!=null?_:{},l=r.querySelector("[data-role='launcher-title']");l&&(l.textContent=(j=i.title)!=null?j:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(m=i.subtitle)!=null?m:"Get answers fast");let h=r.querySelector(".tvw-flex-col");h&&(i.textHidden?h.style.display="none":h.style.display="");let d=r.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let A=(C=i.agentIconSize)!=null?C:"40px";if(d.style.height=A,d.style.width=A,d.innerHTML="",i.agentIconName){let ie=parseFloat(A)||24,J=ye(i.agentIconName,ie*.6,"#ffffff",2);J?(d.appendChild(J),d.style.display=""):(d.textContent=($=i.agentIconText)!=null?$:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(S=i.agentIconText)!=null?S:"\u{1F4AC}",d.style.display="")}let T=r.querySelector("[data-role='launcher-image']");if(T){let A=(Y=i.agentIconSize)!=null?Y:"40px";T.style.height=A,T.style.width=A,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(T.src=i.iconUrl,T.style.display="block"):T.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=(I=i.callToActionIconSize)!=null?I:"32px";f.style.height=A,f.style.width=A,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let ie=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,ie=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let J=parseFloat(A)||24,z=Math.max(J-ie,8),G=ye(i.callToActionIconName,z,"currentColor",2);G?f.appendChild(G):f.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}else f.textContent=(te=i.callToActionIconText)!=null?te:"\u2197"}let b=i.position&&It[i.position]?It[i.position]:It["bottom-right"],w="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${w} ${b}`},o=()=>{r.removeEventListener("click",e),r.remove()};return n&&t(n),{element:r,update:t,destroy:o}};var Ft=n=>{var ie,J,z,G,le,se,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke,We,je;let{config:e,showClose:r=!0}=n,t=c("div","tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(ie=e==null?void 0:e.launcher)!=null?ie:{},s=(J=o.headerIconSize)!=null?J:"48px",i=(z=o.closeButtonSize)!=null?z:"32px",l=(G=o.closeButtonPlacement)!=null?G:"inline",u=(le=o.headerIconHidden)!=null?le:!1,h=o.headerIconName,d=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(d.style.height=s,d.style.width=s,!u)if(h){let K=parseFloat(s)||24,Se=ye(h,K*.6,"#ffffff",2);Se?d.replaceChildren(Se):d.textContent=(P=(se=e==null?void 0:e.launcher)==null?void 0:se.agentIconText)!=null?P:"\u{1F4AC}"}else if((_e=e==null?void 0:e.launcher)!=null&&_e.iconUrl){let K=c("img");K.src=e.launcher.iconUrl,K.alt="",K.className="tvw-rounded-xl tvw-object-cover",K.style.height=s,K.style.width=s,d.replaceChildren(K)}else d.textContent=(Qe=(Ye=e==null?void 0:e.launcher)==null?void 0:Ye.agentIconText)!=null?Qe:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col"),f=c("span","tvw-text-base tvw-font-semibold");f.textContent=(bt=(vt=e==null?void 0:e.launcher)==null?void 0:vt.title)!=null?bt:"Chat Assistant";let b=c("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(he=(D=e==null?void 0:e.launcher)==null?void 0:D.subtitle)!=null?he:"Here to help you get answers fast",T.append(f,b),u?t.append(T):t.append(d,T);let w=(ht=o.clearChat)!=null?ht:{},_=(mt=w.enabled)!=null?mt:!0,j=(Je=w.placement)!=null?Je:"inline",m=null,C=null;if(_){let K=(rt=w.size)!=null?rt:"32px",Se=(M=w.iconName)!=null?M:"refresh-cw",Le=(Me=w.iconColor)!=null?Me:"",Ue=(it=w.backgroundColor)!=null?it:"",tt=(at=w.borderWidth)!=null?at:"",xt=(Tt=w.borderColor)!=null?Tt:"",Mt=(ft=w.borderRadius)!=null?ft:"",pt=(ke=w.paddingX)!=null?ke:"",Ct=(et=w.paddingY)!=null?et:"",de=(qe=w.tooltipText)!=null?qe:"Clear chat",$t=(F=w.showTooltip)!=null?F:!0;C=c("div",j==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),j==="top-right"&&(C.style.right="48px"),m=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),m.style.height=K,m.style.width=K,m.type="button",m.setAttribute("aria-label",de);let Lt=ye(Se,"20px",Le||"",2);if(Lt&&m.appendChild(Lt),Le&&(m.style.color=Le,m.classList.remove("tvw-text-cw-muted")),Ue&&(m.style.backgroundColor=Ue,m.classList.remove("hover:tvw-bg-gray-100")),tt||xt){let ve=tt||"0px",wt=xt||"transparent";m.style.border=`${ve} solid ${wt}`,m.classList.remove("tvw-border-none")}if(Mt&&(m.style.borderRadius=Mt,m.classList.remove("tvw-rounded-full")),pt?(m.style.paddingLeft=pt,m.style.paddingRight=pt):(m.style.paddingLeft="",m.style.paddingRight=""),Ct?(m.style.paddingTop=Ct,m.style.paddingBottom=Ct):(m.style.paddingTop="",m.style.paddingBottom=""),C.appendChild(m),$t&&de&&m&&C){let ve=null,wt=()=>{if(ve||!m)return;ve=c("div","tvw-clear-chat-tooltip"),ve.textContent=de;let Bt=c("div");Bt.className="tvw-clear-chat-tooltip-arrow",ve.appendChild(Bt);let yt=m.getBoundingClientRect();ve.style.position="fixed",ve.style.left=`${yt.left+yt.width/2}px`,ve.style.top=`${yt.top-8}px`,ve.style.transform="translate(-50%, -100%)",document.body.appendChild(ve)},St=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};C.addEventListener("mouseenter",wt),C.addEventListener("mouseleave",St),m.addEventListener("focus",wt),m.addEventListener("blur",St),C._cleanupTooltip=()=>{St(),C&&(C.removeEventListener("mouseenter",wt),C.removeEventListener("mouseleave",St)),m&&(m.removeEventListener("focus",wt),m.removeEventListener("blur",St))}}j==="inline"&&t.appendChild(C)}let $=c("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":_&&j==="inline"?"":"tvw-ml-auto"),S=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");S.style.height=i,S.style.width=i,S.type="button";let Y=(lt=o.closeButtonTooltipText)!=null?lt:"Close chat",I=(Ke=o.closeButtonShowTooltip)!=null?Ke:!0;S.setAttribute("aria-label",Y),S.style.display=r?"":"none";let V=(We=o.closeButtonIconName)!=null?We:"x",te=(je=o.closeButtonIconText)!=null?je:"\xD7",A=ye(V,"20px",o.closeButtonColor||"",2);if(A?S.appendChild(A):S.textContent=te,o.closeButtonColor?(S.style.color=o.closeButtonColor,S.classList.remove("tvw-text-cw-muted")):(S.style.color="",S.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(S.style.backgroundColor=o.closeButtonBackgroundColor,S.classList.remove("hover:tvw-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let K=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";S.style.border=`${K} solid ${Se}`,S.classList.remove("tvw-border-none")}else S.style.border="",S.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(S.style.borderRadius=o.closeButtonBorderRadius,S.classList.remove("tvw-rounded-full")):(S.style.borderRadius="",S.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(S.style.paddingLeft=o.closeButtonPaddingX,S.style.paddingRight=o.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),o.closeButtonPaddingY?(S.style.paddingTop=o.closeButtonPaddingY,S.style.paddingBottom=o.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom=""),$.appendChild(S),I&&Y){let K=null,Se=()=>{if(K)return;K=c("div","tvw-clear-chat-tooltip"),K.textContent=Y;let Ue=c("div");Ue.className="tvw-clear-chat-tooltip-arrow",K.appendChild(Ue);let tt=S.getBoundingClientRect();K.style.position="fixed",K.style.left=`${tt.left+tt.width/2}px`,K.style.top=`${tt.top-8}px`,K.style.transform="translate(-50%, -100%)",document.body.appendChild(K)},Le=()=>{K&&K.parentNode&&(K.parentNode.removeChild(K),K=null)};$.addEventListener("mouseenter",Se),$.addEventListener("mouseleave",Le),S.addEventListener("focus",Se),S.addEventListener("blur",Le),$._cleanupTooltip=()=>{Le(),$.removeEventListener("mouseenter",Se),$.removeEventListener("mouseleave",Le),S.removeEventListener("focus",Se),S.removeEventListener("blur",Le)}}return l!=="top-right"&&t.appendChild($),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:b,closeButton:S,closeButtonWrapper:$,clearChatButton:m,clearChatButtonWrapper:C}},Qt=(n,e,r)=>{var i,l,u,h;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(l=t.closeButtonPlacement)!=null?l:"inline",s=(h=(u=t.clearChat)==null?void 0:u.placement)!=null?h:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var ao=n=>Ft({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),lo=n=>{var w,_,j,m;let{config:e,showClose:r=!0,onClose:t}=n,o=(w=e==null?void 0:e.launcher)!=null?w:{},s=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=c("span","tvw-text-base tvw-font-semibold");i.textContent=(_=o.title)!=null?_:"Chat Assistant",s.appendChild(i);let l=(j=o.closeButtonSize)!=null?j:"32px",u=c("div",""),h=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");h.style.height=l,h.style.width=l,h.type="button",h.setAttribute("aria-label","Close chat"),h.style.display=r?"":"none";let d=(m=o.closeButtonIconName)!=null?m:"x",T=ye(d,"20px",o.closeButtonColor||"",2);T?h.appendChild(T):h.textContent="\xD7",t&&h.addEventListener("click",t),u.appendChild(h),s.appendChild(u);let f=c("div");f.style.display="none";let b=c("span");return b.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:b,closeButton:h,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},co=n=>{var S,Y,I,V,te,A,ie,J;let{config:e,showClose:r=!0,onClose:t,onClearChat:o}=n,s=(S=e==null?void 0:e.launcher)!=null?S:{},i=c("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=c("div","tvw-flex tvw-items-center tvw-gap-3"),u=(Y=s.headerIconSize)!=null?Y:"56px",h=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");h.style.height=u,h.style.width=u;let d=s.headerIconName;if(d){let z=parseFloat(u)||24,G=ye(d,z*.5,"#ffffff",2);G?h.replaceChildren(G):h.textContent=(I=s.agentIconText)!=null?I:"\u{1F4AC}"}else if(s.iconUrl){let z=c("img");z.src=s.iconUrl,z.alt="",z.className="tvw-rounded-xl tvw-object-cover",z.style.height=u,z.style.width=u,h.replaceChildren(z)}else h.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col tvw-flex-1"),f=c("span","tvw-text-lg tvw-font-semibold");f.textContent=(te=s.title)!=null?te:"Chat Assistant";let b=c("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(A=s.subtitle)!=null?A:"Here to help you get answers fast",T.append(f,b),l.append(h,T);let w=(ie=s.closeButtonSize)!=null?ie:"32px",_=c("div",""),j=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");j.style.height=w,j.style.width=w,j.type="button",j.setAttribute("aria-label","Close chat"),j.style.display=r?"":"none";let m=(J=s.closeButtonIconName)!=null?J:"x",C=ye(m,"20px",s.closeButtonColor||"",2);C?j.appendChild(C):j.textContent="\xD7",t&&j.addEventListener("click",t),_.appendChild(j),l.appendChild(_),i.appendChild(l);let $=c("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return $.textContent="Online and ready to help",i.appendChild($),{header:i,iconHolder:h,headerTitle:f,headerSubtitle:b,closeButton:j,closeButtonWrapper:_,clearChatButton:null,clearChatButtonWrapper:null}},An={default:ao,minimal:lo,expanded:co},uo=n=>{var e;return(e=An[n])!=null?e:An.default},Tn=(n,e,r)=>{var i,l,u;if(e!=null&&e.render){let h=e.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),d=c("div");d.style.display="none";let T=c("span"),f=c("span"),b=c("button");b.style.display="none";let w=c("div");return w.style.display="none",{header:h,iconHolder:d,headerTitle:T,headerSubtitle:f,closeButton:b,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=uo(t)({config:n,showClose:(u=(l=e==null?void 0:e.showCloseButton)!=null?l:r==null?void 0:r.showClose)!=null?u:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var $o=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},en=n=>{var se,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke;let{config:e}=n,r=c("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=((se=e==null?void 0:e.voiceRecognition)==null?void 0:se.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),u=c("form",`tvw-flex tvw-items-end ${o&&s?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);u.style.outline="none";let h=c("textarea");h.placeholder=(_e=(P=e==null?void 0:e.copy)==null?void 0:P.inputPlaceholder)!=null?_e:"Type your message\u2026",h.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",h.rows=1;let d=(Qe=(Ye=e==null?void 0:e.theme)==null?void 0:Ye.inputFontFamily)!=null?Qe:"sans-serif",T=(bt=(vt=e==null?void 0:e.theme)==null?void 0:vt.inputFontWeight)!=null?bt:"400";h.style.fontFamily=$o(d),h.style.fontWeight=T,h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.addEventListener("focus",()=>{h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.style.boxShadow="none"}),h.addEventListener("blur",()=>{h.style.border="none",h.style.outline="none"});let f=(D=e==null?void 0:e.sendButton)!=null?D:{},b=(he=f.useIcon)!=null?he:!1,w=(ht=f.iconText)!=null?ht:"\u2191",_=f.iconName,j=(mt=f.tooltipText)!=null?mt:"Send message",m=(Je=f.showTooltip)!=null?Je:!1,C=(rt=f.size)!=null?rt:"40px",$=f.backgroundColor,S=f.textColor,Y=c("div","tvw-send-button-wrapper"),I=c("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(I.type="submit",b){if(I.style.width=C,I.style.height=C,I.style.minWidth=C,I.style.minHeight=C,I.style.fontSize="18px",I.style.lineHeight="1",I.innerHTML="",_){let We=parseFloat(C)||24,je=S&&typeof S=="string"&&S.trim()?S.trim():"currentColor",K=ye(_,We,je,2);K?(I.appendChild(K),I.style.color=je):(I.textContent=w,S?I.style.color=S:I.classList.add("tvw-text-white"))}else I.textContent=w,S?I.style.color=S:I.classList.add("tvw-text-white");$?I.style.backgroundColor=$:I.classList.add("tvw-bg-cw-primary")}else I.textContent=(Me=(M=e==null?void 0:e.copy)==null?void 0:M.sendButtonLabel)!=null?Me:"Send",S?I.style.color=S:I.classList.add("tvw-text-white");if(f.borderWidth&&(I.style.borderWidth=f.borderWidth,I.style.borderStyle="solid"),f.borderColor&&(I.style.borderColor=f.borderColor),f.paddingX?(I.style.paddingLeft=f.paddingX,I.style.paddingRight=f.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),f.paddingY?(I.style.paddingTop=f.paddingY,I.style.paddingBottom=f.paddingY):(I.style.paddingTop="",I.style.paddingBottom=""),m&&j){let We=c("div","tvw-send-button-tooltip");We.textContent=j,Y.appendChild(We)}Y.appendChild(I);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},te=V.enabled===!0,A=null,ie=null,J=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(te&&J){ie=c("div","tvw-send-button-wrapper"),A=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),A.type="button",A.setAttribute("aria-label","Start voice recognition");let We=(at=V.iconName)!=null?at:"mic",je=(Tt=V.iconSize)!=null?Tt:C,K=parseFloat(je)||24,Se=(ft=V.backgroundColor)!=null?ft:$,Le=(ke=V.iconColor)!=null?ke:S;A.style.width=je,A.style.height=je,A.style.minWidth=je,A.style.minHeight=je,A.style.fontSize="18px",A.style.lineHeight="1";let Ue=Le||"currentColor",tt=ye(We,K,Ue,1.5);tt?(A.appendChild(tt),A.style.color=Ue):(A.textContent="\u{1F3A4}",A.style.color=Ue),Se?A.style.backgroundColor=Se:A.classList.add("tvw-bg-cw-primary"),Le?A.style.color=Le:!Le&&!S&&A.classList.add("tvw-text-white"),V.borderWidth&&(A.style.borderWidth=V.borderWidth,A.style.borderStyle="solid"),V.borderColor&&(A.style.borderColor=V.borderColor),V.paddingX&&(A.style.paddingLeft=V.paddingX,A.style.paddingRight=V.paddingX),V.paddingY&&(A.style.paddingTop=V.paddingY,A.style.paddingBottom=V.paddingY),ie.appendChild(A);let xt=(et=V.tooltipText)!=null?et:"Start voice recognition";if(((qe=V.showTooltip)!=null?qe:!1)&&xt){let pt=c("div","tvw-send-button-tooltip");pt.textContent=xt,ie.appendChild(pt)}}u.addEventListener("click",We=>{We.target!==I&&We.target!==Y&&We.target!==A&&We.target!==ie&&h.focus()}),u.append(h),ie&&u.append(ie),u.append(Y);let z=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),G=(F=e==null?void 0:e.statusIndicator)!=null?F:{},le=(lt=G.visible)!=null?lt:!0;return z.style.display=le?"":"none",z.textContent=(Ke=G.idleText)!=null?Ke:"Online",r.append(t,u,z),{footer:r,suggestions:t,composerForm:u,textarea:h,sendButton:I,sendButtonWrapper:Y,micButton:A,micButtonWrapper:ie,statusText:z}};var po=n=>{var u,h,d,T,f;if(!((h=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?h:!0)){let b=c("div","tvw-relative tvw-w-full tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),w=c("div","tvw-relative tvw-w-full tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0");return b.appendChild(w),{wrapper:b,panel:w}}let r=(d=n==null?void 0:n.launcher)!=null?d:{},t=r.position&&It[r.position]?It[r.position]:It["bottom-right"],o=c("div",`tvw-fixed ${t} tvw-z-50 tvw-transition`),s=c("div","tvw-relative tvw-min-h-[320px]"),i=(f=(T=n==null?void 0:n.launcher)==null?void 0:T.width)!=null?f:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,o.appendChild(s),{wrapper:o,panel:s}},go=(n,e=!0)=>{var T,f,b,w,_;let r=c("div","tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-shadow-2xl tvw-border tvw-border-cw-border"),t=(T=n==null?void 0:n.layout)==null?void 0:T.header,o=t?Tn(n,t,{showClose:e}):Ft({config:n,showClose:e}),s=c("div","tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");s.id="vanilla-agent-scroll-container";let i=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}";let u=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(_=(w=n==null?void 0:n.copy)==null?void 0:w.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",i.append(l,u);let h=c("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,h);let d=en({config:n});return Qt(r,o,n),r.append(s,d.footer),{container:r,body:s,messagesWrapper:h,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:l,introSubtitle:u,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:d.footer}};var cn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(r),n.appendChild(t),n.appendChild(o),n},Po=(n,e)=>{let r=c("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=c("img");o.src=t,o.alt=e==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},ho=(n,e)=>{let r=c("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?r.textContent=e.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Oo=(n,e="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},tn=(n,e,r)=>{var j,m,C,$,S;let t=r!=null?r:{},o=(j=t.layout)!=null?j:"bubble",s=t.avatar,i=t.timestamp,l=(m=s==null?void 0:s.show)!=null?m:!1,u=(C=i==null?void 0:i.show)!=null?C:!1,h=($=s==null?void 0:s.position)!=null?$:"left",d=(S=i==null?void 0:i.position)!=null?S:"below",T=Oo(n.role,o),f=c("div",T.join(" ")),b=document.createElement("div");if(b.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),u&&d==="inline"&&n.createdAt){let Y=ho(n,i);Y.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(Y)}if(f.appendChild(b),u&&d==="below"&&n.createdAt){let Y=ho(n,i);Y.classList.add("tvw-mt-1"),f.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=cn();f.appendChild(Y)}if(!l||n.role==="system")return f;let w=c("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),_=Po(s,n.role);return h==="right"||h==="left"&&n.role==="user"?w.append(f,_):w.append(_,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),w},No=(n,e,r)=>{let t=r!=null?r:{};return n.role==="user"&&t.renderUserMessage?t.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&t.renderAssistantMessage?t.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):tn(n,e,r)};var En=new Set,Wn=n=>{let e=n.reasoning,r=c("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return r;let t=En.has(n.id),o=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false");let s=c("div","tvw-flex tvw-flex-col tvw-text-left"),i=c("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=c("span","tvw-text-xs tvw-text-cw-primary");l.textContent=ro(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let u=c("div","tvw-flex tvw-items-center"),d=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);d?u.appendChild(d):u.textContent=t?"Hide":"Show";let T=c("div","tvw-flex tvw-items-center tvw-ml-auto");T.append(u),o.append(s,T);let f=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let b=e.chunks.join(""),w=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");w.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(w);let _=()=>{o.setAttribute("aria-expanded",t?"true":"false"),u.innerHTML="";let C=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);C?u.appendChild(C):u.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},j=()=>{t=!t,t?En.add(n.id):En.delete(n.id),_()};return o.addEventListener("pointerdown",m=>{m.preventDefault(),j()}),o.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),j())}),_(),r.append(o,f),r};var Mn=new Set,Ln=(n,e)=>{var j;let r=n.toolCall,t=(j=e==null?void 0:e.toolCall)!=null?j:{},o=c("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=Mn.has(n.id),i=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=c("div","tvw-flex tvw-flex-col tvw-text-left"),u=c("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(u.style.color=t.headerTextColor),u.textContent=io(r),l.appendChild(u);let h=c("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",T=ye(s?"chevron-up":"chevron-down",16,d,2);T?h.appendChild(T):h.textContent=s?"Hide":"Show";let f=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(h),i.append(l,f);let b=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=s?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),r.name){let m=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?m.style.color=t.contentTextColor:t.headerTextColor&&(m.style.color=t.headerTextColor),m.textContent=r.name,b.appendChild(m)}if(r.args!==void 0){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Arguments";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=yn(r.args),m.append(C,$),b.appendChild(m)}if(r.chunks&&r.chunks.length){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Activity";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=r.chunks.join(`
16
+ `),m.append(C,$),b.appendChild(m)}if(r.status==="complete"&&r.result!==void 0){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Result";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=yn(r.result),m.append(C,$),b.appendChild(m)}if(r.status==="complete"&&typeof r.duration=="number"){let m=c("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${r.duration}ms`,b.appendChild(m)}let w=()=>{i.setAttribute("aria-expanded",s?"true":"false"),h.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",C=ye(s?"chevron-up":"chevron-down",16,m,2);C?h.appendChild(C):h.textContent=s?"Hide":"Show",b.style.display=s?"":"none"},_=()=>{s=!s,s?Mn.add(n.id):Mn.delete(n.id),w()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),_()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),_())}),w(),o.append(i,b),o};var mo=n=>{let e=[];return{buttons:e,render:(t,o,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(b=>b.role==="user"))return;let d=document.createDocumentFragment(),T=o?o.isStreaming():!1,f=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let w=c("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");w.type="button",w.textContent=b,w.disabled=T,l!=null&&l.fontFamily&&(w.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(w.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(w.style.paddingLeft=l.paddingX,w.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(w.style.paddingTop=l.paddingY,w.style.paddingBottom=l.paddingY),w.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(b))}),d.appendChild(w),e.push(w)}),n.appendChild(d)}}};var fo={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"}},Bn=(n,e,r,t)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,_,j;if(s.dataset.enhanced==="true")return;let i=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let l=(_=fo[i])!=null?_:fo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=c("div","tvw-space-y-1"),h=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(h.textContent=l.title,u.appendChild(h),l.description){let m=c("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,u.appendChild(m)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var I,V;let C=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");C.htmlFor=`${e.id}-${i}-${m.name}`;let $=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");$.textContent=m.label,C.appendChild($);let S=(I=m.type)!=null?I:"text",Y;S==="textarea"?(Y=document.createElement("textarea"),Y.rows=3):(Y=document.createElement("input"),Y.type=S),Y.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",Y.id=`${e.id}-${i}-${m.name}`,Y.name=m.name,Y.placeholder=(V=m.placeholder)!=null?V:"",m.required&&(Y.required=!0),C.appendChild(Y),d.appendChild(C)});let T=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=c("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(j=l.submitLabel)!=null?j:"Submit",T.appendChild(f),T.appendChild(b),d.appendChild(T),s.replaceChildren(u,d),d.addEventListener("submit",async m=>{var Y,I;m.preventDefault();let C=(Y=r.formEndpoint)!=null?Y:"/form",$=new FormData(d),S={};$.forEach((V,te)=>{S[te]=V}),S.type=i,b.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let te=await V.json();f.textContent=(I=te.message)!=null?I:"Thanks! We'll be in touch soon.",te.success&&te.nextPrompt&&await t.sendMessage(String(te.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var Hn=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var t;let r=this.plugins.get(e);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let t=new Set(e.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,u;return((l=i.priority)!=null?l:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},un=new Hn;var Ne={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},debug:!1};function kn(n){var e,r,t,o,s,i,l,u,h,d,T,f,b,w,_,j,m;return n?{...Ne,...n,theme:{...Ne.theme,...n.theme},launcher:{...Ne.launcher,...n.launcher,clearChat:{...(e=Ne.launcher)==null?void 0:e.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...Ne.copy,...n.copy},sendButton:{...Ne.sendButton,...n.sendButton},statusIndicator:{...Ne.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ne.voiceRecognition,...n.voiceRecognition},features:{...Ne.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Ne.suggestionChips,suggestionChipsConfig:{...Ne.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ne.layout,...n.layout,header:{...(o=Ne.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Ne.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(h=(u=Ne.layout)==null?void 0:u.messages)==null?void 0:h.avatar,...(T=(d=n.layout)==null?void 0:d.messages)==null?void 0:T.avatar},timestamp:{...(b=(f=Ne.layout)==null?void 0:f.messages)==null?void 0:b.timestamp,...(_=(w=n.layout)==null?void 0:w.messages)==null?void 0:_.timestamp}},slots:{...(j=Ne.layout)==null?void 0:j.slots,...(m=n.layout)==null?void 0:m.slots}}}:Ne}var wo=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:e,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(l=>{try{l(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Do=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Fo=n=>{let e=n.trim(),r=e.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(r,o+1)}return null},pn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Do(n),r=Fo(e);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},Rn=n=>typeof n=="string"?n:n==null?"":String(n),Ut={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Rn(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,t=Rn(r.element);if(t&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Rn(r.text)}}},yo=n=>Array.isArray(n)?n.map(e=>String(e)):[],gn=n=>{let e=new Set(yo(n.getMetadata().processedActionMessageIds)),r=()=>{e=new Set(yo(n.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((h,d)=>h||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let u={action:l,message:s.message};n.emit("action:detected",u);for(let h of n.handlers)if(h)try{let d=h(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let T=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:T}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:r}};var jo=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},_o=n=>n.map(e=>({...e,streaming:!1})),In=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?jo(r.getItem(n)):null},save:r=>{let t=e();if(t)try{let o={...r,messages:r.messages?_o(r.messages):void 0};t.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var $n=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,t])=>{this.register(r,t)})}},nn=new $n;import{parse as qo,STR as Uo,OBJ as zo}from"partial-json";function Yo(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function Jo(n,e){if(!Yo(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:e}}function Pn(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n;try{let o=qo(r,Uo|zo),s=Jo(o,r);s&&(n=s)}catch{}return e=r.length,n},reset:()=>{n=null,e=0}}}function Ko(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function On(n,e){let{config:r,message:t,onPropsUpdate:o}=e,s=nn.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:l=>{o&&o(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Xo(){let n=Pn();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Nn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Dn(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var zt="vanilla-agent-chat-history",Vo=30*1e3,Fn=n=>!n||typeof n!="object"?{}:{...n},vo=n=>n.map(e=>({...e,streaming:!1})),bo=(n,e)=>r=>{var s,i,l;let t=(s=r.text)!=null?s:"",o=(i=r.message.rawContent)!=null?i:null;if(e){let u=e.process({text:t,raw:o!=null?o:t,message:r.message,streaming:r.streaming});u!==null&&(t=u.text,u.persist||(r.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...r,text:t,raw:(l=o!=null?o:r.text)!=null?l:""}):wn(t)},jn=(n,e,r)=>{var ae,ue,He,pe,Pe,ot,gt,qn,Un,zn,Yn,Jn,Kn,Xn;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=kn(e);Sn(n,t);let o=un.getForInstance(t.plugins);t.components&&nn.registerAll(t.components);let s=wo(),i=(ae=t.storageAdapter)!=null?ae:In(),l={},u=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")u=a;else if(a){let p=a;p.metadata&&(l=Fn(p.metadata)),(ue=p.messages)!=null&&ue.length&&(t={...t,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let h=()=>l,d=a=>{var E;l=(E=a({...l}))!=null?E:{},Bt()},T=t.actionParsers&&t.actionParsers.length?t.actionParsers:[pn],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Ut.message,Ut.messageAndClick],b=gn({parsers:T,handlers:f,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let w=(pe=(He=t.launcher)==null?void 0:He.enabled)!=null?pe:!0,_=(ot=(Pe=t.launcher)==null?void 0:Pe.autoExpand)!=null?ot:!1,j=_,m=w,C=w?_:!0,$=bo(t,b),S=(qn=(gt=t.features)==null?void 0:gt.showReasoning)!=null?qn:!0,Y=(zn=(Un=t.features)==null?void 0:Un.showToolCalls)!=null?zn:!0,I=(Yn=t.statusIndicator)!=null?Yn:{},V=a=>{var p,E,N,k;return a==="idle"?(p=I.idleText)!=null?p:ze.idle:a==="connecting"?(E=I.connectingText)!=null?E:ze.connecting:a==="connected"?(N=I.connectedText)!=null?N:ze.connected:a==="error"?(k=I.errorText)!=null?k:ze.error:ze[a]},{wrapper:te,panel:A}=po(t),ie=go(t,w),{container:J,body:z,messagesWrapper:G,suggestions:le,textarea:se,sendButton:P,sendButtonWrapper:_e,composerForm:Ye,statusText:Qe,introTitle:vt,introSubtitle:bt,closeButton:D,iconHolder:he,headerTitle:ht,headerSubtitle:mt,header:Je,footer:rt}=ie,M=ie.micButton,Me=ie.micButtonWrapper,it=o.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let p=Ft({config:t,showClose:w});return Qt(J,p,t),p.header},onClose:()=>nt(!1,"user")});if(a){let p=J.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Je=a)}}let at=o.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>en({config:t}).footer,onSubmit:p=>{F&&!F.isStreaming()&&F.sendMessage(p)},disabled:!1});a&&(rt.replaceWith(a),rt=a)}(()=>{var N,k;let a=(k=(N=t.layout)==null?void 0:N.slots)!=null?k:{},p=ee=>{switch(ee){case"body-top":return J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return G;case"footer-top":return le;case"composer":return Ye;case"footer-bottom":return Qe;default:return null}},E=(ee,H)=>{var v;switch(ee){case"header-left":case"header-center":case"header-right":if(ee==="header-left")Je.insertBefore(H,Je.firstChild);else if(ee==="header-right")Je.appendChild(H);else{let O=Je.querySelector(".tvw-flex-col");O?(v=O.parentNode)==null||v.insertBefore(H,O.nextSibling):Je.appendChild(H)}break;case"body-top":let U=z.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");U?U.replaceWith(H):z.insertBefore(H,z.firstChild);break;case"body-bottom":z.appendChild(H);break;case"footer-top":le.replaceWith(H);break;case"footer-bottom":Qe.replaceWith(H);break;default:break}};for(let[ee,H]of Object.entries(a))if(H)try{let v=H({config:t,defaultContent:()=>p(ee)});v&&E(ee,v)}catch(v){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ee}":`,v)}})(),A.appendChild(J),n.appendChild(te);let ft=()=>{var q,$e,xe,re,Oe,dt,oe,ct,Ht,kt,Wt,Nt;let a=($e=(q=t.launcher)==null?void 0:q.sidebarMode)!=null?$e:!1,p=a||((re=(xe=t.launcher)==null?void 0:xe.fullHeight)!=null?re:!1),E=(Oe=t.theme)!=null?Oe:{},N=(oe=(dt=t.launcher)==null?void 0:dt.position)!=null?oe:"bottom-left",k=N==="bottom-left"||N==="top-left",ee=a?"none":"1px solid var(--tvw-cw-border)",H=a?k?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",v=a?"0":"16px",U=(ct=E.panelBorder)!=null?ct:ee,O=(Ht=E.panelShadow)!=null?Ht:H,R=(kt=E.panelBorderRadius)!=null?kt:v;if(J.style.border=U,J.style.boxShadow=O,J.style.borderRadius=R,p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.height="100%",te.style.overflow="hidden",A.style.display="flex",A.style.flexDirection="column",A.style.flex="1 1 0%",A.style.minHeight="0",A.style.maxHeight="100%",A.style.height="100%",A.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",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",rt.style.flexShrink="0"),a){let Dt=(Nt=(Wt=t.launcher)==null?void 0:Wt.sidebarWidth)!=null?Nt:"420px";te.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),te.style.cssText=`
17
17
  position: fixed !important;
18
18
  top: 0 !important;
19
19
  bottom: 0 !important;
@@ -52,7 +52,7 @@ import{marked as eo}from"marked";eo.setOptions({breaks:!0});var to=n=>eo.parse(n
52
52
  flex-shrink: 0 !important;
53
53
  border-top: none !important;
54
54
  padding: 8px 16px 12px 16px !important;
55
- `}};ft();let ke=[],et=mo(le),qe=null,F,lt=!1,Ke=!0,We=0,je=0,K=null,Se=!1,Le=0,Ue=!1,tt=125,xt=2e3,Mt=5,pt=50,Ct=new Map,de={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},$t=(Kn=(Jn=t.voiceRecognition)==null?void 0:Jn.autoResume)!=null?Kn:!1,Lt=a=>{s.emit("voice:state",{active:de.active,source:a,timestamp:Date.now()})},ve=()=>{d(a=>({...a,voiceState:{active:de.active,timestamp:Date.now(),manuallyDeactivated:de.manuallyDeactivated}}))},wt=()=>{var N,k;if(((N=t.voiceRecognition)==null?void 0:N.enabled)===!1)return;let a=Fn(l.voiceState),p=!!a.active,E=Number((k=a.timestamp)!=null?k:0);de.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-E<Vo&&setTimeout(()=>{de.active||(de.manuallyDeactivated=!1,Ie("restore"))},1e3)},St=()=>F?vo(F.getMessages()).filter(a=>!a.__skipPersist):[];function Bt(a){if(!(i!=null&&i.save))return;let E={messages:a?vo(a):F?St():[],metadata:l};try{let N=i.save(E);N instanceof Promise&&N.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(N){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",N)}}let yt=(a=!1)=>{if(!Ke)return;let p=Date.now();Se&&p<Le&&!a||(Se&&p>=Le&&(Se=!1),!(!a&&!lt)&&(p-je<tt||(je=p,K&&cancelAnimationFrame(K),K=requestAnimationFrame(()=>{Se||!Ke||(Ue=!0,z.scrollTop=z.scrollHeight,We=z.scrollTop,requestAnimationFrame(()=>{Ue=!1}),K=null)}))))},Et=null,sn=()=>te.querySelector("#vanilla-agent-scroll-container")||z,on=(a,p=500)=>{let E=a.scrollTop,N=a.clientHeight,k=a.scrollHeight,ee=k-E;if(E+N>=k-2||Math.abs(ee)<5)return;Et!==null&&(cancelAnimationFrame(Et),Et=null);let v=performance.now(),U=R=>1-Math.pow(1-R,3),O=R=>{let q=a.scrollHeight;q!==k&&(k=q,ee=k-E);let $e=R-v,xe=Math.min($e/p,1),re=U(xe),Oe=E+ee*re;a.scrollTop=Oe,xe<1?Et=requestAnimationFrame(O):(a.scrollTop=a.scrollHeight,Et=null)};Et=requestAnimationFrame(O)},rn=a=>{let p=new Map;a.forEach(E=>{let N=Ct.get(E.id);p.set(E.id,{streaming:E.streaming,role:E.role}),!N&&E.role==="assistant"&&s.emit("assistant:message",E),E.role==="assistant"&&(N!=null&&N.streaming)&&E.streaming===!1&&s.emit("assistant:complete",E)}),Ct.clear(),p.forEach((E,N)=>{Ct.set(N,E)})},Pt=(a,p,E)=>{a.innerHTML="";let N=document.createDocumentFragment();p.forEach(v=>{var $e,xe;let U=null,O=o.find(re=>!!(v.variant==="reasoning"&&re.renderReasoning||v.variant==="tool"&&re.renderToolCall||!v.variant&&re.renderMessage)),R=($e=t.layout)==null?void 0:$e.messages;if(O)if(v.variant==="reasoning"&&v.reasoning&&O.renderReasoning){if(!S)return;U=O.renderReasoning({message:v,defaultRenderer:()=>Wn(v),config:t})}else if(v.variant==="tool"&&v.toolCall&&O.renderToolCall){if(!Y)return;U=O.renderToolCall({message:v,defaultRenderer:()=>Ln(v,t),config:t})}else O.renderMessage&&(U=O.renderMessage({message:v,defaultRenderer:()=>{let re=tn(v,E,R);return v.role!=="user"&&Bn(re,v,t,F),re},config:t}));if(!U&&v.role==="assistant"&&!v.variant&&t.enableComponentStreaming!==!1&&Nn(v)){let Oe=Dn(v);if(Oe){let dt=On(Oe,{config:t,message:v,transform:E});if(dt){let oe=document.createElement("div");if(oe.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),oe.setAttribute("data-message-id",v.id),v.content&&v.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=E({text:v.content,message:v,streaming:!!v.streaming,raw:v.rawContent}),oe.appendChild(ct)}oe.appendChild(dt),U=oe}}}if(!U)if(v.variant==="reasoning"&&v.reasoning){if(!S)return;U=Wn(v)}else if(v.variant==="tool"&&v.toolCall){if(!Y)return;U=Ln(v,t)}else{let re=(xe=t.layout)==null?void 0:xe.messages;re!=null&&re.renderUserMessage&&v.role==="user"?U=re.renderUserMessage({message:v,config:t,streaming:!!v.streaming}):re!=null&&re.renderAssistantMessage&&v.role==="assistant"?U=re.renderAssistantMessage({message:v,config:t,streaming:!!v.streaming}):U=tn(v,E,re),v.role!=="user"&&U&&Bn(U,v,t,F)}let q=document.createElement("div");q.className="tvw-flex",v.role==="user"&&q.classList.add("tvw-justify-end"),q.appendChild(U),N.appendChild(q)});let k=p.some(v=>v.role==="assistant"&&v.streaming),ee=p[p.length-1],H=(ee==null?void 0:ee.role)==="assistant"&&!ee.streaming;if(lt&&p.some(v=>v.role==="user")&&!k&&!H){let v=cn(),U=document.createElement("div");U.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),U.appendChild(v);let O=document.createElement("div");O.className="tvw-flex",O.appendChild(U),N.appendChild(O)}a.appendChild(N),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let v=sn();on(v)})})},Ot=()=>{w&&(C?(te.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),A.classList.remove("tvw-scale-95","tvw-opacity-0"),A.classList.add("tvw-scale-100","tvw-opacity-100"),g?g.element.style.display="none":B&&(B.style.display="none")):(te.classList.add("tvw-pointer-events-none","tvw-opacity-0"),A.classList.remove("tvw-scale-100","tvw-opacity-100"),A.classList.add("tvw-scale-95","tvw-opacity-0"),g?g.element.style.display="":B&&(B.style.display="")))},nt=(a,p="user")=>{if(!w||C===a)return;let E=C;C=a,Ot(),C&&(we(),yt(!0));let N={open:C,source:p,timestamp:Date.now()};C&&!E?s.emit("widget:opened",N):!C&&E&&s.emit("widget:closed",N),s.emit("widget:state",{open:C,launcherEnabled:w,voiceActive:de.active,streaming:F.isStreaming()})},jt=a=>{ne.disabled=a,P.disabled=a,M&&(M.disabled=a),et.buttons.forEach(p=>{p.disabled=a})},Yt=()=>{var k,ee,H,v,U,O,R,q,$e,xe,re,Oe,dt,oe;vt.textContent=(ee=(k=t.copy)==null?void 0:k.welcomeTitle)!=null?ee:"Hello \u{1F44B}",bt.textContent=(v=(H=t.copy)==null?void 0:H.welcomeSubtitle)!=null?v:"Ask anything about your account or products.",ne.placeholder=(O=(U=t.copy)==null?void 0:U.inputPlaceholder)!=null?O:"How can I help...",((q=(R=t.sendButton)==null?void 0:R.useIcon)!=null?q:!1)||(P.textContent=(xe=($e=t.copy)==null?void 0:$e.sendButtonLabel)!=null?xe:"Send");let p=(Oe=(re=t.theme)==null?void 0:re.inputFontFamily)!=null?Oe:"sans-serif",E=(oe=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?oe:"400",N=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};ne.style.fontFamily=N(p),ne.style.fontWeight=E};F=new Gt(t,{onMessagesChanged(a){Pt(G,a,$),F&&(a.some(N=>N.role==="user")?et.render([],F,ne,a):et.render(t.suggestionChips,F,ne,a,t.suggestionChipsConfig)),yt(!lt),rn(a);let p=[...a].reverse().find(E=>E.role==="user");de.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Bt(a)},onStatusChanged(a){var N;let p=(N=t.statusIndicator)!=null?N:{},E=k=>{var ee,H,v,U;return k==="idle"?(ee=p.idleText)!=null?ee:ze.idle:k==="connecting"?(H=p.connectingText)!=null?H:ze.connecting:k==="connected"?(v=p.connectedText)!=null?v:ze.connected:k==="error"?(U=p.errorText)!=null?U:ze.error:ze[k]};Qe.textContent=E(a)},onStreamingChanged(a){lt=a,jt(a),F&&Pt(G,F.getMessages(),$),a||yt(!0)}}),u&&u.then(a=>{var p;a&&(a.metadata&&(l=Fn(a.metadata),b.syncFromMetadata()),(p=a.messages)!=null&&p.length&&F.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let Jt=a=>{a.preventDefault();let p=ne.value.trim();p&&(ne.value="",F.sendMessage(p))},Kt=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),P.click())},y=null,X=!1,se=null,fe=null,Re=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ie=(a="user")=>{var ee,H,v,U;if(X||F.isStreaming())return;let p=Re();if(!p)return;y=new p;let N=(H=((ee=t.voiceRecognition)!=null?ee:{}).pauseDuration)!=null?H:2e3;y.continuous=!0,y.interimResults=!0,y.lang="en-US";let k=ne.value;y.onresult=O=>{let R="",q="";for(let xe=0;xe<O.results.length;xe++){let re=O.results[xe],Oe=re[0].transcript;re.isFinal?R+=Oe+" ":q=Oe}let $e=k+R+q;ne.value=$e,se&&clearTimeout(se),(R||q)&&(se=window.setTimeout(()=>{let xe=ne.value.trim();xe&&y&&X&&(ce(),ne.value="",F.sendMessage(xe,{viaVoice:!0}))},N))},y.onerror=O=>{O.error!=="no-speech"&&ce()},y.onend=()=>{if(X){let O=ne.value.trim();O&&O!==k.trim()&&(ne.value="",F.sendMessage(O,{viaVoice:!0})),ce()}};try{if(y.start(),X=!0,de.active=!0,a!=="system"&&(de.manuallyDeactivated=!1),Lt(a),ve(),M){fe={backgroundColor:M.style.backgroundColor,color:M.style.color,borderColor:M.style.borderColor};let O=(v=t.voiceRecognition)!=null?v:{},R=(U=O.recordingBackgroundColor)!=null?U:"#ef4444",q=O.recordingIconColor,$e=O.recordingBorderColor;if(M.classList.add("tvw-voice-recording"),M.style.backgroundColor=R,q){M.style.color=q;let xe=M.querySelector("svg");xe&&xe.setAttribute("stroke",q)}$e&&(M.style.borderColor=$e),M.setAttribute("aria-label","Stop voice recognition")}}catch{ce("system")}},ce=(a="user")=>{if(X){if(X=!1,se&&(clearTimeout(se),se=null),y){try{y.stop()}catch{}y=null}if(de.active=!1,Lt(a),ve(),M){if(M.classList.remove("tvw-voice-recording"),fe){M.style.backgroundColor=fe.backgroundColor,M.style.color=fe.color,M.style.borderColor=fe.borderColor;let p=M.querySelector("svg");p&&p.setAttribute("stroke",fe.color||"currentColor"),fe=null}M.setAttribute("aria-label","Start voice recognition")}}},L=(a,p)=>{var Oe,dt,oe,ct,Ht,kt,Wt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let N=c("div","tvw-send-button-wrapper"),k=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");k.type="button",k.setAttribute("aria-label","Start voice recognition");let ee=(Oe=a==null?void 0:a.iconName)!=null?Oe:"mic",H=(dt=p==null?void 0:p.size)!=null?dt:"40px",v=(oe=a==null?void 0:a.iconSize)!=null?oe:H,U=parseFloat(v)||24,O=(ct=a==null?void 0:a.backgroundColor)!=null?ct:p==null?void 0:p.backgroundColor,R=(Ht=a==null?void 0:a.iconColor)!=null?Ht:p==null?void 0:p.textColor;k.style.width=v,k.style.height=v,k.style.minWidth=v,k.style.minHeight=v,k.style.fontSize="18px",k.style.lineHeight="1";let q=R||"currentColor",$e=ye(ee,U,q,1.5);$e?(k.appendChild($e),k.style.color=q):(k.textContent="\u{1F3A4}",k.style.color=q),O?k.style.backgroundColor=O:k.classList.add("tvw-bg-cw-primary"),R?k.style.color=R:!R&&!(p!=null&&p.textColor)&&k.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(k.style.borderWidth=a.borderWidth,k.style.borderStyle="solid"),a!=null&&a.borderColor&&(k.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(k.style.paddingLeft=a.paddingX,k.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(k.style.paddingTop=a.paddingY,k.style.paddingBottom=a.paddingY),N.appendChild(k);let xe=(kt=a==null?void 0:a.tooltipText)!=null?kt:"Start voice recognition";if(((Wt=a==null?void 0:a.showTooltip)!=null?Wt:!1)&&xe){let Nt=c("div","tvw-send-button-tooltip");Nt.textContent=xe,N.appendChild(Nt)}return{micButton:k,micButtonWrapper:N}},st=()=>{if(X){let a=ne.value.trim();de.manuallyDeactivated=!0,ve(),ce("user"),a&&(ne.value="",F.sendMessage(a))}else de.manuallyDeactivated=!1,ve(),Ie("user")};M&&(M.addEventListener("click",st),ke.push(()=>{ce("system"),M&&M.removeEventListener("click",st)}));let Z=s.on("assistant:complete",()=>{$t&&(de.active||de.manuallyDeactivated||$t==="assistant"&&!de.lastUserMessageWasVoice||setTimeout(()=>{!de.active&&!de.manuallyDeactivated&&Ie("auto")},600))});ke.push(Z);let x=()=>{nt(!C,"user")},g=null,B=null;if(w){let a=o.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:t,defaultRenderer:()=>Zt(t,x).element,onToggle:x});p&&(B=p)}B||(g=Zt(t,x))}g?n.appendChild(g.element):B&&n.appendChild(B),Ot(),et.render(t.suggestionChips,F,ne,void 0,t.suggestionChipsConfig),Yt(),jt(F.isStreaming()),yt(!0),wt();let we=()=>{var E,N,k,ee,H,v;let a=(N=(E=t.launcher)==null?void 0:E.sidebarMode)!=null?N:!1,p=a||((ee=(k=t.launcher)==null?void 0:k.fullHeight)!=null?ee:!1);if(!w){A.style.height="",A.style.width="";return}if(!a){let U=(v=(H=t==null?void 0:t.launcher)==null?void 0:H.width)!=null?v:t==null?void 0:t.launcherWidth,O=U!=null?U:"min(400px, calc(100vw - 24px))";A.style.width=O,A.style.maxWidth=O}if(!p){let U=window.innerHeight,R=Math.max(200,U-64),q=Math.min(640,R);A.style.height=`${q}px`}};we(),window.addEventListener("resize",we),ke.push(()=>window.removeEventListener("resize",we)),We=z.scrollTop;let Ae=()=>{let a=z.scrollTop,p=z.scrollHeight,E=z.clientHeight,N=p-a-E,k=Math.abs(a-We);if(We=a,!Ue&&!(k<=Mt)){if(!Ke&&N<pt){Se=!1,Ke=!0;return}Ke&&N>pt&&(Se=!0,Le=Date.now()+xt,Ke=!1)}};z.addEventListener("scroll",Ae,{passive:!0}),ke.push(()=>z.removeEventListener("scroll",Ae)),ke.push(()=>{K&&cancelAnimationFrame(K)});let Xe=()=>{D&&(qe&&(D.removeEventListener("click",qe),qe=null),w?(D.style.display="",qe=()=>{C=!1,Ot()},D.addEventListener("click",qe)):D.style.display="none")};Xe(),(()=>{let{clearChatButton:a}=ie;a&&a.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zt}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let E=i.clear();E instanceof Promise&&E.catch(N=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",N)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},b.syncFromMetadata()})})(),Ye.addEventListener("submit",Jt),ne.addEventListener("keydown",Kt),ke.push(()=>{Ye.removeEventListener("submit",Jt),ne.removeEventListener("keydown",Kt)}),ke.push(()=>{F.cancel()}),g?ke.push(()=>{g==null||g.destroy()}):B&&ke.push(()=>{B==null||B.remove()});let be={update(a){var Vn,Gn,Zn,Qn,es,ts,ns,ss,os,rs,is,as,ls,ds,cs,us,ps,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,Hs,ks,Rs,Is,$s,Ps,Os,Ns,Ds,Fs,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs;let p=t.toolCall;t={...t,...a},Sn(n,t),ft();let E=un.getForInstance(t.plugins);if(o.length=0,o.push(...E),w=(Gn=(Vn=t.launcher)==null?void 0:Vn.enabled)!=null?Gn:!0,_=(Qn=(Zn=t.launcher)==null?void 0:Zn.autoExpand)!=null?Qn:!1,S=(ts=(es=t.features)==null?void 0:es.showReasoning)!=null?ts:!0,Y=(ss=(ns=t.features)==null?void 0:ns.showToolCalls)!=null?ss:!0,((os=t.launcher)==null?void 0:os.enabled)===!1&&g&&(g.destroy(),g=null),((rs=t.launcher)==null?void 0:rs.enabled)===!1&&B&&(B.remove(),B=null),((is=t.launcher)==null?void 0:is.enabled)!==!1&&!g&&!B){let W=o.find(me=>me.renderLauncher);if(W!=null&&W.renderLauncher){let me=W.renderLauncher({config:t,defaultRenderer:()=>Zt(t,x).element,onToggle:x});me&&(B=me,n.appendChild(B))}B||(g=Zt(t,x),n.appendChild(g.element))}g&&g.update(t),ht&&((as=t.launcher)==null?void 0:as.title)!==void 0&&(ht.textContent=t.launcher.title),mt&&((ls=t.launcher)==null?void 0:ls.subtitle)!==void 0&&(mt.textContent=t.launcher.subtitle),w!==m?w?nt(_,"auto"):(C=!0,Ot()):_!==j&&nt(_,"auto"),j=_,m=w,we(),Xe(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&F&&Pt(G,F.getMessages(),$);let H=(ds=t.launcher)!=null?ds:{},v=(cs=H.headerIconHidden)!=null?cs:!1,U=H.headerIconName,O=(us=H.headerIconSize)!=null?us:"48px";if(he){let W=J.querySelector(".tvw-border-b-cw-divider"),me=W==null?void 0:W.querySelector(".tvw-flex-col");if(v)he.style.display="none",W&&me&&!W.contains(me)&&W.insertBefore(me,W.firstChild);else{if(he.style.display="",he.style.height=O,he.style.width=O,W&&me&&(W.contains(he)?he.nextSibling!==me&&(he.remove(),W.insertBefore(he,me)):W.insertBefore(he,me)),U){let Ee=parseFloat(O)||24,Ce=ye(U,Ee*.6,"#ffffff",2);Ce?he.replaceChildren(Ce):he.textContent=(ps=H.agentIconText)!=null?ps:"\u{1F4AC}"}else if(H.iconUrl){let Ee=he.querySelector("img");if(Ee)Ee.src=H.iconUrl,Ee.style.height=O,Ee.style.width=O;else{let Ce=document.createElement("img");Ce.src=H.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=O,Ce.style.width=O,he.replaceChildren(Ce)}}else{let Ee=he.querySelector("svg"),Ce=he.querySelector("img");(Ee||Ce)&&he.replaceChildren(),he.textContent=(gs=H.agentIconText)!=null?gs:"\u{1F4AC}"}let Q=he.querySelector("img");Q&&(Q.style.height=O,Q.style.width=O)}}if(D){let W=(hs=H.closeButtonSize)!=null?hs:"32px",me=(ms=H.closeButtonPlacement)!=null?ms:"inline";D.style.height=W,D.style.width=W;let{closeButtonWrapper:Q}=ie,Ee=me==="top-right",Ce=Q==null?void 0:Q.classList.contains("tvw-absolute");if(Q&&Ee!==Ce)if(Q.remove(),Ee)Q.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",J.style.position="relative",J.appendChild(Q);else{let ge=(ws=(fs=H.clearChat)==null?void 0:fs.placement)!=null?ws:"inline",Ge=(vs=(ys=H.clearChat)==null?void 0:ys.enabled)!=null?vs:!0;Q.className=Ge&&ge==="inline"?"":"tvw-ml-auto";let Ze=J.querySelector(".tvw-border-b-cw-divider");Ze&&Ze.appendChild(Q)}if(H.closeButtonColor?(D.style.color=H.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),H.closeButtonBackgroundColor?(D.style.backgroundColor=H.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),H.closeButtonBorderWidth||H.closeButtonBorderColor){let ge=H.closeButtonBorderWidth||"0px",Ge=H.closeButtonBorderColor||"transparent";D.style.border=`${ge} solid ${Ge}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");H.closeButtonBorderRadius?(D.style.borderRadius=H.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),H.closeButtonPaddingX?(D.style.paddingLeft=H.closeButtonPaddingX,D.style.paddingRight=H.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),H.closeButtonPaddingY?(D.style.paddingTop=H.closeButtonPaddingY,D.style.paddingBottom=H.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Ve=(bs=H.closeButtonIconName)!=null?bs:"x",Fe=(xs=H.closeButtonIconText)!=null?xs:"\xD7";D.innerHTML="";let ut=ye(Ve,"20px",H.closeButtonColor||"",2);ut?D.appendChild(ut):D.textContent=Fe;let Rt=(Cs=H.closeButtonTooltipText)!=null?Cs:"Close chat",Te=(Ss=H.closeButtonShowTooltip)!=null?Ss:!0;if(D.setAttribute("aria-label",Rt),Q&&(Q._cleanupTooltip&&(Q._cleanupTooltip(),delete Q._cleanupTooltip),Te&&Rt)){let ge=null,Ge=()=>{if(ge||!D)return;ge=c("div","tvw-clear-chat-tooltip"),ge.textContent=Rt;let _t=c("div");_t.className="tvw-clear-chat-tooltip-arrow",ge.appendChild(_t);let fn=D.getBoundingClientRect();ge.style.position="fixed",ge.style.left=`${fn.left+fn.width/2}px`,ge.style.top=`${fn.top-8}px`,ge.style.transform="translate(-50%, -100%)",document.body.appendChild(ge)},Ze=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};Q.addEventListener("mouseenter",Ge),Q.addEventListener("mouseleave",Ze),D.addEventListener("focus",Ge),D.addEventListener("blur",Ze),Q._cleanupTooltip=()=>{Ze(),Q&&(Q.removeEventListener("mouseenter",Ge),Q.removeEventListener("mouseleave",Ze)),D&&(D.removeEventListener("focus",Ge),D.removeEventListener("blur",Ze))}}}let{clearChatButton:R,clearChatButtonWrapper:q}=ie;if(R){let W=(As=H.clearChat)!=null?As:{},me=(Ts=W.enabled)!=null?Ts:!0,Q=(Es=W.placement)!=null?Es:"inline";if(q){q.style.display=me?"":"none";let Ee=Q==="top-right",Ce=q.classList.contains("tvw-absolute");if(Ee!==Ce&&me){if(q.remove(),Ee)q.className="tvw-absolute tvw-top-4 tvw-z-50",q.style.right="48px",J.style.position="relative",J.appendChild(q);else{q.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",q.style.right="";let Fe=J.querySelector(".tvw-border-b-cw-divider"),ut=ie.closeButtonWrapper;Fe&&ut&&ut.parentElement===Fe?Fe.insertBefore(q,ut):Fe&&Fe.appendChild(q)}let Ve=ie.closeButtonWrapper;Ve&&!Ve.classList.contains("tvw-absolute")&&(Ee?Ve.classList.add("tvw-ml-auto"):Ve.classList.remove("tvw-ml-auto"))}}if(me){let Ee=(Ws=W.size)!=null?Ws:"32px";R.style.height=Ee,R.style.width=Ee;let Ce=(Ms=W.iconName)!=null?Ms:"refresh-cw",Ve=(Ls=W.iconColor)!=null?Ls:"";R.innerHTML="";let Fe=ye(Ce,"20px",Ve||"",2);if(Fe&&R.appendChild(Fe),Ve?(R.style.color=Ve,R.classList.remove("tvw-text-cw-muted")):(R.style.color="",R.classList.add("tvw-text-cw-muted")),W.backgroundColor?(R.style.backgroundColor=W.backgroundColor,R.classList.remove("hover:tvw-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let Te=W.borderWidth||"0px",ge=W.borderColor||"transparent";R.style.border=`${Te} solid ${ge}`,R.classList.remove("tvw-border-none")}else R.style.border="",R.classList.add("tvw-border-none");W.borderRadius?(R.style.borderRadius=W.borderRadius,R.classList.remove("tvw-rounded-full")):(R.style.borderRadius="",R.classList.add("tvw-rounded-full")),W.paddingX?(R.style.paddingLeft=W.paddingX,R.style.paddingRight=W.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),W.paddingY?(R.style.paddingTop=W.paddingY,R.style.paddingBottom=W.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let ut=(Bs=W.tooltipText)!=null?Bs:"Clear chat",Rt=(Hs=W.showTooltip)!=null?Hs:!0;if(R.setAttribute("aria-label",ut),q&&(q._cleanupTooltip&&(q._cleanupTooltip(),delete q._cleanupTooltip),Rt&&ut)){let Te=null,ge=()=>{if(Te||!R)return;Te=c("div","tvw-clear-chat-tooltip"),Te.textContent=ut;let Ze=c("div");Ze.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(Ze);let _t=R.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${_t.left+_t.width/2}px`,Te.style.top=`${_t.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},Ge=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};q.addEventListener("mouseenter",ge),q.addEventListener("mouseleave",Ge),R.addEventListener("focus",ge),R.addEventListener("blur",Ge),q._cleanupTooltip=()=>{Ge(),q&&(q.removeEventListener("mouseenter",ge),q.removeEventListener("mouseleave",Ge)),R&&(R.removeEventListener("focus",ge),R.removeEventListener("blur",Ge))}}}}let $e=t.actionParsers&&t.actionParsers.length?t.actionParsers:[pn],xe=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Ut.message,Ut.messageAndClick];b=gn({parsers:$e,handlers:xe,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),$=bo(t,b),F.updateConfig(t),Pt(G,F.getMessages(),$),et.render(t.suggestionChips,F,ne,void 0,t.suggestionChipsConfig),Yt(),jt(F.isStreaming());let re=((ks=t.voiceRecognition)==null?void 0:ks.enabled)===!0,Oe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=re&&Oe;if(Ye.classList.remove("tvw-gap-1","tvw-gap-3"),Ye.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),re&&Oe)if(!M||!Me){let W=L(t.voiceRecognition,t.sendButton);W&&(M=W.micButton,Me=W.micButtonWrapper,Ye.insertBefore(Me,_e),M.addEventListener("click",st),M.disabled=F.isStreaming())}else{let W=(Rs=t.voiceRecognition)!=null?Rs:{},me=(Is=t.sendButton)!=null?Is:{},Q=($s=W.iconName)!=null?$s:"mic",Ee=(Ps=me.size)!=null?Ps:"40px",Ce=(Os=W.iconSize)!=null?Os:Ee,Ve=parseFloat(Ce)||24;M.style.width=Ce,M.style.height=Ce,M.style.minWidth=Ce,M.style.minHeight=Ce;let Fe=(Ds=(Ns=W.iconColor)!=null?Ns:me.textColor)!=null?Ds:"currentColor";M.innerHTML="";let ut=ye(Q,Ve,Fe,2);ut?M.appendChild(ut):M.textContent="\u{1F3A4}";let Rt=(Fs=W.backgroundColor)!=null?Fs:me.backgroundColor;Rt?(M.style.backgroundColor=Rt,M.classList.remove("tvw-bg-cw-primary")):(M.style.backgroundColor="",M.classList.add("tvw-bg-cw-primary")),Fe?(M.style.color=Fe,M.classList.remove("tvw-text-white")):!Fe&&!me.textColor&&(M.style.color="",M.classList.add("tvw-text-white")),W.borderWidth?(M.style.borderWidth=W.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),W.borderColor?M.style.borderColor=W.borderColor:M.style.borderColor="",W.paddingX?(M.style.paddingLeft=W.paddingX,M.style.paddingRight=W.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),W.paddingY?(M.style.paddingTop=W.paddingY,M.style.paddingBottom=W.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Te=Me==null?void 0:Me.querySelector(".tvw-send-button-tooltip"),ge=(js=W.tooltipText)!=null?js:"Start voice recognition";if(((_s=W.showTooltip)!=null?_s:!1)&&ge)if(Te)Te.textContent=ge,Te.style.display="";else{let Ze=document.createElement("div");Ze.className="tvw-send-button-tooltip",Ze.textContent=ge,Me==null||Me.insertBefore(Ze,M)}else Te&&(Te.style.display="none");Me.style.display="",M.disabled=F.isStreaming()}else M&&Me&&(Me.style.display="none",X&&ce());let oe=(qs=t.sendButton)!=null?qs:{},ct=(Us=oe.useIcon)!=null?Us:!1,Ht=(zs=oe.iconText)!=null?zs:"\u2191",kt=oe.iconName,Wt=(Ys=oe.tooltipText)!=null?Ys:"Send message",Nt=(Js=oe.showTooltip)!=null?Js:!1,Dt=(Ks=oe.size)!=null?Ks:"40px",an=oe.backgroundColor,At=oe.textColor;if(ct){if(P.style.width=Dt,P.style.height=Dt,P.style.minWidth=Dt,P.style.minHeight=Dt,P.style.fontSize="18px",P.style.lineHeight="1",P.innerHTML="",kt){let W=parseFloat(Dt)||24,me=At&&typeof At=="string"&&At.trim()?At.trim():"currentColor",Q=ye(kt,W,me,2);Q?(P.appendChild(Q),P.style.color=me):(P.textContent=Ht,At?P.style.color=At:P.classList.add("tvw-text-white"))}else P.textContent=Ht,At?P.style.color=At:P.classList.add("tvw-text-white");P.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",an?(P.style.backgroundColor=an,P.classList.remove("tvw-bg-cw-primary")):P.classList.add("tvw-bg-cw-primary")}else P.textContent=(Vs=(Xs=t.copy)==null?void 0:Xs.sendButtonLabel)!=null?Vs:"Send",P.style.width="",P.style.height="",P.style.minWidth="",P.style.minHeight="",P.style.fontSize="",P.style.lineHeight="",P.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",an?(P.style.backgroundColor=an,P.classList.remove("tvw-bg-cw-accent")):P.classList.add("tvw-bg-cw-accent"),At?P.style.color=At:P.classList.add("tvw-text-white");oe.borderWidth?(P.style.borderWidth=oe.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),oe.borderColor?P.style.borderColor=oe.borderColor:P.style.borderColor="",oe.paddingX?(P.style.paddingLeft=oe.paddingX,P.style.paddingRight=oe.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),oe.paddingY?(P.style.paddingTop=oe.paddingY,P.style.paddingBottom=oe.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let Xt=_e==null?void 0:_e.querySelector(".tvw-send-button-tooltip");if(Nt&&Wt)if(Xt)Xt.textContent=Wt,Xt.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=Wt,_e==null||_e.insertBefore(W,P)}else Xt&&(Xt.style.display="none");let Vt=(Gs=t.statusIndicator)!=null?Gs:{},So=(Zs=Vt.visible)!=null?Zs:!0;if(Qe.style.display=So?"":"none",F){let W=F.getStatus(),me=Q=>{var Ee,Ce,Ve,Fe;return Q==="idle"?(Ee=Vt.idleText)!=null?Ee:ze.idle:Q==="connecting"?(Ce=Vt.connectingText)!=null?Ce:ze.connecting:Q==="connected"?(Ve=Vt.connectedText)!=null?Ve:ze.connected:Q==="error"?(Fe=Vt.errorText)!=null?Fe:ze.error:ze[Q]};Qe.textContent=me(W)}},open(){w&&nt(!0,"api")},close(){w&&nt(!1,"api")},toggle(){w&&nt(!C,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zt}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},b.syncFromMetadata()},setMessage(a){return!ne||F.isStreaming()?!1:(!C&&w&&nt(!0,"system"),ne.value=a,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(F.isStreaming())return!1;let p=(a==null?void 0:a.trim())||ne.value.trim();return p?(!C&&w&&nt(!0,"system"),ne.value="",F.sendMessage(p),!0):!1},startVoiceRecognition(){return X||F.isStreaming()||!Re()?!1:(!C&&w&&nt(!0,"system"),de.manuallyDeactivated=!1,ve(),Ie("user"),!0)},stopVoiceRecognition(){return X?(de.manuallyDeactivated=!0,ve(),ce("user"),!0):!1},injectTestMessage(a){!C&&w&&nt(!0,"system"),F.injectTestEvent(a)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,p){return s.on(a,p)},off(a,p){s.off(a,p)},isOpen(){return w&&C},isVoiceActive(){return de.active},getState(){return{open:w&&C,launcherEnabled:w,voiceActive:de.active,streaming:F.isStreaming()}},destroy(){ke.forEach(a=>a()),te.remove(),g==null||g.destroy(),B==null||B.remove(),qe&&D.removeEventListener("click",qe)}};if((((Xn=r==null?void 0:r.debugTools)!=null?Xn:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:be,getMessages:be.getMessages,getStatus:be.getStatus,getMetadata:be.getPersistentMetadata,updateMetadata:be.updatePersistentMetadata,clearHistory:()=>be.clearChat(),setVoiceActive:E=>E?be.startVoiceRecognition():be.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ke.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return be};var _n={},Go=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},Zo=()=>{try{if(typeof _n!="undefined"&&_n.url)return new URL("../widget.css",_n.url).href}catch{}return null},xo=n=>{let e=Zo(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let o=t.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},Co=n=>{var h,d,T,f;let e=Go(n.target),r=document.createElement("div");r.className="vanilla-agent-host";let t=(T=(d=(h=n.config)==null?void 0:h.launcher)==null?void 0:d.enabled)!=null?T:!0;t||(r.style.height="100%",r.style.display="flex",r.style.flexDirection="column"),e.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let b=r.attachShadow({mode:"open"});i=b,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),b.appendChild(s),xo(b)}else i=r,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),xo(r);let l=jn(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let u={...l,host:r,destroy(){l.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=u),u};function Qo(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function hn(n){var e,r;return(r=(e=n.parserType)!=null?e:Qo(n.streamParser))!=null?r:"plain"}function er(n,e="esm"){let r={...n};return delete r.postprocessMessage,delete r.initialMessages,e==="esm"?tr(r):e==="script-installer"?or(r):e==="script-advanced"?ir(r):e==="react-component"?nr(r):e==="react-advanced"?sr(r):rr(r)}function tr(n){let e=hn(n),r=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
55
+ `}};ft();let ke=[],et=mo(le),qe=null,F,lt=!1,Ke=!0,We=0,je=0,K=null,Se=!1,Le=0,Ue=!1,tt=125,xt=2e3,Mt=5,pt=50,Ct=new Map,de={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},$t=(Kn=(Jn=t.voiceRecognition)==null?void 0:Jn.autoResume)!=null?Kn:!1,Lt=a=>{s.emit("voice:state",{active:de.active,source:a,timestamp:Date.now()})},ve=()=>{d(a=>({...a,voiceState:{active:de.active,timestamp:Date.now(),manuallyDeactivated:de.manuallyDeactivated}}))},wt=()=>{var N,k;if(((N=t.voiceRecognition)==null?void 0:N.enabled)===!1)return;let a=Fn(l.voiceState),p=!!a.active,E=Number((k=a.timestamp)!=null?k:0);de.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-E<Vo&&setTimeout(()=>{de.active||(de.manuallyDeactivated=!1,Ie("restore"))},1e3)},St=()=>F?vo(F.getMessages()).filter(a=>!a.__skipPersist):[];function Bt(a){if(!(i!=null&&i.save))return;let E={messages:a?vo(a):F?St():[],metadata:l};try{let N=i.save(E);N instanceof Promise&&N.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(N){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",N)}}let yt=(a=!1)=>{if(!Ke)return;let p=Date.now();Se&&p<Le&&!a||(Se&&p>=Le&&(Se=!1),!(!a&&!lt)&&(p-je<tt||(je=p,K&&cancelAnimationFrame(K),K=requestAnimationFrame(()=>{Se||!Ke||(Ue=!0,z.scrollTop=z.scrollHeight,We=z.scrollTop,requestAnimationFrame(()=>{Ue=!1}),K=null)}))))},Et=null,sn=()=>te.querySelector("#vanilla-agent-scroll-container")||z,on=(a,p=500)=>{let E=a.scrollTop,N=a.clientHeight,k=a.scrollHeight,ee=k-E;if(E+N>=k-2||Math.abs(ee)<5)return;Et!==null&&(cancelAnimationFrame(Et),Et=null);let v=performance.now(),U=R=>1-Math.pow(1-R,3),O=R=>{let q=a.scrollHeight;q!==k&&(k=q,ee=k-E);let $e=R-v,xe=Math.min($e/p,1),re=U(xe),Oe=E+ee*re;a.scrollTop=Oe,xe<1?Et=requestAnimationFrame(O):(a.scrollTop=a.scrollHeight,Et=null)};Et=requestAnimationFrame(O)},rn=a=>{let p=new Map;a.forEach(E=>{let N=Ct.get(E.id);p.set(E.id,{streaming:E.streaming,role:E.role}),!N&&E.role==="assistant"&&s.emit("assistant:message",E),E.role==="assistant"&&(N!=null&&N.streaming)&&E.streaming===!1&&s.emit("assistant:complete",E)}),Ct.clear(),p.forEach((E,N)=>{Ct.set(N,E)})},Pt=(a,p,E)=>{a.innerHTML="";let N=document.createDocumentFragment();p.forEach(v=>{var $e,xe;let U=null,O=o.find(re=>!!(v.variant==="reasoning"&&re.renderReasoning||v.variant==="tool"&&re.renderToolCall||!v.variant&&re.renderMessage)),R=($e=t.layout)==null?void 0:$e.messages;if(O)if(v.variant==="reasoning"&&v.reasoning&&O.renderReasoning){if(!S)return;U=O.renderReasoning({message:v,defaultRenderer:()=>Wn(v),config:t})}else if(v.variant==="tool"&&v.toolCall&&O.renderToolCall){if(!Y)return;U=O.renderToolCall({message:v,defaultRenderer:()=>Ln(v,t),config:t})}else O.renderMessage&&(U=O.renderMessage({message:v,defaultRenderer:()=>{let re=tn(v,E,R);return v.role!=="user"&&Bn(re,v,t,F),re},config:t}));if(!U&&v.role==="assistant"&&!v.variant&&t.enableComponentStreaming!==!1&&Nn(v)){let Oe=Dn(v);if(Oe){let dt=On(Oe,{config:t,message:v,transform:E});if(dt){let oe=document.createElement("div");if(oe.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),oe.setAttribute("data-message-id",v.id),v.content&&v.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=E({text:v.content,message:v,streaming:!!v.streaming,raw:v.rawContent}),oe.appendChild(ct)}oe.appendChild(dt),U=oe}}}if(!U)if(v.variant==="reasoning"&&v.reasoning){if(!S)return;U=Wn(v)}else if(v.variant==="tool"&&v.toolCall){if(!Y)return;U=Ln(v,t)}else{let re=(xe=t.layout)==null?void 0:xe.messages;re!=null&&re.renderUserMessage&&v.role==="user"?U=re.renderUserMessage({message:v,config:t,streaming:!!v.streaming}):re!=null&&re.renderAssistantMessage&&v.role==="assistant"?U=re.renderAssistantMessage({message:v,config:t,streaming:!!v.streaming}):U=tn(v,E,re),v.role!=="user"&&U&&Bn(U,v,t,F)}let q=document.createElement("div");q.className="tvw-flex",v.role==="user"&&q.classList.add("tvw-justify-end"),q.appendChild(U),N.appendChild(q)});let k=p.some(v=>v.role==="assistant"&&v.streaming),ee=p[p.length-1],H=(ee==null?void 0:ee.role)==="assistant"&&!ee.streaming;if(lt&&p.some(v=>v.role==="user")&&!k&&!H){let v=cn(),U=document.createElement("div");U.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),U.appendChild(v);let O=document.createElement("div");O.className="tvw-flex",O.appendChild(U),N.appendChild(O)}a.appendChild(N),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let v=sn();on(v)})})},Ot=()=>{w&&(C?(te.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),A.classList.remove("tvw-scale-95","tvw-opacity-0"),A.classList.add("tvw-scale-100","tvw-opacity-100"),g?g.element.style.display="none":B&&(B.style.display="none")):(te.classList.add("tvw-pointer-events-none","tvw-opacity-0"),A.classList.remove("tvw-scale-100","tvw-opacity-100"),A.classList.add("tvw-scale-95","tvw-opacity-0"),g?g.element.style.display="":B&&(B.style.display="")))},nt=(a,p="user")=>{if(!w||C===a)return;let E=C;C=a,Ot(),C&&(we(),yt(!0));let N={open:C,source:p,timestamp:Date.now()};C&&!E?s.emit("widget:opened",N):!C&&E&&s.emit("widget:closed",N),s.emit("widget:state",{open:C,launcherEnabled:w,voiceActive:de.active,streaming:F.isStreaming()})},jt=a=>{P.disabled=a,M&&(M.disabled=a),et.buttons.forEach(p=>{p.disabled=a})},Yt=()=>{var k,ee,H,v,U,O,R,q,$e,xe,re,Oe,dt,oe;vt.textContent=(ee=(k=t.copy)==null?void 0:k.welcomeTitle)!=null?ee:"Hello \u{1F44B}",bt.textContent=(v=(H=t.copy)==null?void 0:H.welcomeSubtitle)!=null?v:"Ask anything about your account or products.",se.placeholder=(O=(U=t.copy)==null?void 0:U.inputPlaceholder)!=null?O:"How can I help...",((q=(R=t.sendButton)==null?void 0:R.useIcon)!=null?q:!1)||(P.textContent=(xe=($e=t.copy)==null?void 0:$e.sendButtonLabel)!=null?xe:"Send");let p=(Oe=(re=t.theme)==null?void 0:re.inputFontFamily)!=null?Oe:"sans-serif",E=(oe=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?oe:"400",N=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=N(p),se.style.fontWeight=E};F=new Gt(t,{onMessagesChanged(a){Pt(G,a,$),F&&(a.some(N=>N.role==="user")?et.render([],F,se,a):et.render(t.suggestionChips,F,se,a,t.suggestionChipsConfig)),yt(!lt),rn(a);let p=[...a].reverse().find(E=>E.role==="user");de.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Bt(a)},onStatusChanged(a){var N;let p=(N=t.statusIndicator)!=null?N:{},E=k=>{var ee,H,v,U;return k==="idle"?(ee=p.idleText)!=null?ee:ze.idle:k==="connecting"?(H=p.connectingText)!=null?H:ze.connecting:k==="connected"?(v=p.connectedText)!=null?v:ze.connected:k==="error"?(U=p.errorText)!=null?U:ze.error:ze[k]};Qe.textContent=E(a)},onStreamingChanged(a){lt=a,jt(a),F&&Pt(G,F.getMessages(),$),a||yt(!0)}}),u&&u.then(a=>{var p;a&&(a.metadata&&(l=Fn(a.metadata),b.syncFromMetadata()),(p=a.messages)!=null&&p.length&&F.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let Jt=a=>{a.preventDefault();let p=se.value.trim();p&&(se.value="",F.sendMessage(p))},Kt=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),P.click())},y=null,X=!1,ne=null,fe=null,Re=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ie=(a="user")=>{var ee,H,v,U;if(X||F.isStreaming())return;let p=Re();if(!p)return;y=new p;let N=(H=((ee=t.voiceRecognition)!=null?ee:{}).pauseDuration)!=null?H:2e3;y.continuous=!0,y.interimResults=!0,y.lang="en-US";let k=se.value;y.onresult=O=>{let R="",q="";for(let xe=0;xe<O.results.length;xe++){let re=O.results[xe],Oe=re[0].transcript;re.isFinal?R+=Oe+" ":q=Oe}let $e=k+R+q;se.value=$e,ne&&clearTimeout(ne),(R||q)&&(ne=window.setTimeout(()=>{let xe=se.value.trim();xe&&y&&X&&(ce(),se.value="",F.sendMessage(xe,{viaVoice:!0}))},N))},y.onerror=O=>{O.error!=="no-speech"&&ce()},y.onend=()=>{if(X){let O=se.value.trim();O&&O!==k.trim()&&(se.value="",F.sendMessage(O,{viaVoice:!0})),ce()}};try{if(y.start(),X=!0,de.active=!0,a!=="system"&&(de.manuallyDeactivated=!1),Lt(a),ve(),M){fe={backgroundColor:M.style.backgroundColor,color:M.style.color,borderColor:M.style.borderColor};let O=(v=t.voiceRecognition)!=null?v:{},R=(U=O.recordingBackgroundColor)!=null?U:"#ef4444",q=O.recordingIconColor,$e=O.recordingBorderColor;if(M.classList.add("tvw-voice-recording"),M.style.backgroundColor=R,q){M.style.color=q;let xe=M.querySelector("svg");xe&&xe.setAttribute("stroke",q)}$e&&(M.style.borderColor=$e),M.setAttribute("aria-label","Stop voice recognition")}}catch{ce("system")}},ce=(a="user")=>{if(X){if(X=!1,ne&&(clearTimeout(ne),ne=null),y){try{y.stop()}catch{}y=null}if(de.active=!1,Lt(a),ve(),M){if(M.classList.remove("tvw-voice-recording"),fe){M.style.backgroundColor=fe.backgroundColor,M.style.color=fe.color,M.style.borderColor=fe.borderColor;let p=M.querySelector("svg");p&&p.setAttribute("stroke",fe.color||"currentColor"),fe=null}M.setAttribute("aria-label","Start voice recognition")}}},L=(a,p)=>{var Oe,dt,oe,ct,Ht,kt,Wt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let N=c("div","tvw-send-button-wrapper"),k=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");k.type="button",k.setAttribute("aria-label","Start voice recognition");let ee=(Oe=a==null?void 0:a.iconName)!=null?Oe:"mic",H=(dt=p==null?void 0:p.size)!=null?dt:"40px",v=(oe=a==null?void 0:a.iconSize)!=null?oe:H,U=parseFloat(v)||24,O=(ct=a==null?void 0:a.backgroundColor)!=null?ct:p==null?void 0:p.backgroundColor,R=(Ht=a==null?void 0:a.iconColor)!=null?Ht:p==null?void 0:p.textColor;k.style.width=v,k.style.height=v,k.style.minWidth=v,k.style.minHeight=v,k.style.fontSize="18px",k.style.lineHeight="1";let q=R||"currentColor",$e=ye(ee,U,q,1.5);$e?(k.appendChild($e),k.style.color=q):(k.textContent="\u{1F3A4}",k.style.color=q),O?k.style.backgroundColor=O:k.classList.add("tvw-bg-cw-primary"),R?k.style.color=R:!R&&!(p!=null&&p.textColor)&&k.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(k.style.borderWidth=a.borderWidth,k.style.borderStyle="solid"),a!=null&&a.borderColor&&(k.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(k.style.paddingLeft=a.paddingX,k.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(k.style.paddingTop=a.paddingY,k.style.paddingBottom=a.paddingY),N.appendChild(k);let xe=(kt=a==null?void 0:a.tooltipText)!=null?kt:"Start voice recognition";if(((Wt=a==null?void 0:a.showTooltip)!=null?Wt:!1)&&xe){let Nt=c("div","tvw-send-button-tooltip");Nt.textContent=xe,N.appendChild(Nt)}return{micButton:k,micButtonWrapper:N}},st=()=>{if(X){let a=se.value.trim();de.manuallyDeactivated=!0,ve(),ce("user"),a&&(se.value="",F.sendMessage(a))}else de.manuallyDeactivated=!1,ve(),Ie("user")};M&&(M.addEventListener("click",st),ke.push(()=>{ce("system"),M&&M.removeEventListener("click",st)}));let Z=s.on("assistant:complete",()=>{$t&&(de.active||de.manuallyDeactivated||$t==="assistant"&&!de.lastUserMessageWasVoice||setTimeout(()=>{!de.active&&!de.manuallyDeactivated&&Ie("auto")},600))});ke.push(Z);let x=()=>{nt(!C,"user")},g=null,B=null;if(w){let a=o.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:t,defaultRenderer:()=>Zt(t,x).element,onToggle:x});p&&(B=p)}B||(g=Zt(t,x))}g?n.appendChild(g.element):B&&n.appendChild(B),Ot(),et.render(t.suggestionChips,F,se,void 0,t.suggestionChipsConfig),Yt(),jt(F.isStreaming()),yt(!0),wt();let we=()=>{var E,N,k,ee,H,v;let a=(N=(E=t.launcher)==null?void 0:E.sidebarMode)!=null?N:!1,p=a||((ee=(k=t.launcher)==null?void 0:k.fullHeight)!=null?ee:!1);if(!w){A.style.height="",A.style.width="";return}if(!a){let U=(v=(H=t==null?void 0:t.launcher)==null?void 0:H.width)!=null?v:t==null?void 0:t.launcherWidth,O=U!=null?U:"min(400px, calc(100vw - 24px))";A.style.width=O,A.style.maxWidth=O}if(!p){let U=window.innerHeight,R=Math.max(200,U-64),q=Math.min(640,R);A.style.height=`${q}px`}};we(),window.addEventListener("resize",we),ke.push(()=>window.removeEventListener("resize",we)),We=z.scrollTop;let Ae=()=>{let a=z.scrollTop,p=z.scrollHeight,E=z.clientHeight,N=p-a-E,k=Math.abs(a-We);if(We=a,!Ue&&!(k<=Mt)){if(!Ke&&N<pt){Se=!1,Ke=!0;return}Ke&&N>pt&&(Se=!0,Le=Date.now()+xt,Ke=!1)}};z.addEventListener("scroll",Ae,{passive:!0}),ke.push(()=>z.removeEventListener("scroll",Ae)),ke.push(()=>{K&&cancelAnimationFrame(K)});let Xe=()=>{D&&(qe&&(D.removeEventListener("click",qe),qe=null),w?(D.style.display="",qe=()=>{C=!1,Ot()},D.addEventListener("click",qe)):D.style.display="none")};Xe(),(()=>{let{clearChatButton:a}=ie;a&&a.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zt}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let E=i.clear();E instanceof Promise&&E.catch(N=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",N)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},b.syncFromMetadata()})})(),Ye.addEventListener("submit",Jt),se.addEventListener("keydown",Kt),ke.push(()=>{Ye.removeEventListener("submit",Jt),se.removeEventListener("keydown",Kt)}),ke.push(()=>{F.cancel()}),g?ke.push(()=>{g==null||g.destroy()}):B&&ke.push(()=>{B==null||B.remove()});let be={update(a){var Vn,Gn,Zn,Qn,es,ts,ns,ss,os,rs,is,as,ls,ds,cs,us,ps,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,Hs,ks,Rs,Is,$s,Ps,Os,Ns,Ds,Fs,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs;let p=t.toolCall;t={...t,...a},Sn(n,t),ft();let E=un.getForInstance(t.plugins);if(o.length=0,o.push(...E),w=(Gn=(Vn=t.launcher)==null?void 0:Vn.enabled)!=null?Gn:!0,_=(Qn=(Zn=t.launcher)==null?void 0:Zn.autoExpand)!=null?Qn:!1,S=(ts=(es=t.features)==null?void 0:es.showReasoning)!=null?ts:!0,Y=(ss=(ns=t.features)==null?void 0:ns.showToolCalls)!=null?ss:!0,((os=t.launcher)==null?void 0:os.enabled)===!1&&g&&(g.destroy(),g=null),((rs=t.launcher)==null?void 0:rs.enabled)===!1&&B&&(B.remove(),B=null),((is=t.launcher)==null?void 0:is.enabled)!==!1&&!g&&!B){let W=o.find(me=>me.renderLauncher);if(W!=null&&W.renderLauncher){let me=W.renderLauncher({config:t,defaultRenderer:()=>Zt(t,x).element,onToggle:x});me&&(B=me,n.appendChild(B))}B||(g=Zt(t,x),n.appendChild(g.element))}g&&g.update(t),ht&&((as=t.launcher)==null?void 0:as.title)!==void 0&&(ht.textContent=t.launcher.title),mt&&((ls=t.launcher)==null?void 0:ls.subtitle)!==void 0&&(mt.textContent=t.launcher.subtitle),w!==m?w?nt(_,"auto"):(C=!0,Ot()):_!==j&&nt(_,"auto"),j=_,m=w,we(),Xe(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&F&&Pt(G,F.getMessages(),$);let H=(ds=t.launcher)!=null?ds:{},v=(cs=H.headerIconHidden)!=null?cs:!1,U=H.headerIconName,O=(us=H.headerIconSize)!=null?us:"48px";if(he){let W=J.querySelector(".tvw-border-b-cw-divider"),me=W==null?void 0:W.querySelector(".tvw-flex-col");if(v)he.style.display="none",W&&me&&!W.contains(me)&&W.insertBefore(me,W.firstChild);else{if(he.style.display="",he.style.height=O,he.style.width=O,W&&me&&(W.contains(he)?he.nextSibling!==me&&(he.remove(),W.insertBefore(he,me)):W.insertBefore(he,me)),U){let Ee=parseFloat(O)||24,Ce=ye(U,Ee*.6,"#ffffff",2);Ce?he.replaceChildren(Ce):he.textContent=(ps=H.agentIconText)!=null?ps:"\u{1F4AC}"}else if(H.iconUrl){let Ee=he.querySelector("img");if(Ee)Ee.src=H.iconUrl,Ee.style.height=O,Ee.style.width=O;else{let Ce=document.createElement("img");Ce.src=H.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=O,Ce.style.width=O,he.replaceChildren(Ce)}}else{let Ee=he.querySelector("svg"),Ce=he.querySelector("img");(Ee||Ce)&&he.replaceChildren(),he.textContent=(gs=H.agentIconText)!=null?gs:"\u{1F4AC}"}let Q=he.querySelector("img");Q&&(Q.style.height=O,Q.style.width=O)}}if(D){let W=(hs=H.closeButtonSize)!=null?hs:"32px",me=(ms=H.closeButtonPlacement)!=null?ms:"inline";D.style.height=W,D.style.width=W;let{closeButtonWrapper:Q}=ie,Ee=me==="top-right",Ce=Q==null?void 0:Q.classList.contains("tvw-absolute");if(Q&&Ee!==Ce)if(Q.remove(),Ee)Q.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",J.style.position="relative",J.appendChild(Q);else{let ge=(ws=(fs=H.clearChat)==null?void 0:fs.placement)!=null?ws:"inline",Ge=(vs=(ys=H.clearChat)==null?void 0:ys.enabled)!=null?vs:!0;Q.className=Ge&&ge==="inline"?"":"tvw-ml-auto";let Ze=J.querySelector(".tvw-border-b-cw-divider");Ze&&Ze.appendChild(Q)}if(H.closeButtonColor?(D.style.color=H.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),H.closeButtonBackgroundColor?(D.style.backgroundColor=H.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),H.closeButtonBorderWidth||H.closeButtonBorderColor){let ge=H.closeButtonBorderWidth||"0px",Ge=H.closeButtonBorderColor||"transparent";D.style.border=`${ge} solid ${Ge}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");H.closeButtonBorderRadius?(D.style.borderRadius=H.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),H.closeButtonPaddingX?(D.style.paddingLeft=H.closeButtonPaddingX,D.style.paddingRight=H.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),H.closeButtonPaddingY?(D.style.paddingTop=H.closeButtonPaddingY,D.style.paddingBottom=H.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Ve=(bs=H.closeButtonIconName)!=null?bs:"x",Fe=(xs=H.closeButtonIconText)!=null?xs:"\xD7";D.innerHTML="";let ut=ye(Ve,"20px",H.closeButtonColor||"",2);ut?D.appendChild(ut):D.textContent=Fe;let Rt=(Cs=H.closeButtonTooltipText)!=null?Cs:"Close chat",Te=(Ss=H.closeButtonShowTooltip)!=null?Ss:!0;if(D.setAttribute("aria-label",Rt),Q&&(Q._cleanupTooltip&&(Q._cleanupTooltip(),delete Q._cleanupTooltip),Te&&Rt)){let ge=null,Ge=()=>{if(ge||!D)return;ge=c("div","tvw-clear-chat-tooltip"),ge.textContent=Rt;let _t=c("div");_t.className="tvw-clear-chat-tooltip-arrow",ge.appendChild(_t);let fn=D.getBoundingClientRect();ge.style.position="fixed",ge.style.left=`${fn.left+fn.width/2}px`,ge.style.top=`${fn.top-8}px`,ge.style.transform="translate(-50%, -100%)",document.body.appendChild(ge)},Ze=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};Q.addEventListener("mouseenter",Ge),Q.addEventListener("mouseleave",Ze),D.addEventListener("focus",Ge),D.addEventListener("blur",Ze),Q._cleanupTooltip=()=>{Ze(),Q&&(Q.removeEventListener("mouseenter",Ge),Q.removeEventListener("mouseleave",Ze)),D&&(D.removeEventListener("focus",Ge),D.removeEventListener("blur",Ze))}}}let{clearChatButton:R,clearChatButtonWrapper:q}=ie;if(R){let W=(As=H.clearChat)!=null?As:{},me=(Ts=W.enabled)!=null?Ts:!0,Q=(Es=W.placement)!=null?Es:"inline";if(q){q.style.display=me?"":"none";let Ee=Q==="top-right",Ce=q.classList.contains("tvw-absolute");if(Ee!==Ce&&me){if(q.remove(),Ee)q.className="tvw-absolute tvw-top-4 tvw-z-50",q.style.right="48px",J.style.position="relative",J.appendChild(q);else{q.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",q.style.right="";let Fe=J.querySelector(".tvw-border-b-cw-divider"),ut=ie.closeButtonWrapper;Fe&&ut&&ut.parentElement===Fe?Fe.insertBefore(q,ut):Fe&&Fe.appendChild(q)}let Ve=ie.closeButtonWrapper;Ve&&!Ve.classList.contains("tvw-absolute")&&(Ee?Ve.classList.add("tvw-ml-auto"):Ve.classList.remove("tvw-ml-auto"))}}if(me){let Ee=(Ws=W.size)!=null?Ws:"32px";R.style.height=Ee,R.style.width=Ee;let Ce=(Ms=W.iconName)!=null?Ms:"refresh-cw",Ve=(Ls=W.iconColor)!=null?Ls:"";R.innerHTML="";let Fe=ye(Ce,"20px",Ve||"",2);if(Fe&&R.appendChild(Fe),Ve?(R.style.color=Ve,R.classList.remove("tvw-text-cw-muted")):(R.style.color="",R.classList.add("tvw-text-cw-muted")),W.backgroundColor?(R.style.backgroundColor=W.backgroundColor,R.classList.remove("hover:tvw-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let Te=W.borderWidth||"0px",ge=W.borderColor||"transparent";R.style.border=`${Te} solid ${ge}`,R.classList.remove("tvw-border-none")}else R.style.border="",R.classList.add("tvw-border-none");W.borderRadius?(R.style.borderRadius=W.borderRadius,R.classList.remove("tvw-rounded-full")):(R.style.borderRadius="",R.classList.add("tvw-rounded-full")),W.paddingX?(R.style.paddingLeft=W.paddingX,R.style.paddingRight=W.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),W.paddingY?(R.style.paddingTop=W.paddingY,R.style.paddingBottom=W.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let ut=(Bs=W.tooltipText)!=null?Bs:"Clear chat",Rt=(Hs=W.showTooltip)!=null?Hs:!0;if(R.setAttribute("aria-label",ut),q&&(q._cleanupTooltip&&(q._cleanupTooltip(),delete q._cleanupTooltip),Rt&&ut)){let Te=null,ge=()=>{if(Te||!R)return;Te=c("div","tvw-clear-chat-tooltip"),Te.textContent=ut;let Ze=c("div");Ze.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(Ze);let _t=R.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${_t.left+_t.width/2}px`,Te.style.top=`${_t.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},Ge=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};q.addEventListener("mouseenter",ge),q.addEventListener("mouseleave",Ge),R.addEventListener("focus",ge),R.addEventListener("blur",Ge),q._cleanupTooltip=()=>{Ge(),q&&(q.removeEventListener("mouseenter",ge),q.removeEventListener("mouseleave",Ge)),R&&(R.removeEventListener("focus",ge),R.removeEventListener("blur",Ge))}}}}let $e=t.actionParsers&&t.actionParsers.length?t.actionParsers:[pn],xe=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Ut.message,Ut.messageAndClick];b=gn({parsers:$e,handlers:xe,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),$=bo(t,b),F.updateConfig(t),Pt(G,F.getMessages(),$),et.render(t.suggestionChips,F,se,void 0,t.suggestionChipsConfig),Yt(),jt(F.isStreaming());let re=((ks=t.voiceRecognition)==null?void 0:ks.enabled)===!0,Oe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=re&&Oe;if(Ye.classList.remove("tvw-gap-1","tvw-gap-3"),Ye.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),re&&Oe)if(!M||!Me){let W=L(t.voiceRecognition,t.sendButton);W&&(M=W.micButton,Me=W.micButtonWrapper,Ye.insertBefore(Me,_e),M.addEventListener("click",st),M.disabled=F.isStreaming())}else{let W=(Rs=t.voiceRecognition)!=null?Rs:{},me=(Is=t.sendButton)!=null?Is:{},Q=($s=W.iconName)!=null?$s:"mic",Ee=(Ps=me.size)!=null?Ps:"40px",Ce=(Os=W.iconSize)!=null?Os:Ee,Ve=parseFloat(Ce)||24;M.style.width=Ce,M.style.height=Ce,M.style.minWidth=Ce,M.style.minHeight=Ce;let Fe=(Ds=(Ns=W.iconColor)!=null?Ns:me.textColor)!=null?Ds:"currentColor";M.innerHTML="";let ut=ye(Q,Ve,Fe,2);ut?M.appendChild(ut):M.textContent="\u{1F3A4}";let Rt=(Fs=W.backgroundColor)!=null?Fs:me.backgroundColor;Rt?(M.style.backgroundColor=Rt,M.classList.remove("tvw-bg-cw-primary")):(M.style.backgroundColor="",M.classList.add("tvw-bg-cw-primary")),Fe?(M.style.color=Fe,M.classList.remove("tvw-text-white")):!Fe&&!me.textColor&&(M.style.color="",M.classList.add("tvw-text-white")),W.borderWidth?(M.style.borderWidth=W.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),W.borderColor?M.style.borderColor=W.borderColor:M.style.borderColor="",W.paddingX?(M.style.paddingLeft=W.paddingX,M.style.paddingRight=W.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),W.paddingY?(M.style.paddingTop=W.paddingY,M.style.paddingBottom=W.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Te=Me==null?void 0:Me.querySelector(".tvw-send-button-tooltip"),ge=(js=W.tooltipText)!=null?js:"Start voice recognition";if(((_s=W.showTooltip)!=null?_s:!1)&&ge)if(Te)Te.textContent=ge,Te.style.display="";else{let Ze=document.createElement("div");Ze.className="tvw-send-button-tooltip",Ze.textContent=ge,Me==null||Me.insertBefore(Ze,M)}else Te&&(Te.style.display="none");Me.style.display="",M.disabled=F.isStreaming()}else M&&Me&&(Me.style.display="none",X&&ce());let oe=(qs=t.sendButton)!=null?qs:{},ct=(Us=oe.useIcon)!=null?Us:!1,Ht=(zs=oe.iconText)!=null?zs:"\u2191",kt=oe.iconName,Wt=(Ys=oe.tooltipText)!=null?Ys:"Send message",Nt=(Js=oe.showTooltip)!=null?Js:!1,Dt=(Ks=oe.size)!=null?Ks:"40px",an=oe.backgroundColor,At=oe.textColor;if(ct){if(P.style.width=Dt,P.style.height=Dt,P.style.minWidth=Dt,P.style.minHeight=Dt,P.style.fontSize="18px",P.style.lineHeight="1",P.innerHTML="",kt){let W=parseFloat(Dt)||24,me=At&&typeof At=="string"&&At.trim()?At.trim():"currentColor",Q=ye(kt,W,me,2);Q?(P.appendChild(Q),P.style.color=me):(P.textContent=Ht,At?P.style.color=At:P.classList.add("tvw-text-white"))}else P.textContent=Ht,At?P.style.color=At:P.classList.add("tvw-text-white");P.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",an?(P.style.backgroundColor=an,P.classList.remove("tvw-bg-cw-primary")):P.classList.add("tvw-bg-cw-primary")}else P.textContent=(Vs=(Xs=t.copy)==null?void 0:Xs.sendButtonLabel)!=null?Vs:"Send",P.style.width="",P.style.height="",P.style.minWidth="",P.style.minHeight="",P.style.fontSize="",P.style.lineHeight="",P.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",an?(P.style.backgroundColor=an,P.classList.remove("tvw-bg-cw-accent")):P.classList.add("tvw-bg-cw-accent"),At?P.style.color=At:P.classList.add("tvw-text-white");oe.borderWidth?(P.style.borderWidth=oe.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),oe.borderColor?P.style.borderColor=oe.borderColor:P.style.borderColor="",oe.paddingX?(P.style.paddingLeft=oe.paddingX,P.style.paddingRight=oe.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),oe.paddingY?(P.style.paddingTop=oe.paddingY,P.style.paddingBottom=oe.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let Xt=_e==null?void 0:_e.querySelector(".tvw-send-button-tooltip");if(Nt&&Wt)if(Xt)Xt.textContent=Wt,Xt.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=Wt,_e==null||_e.insertBefore(W,P)}else Xt&&(Xt.style.display="none");let Vt=(Gs=t.statusIndicator)!=null?Gs:{},So=(Zs=Vt.visible)!=null?Zs:!0;if(Qe.style.display=So?"":"none",F){let W=F.getStatus(),me=Q=>{var Ee,Ce,Ve,Fe;return Q==="idle"?(Ee=Vt.idleText)!=null?Ee:ze.idle:Q==="connecting"?(Ce=Vt.connectingText)!=null?Ce:ze.connecting:Q==="connected"?(Ve=Vt.connectedText)!=null?Ve:ze.connected:Q==="error"?(Fe=Vt.errorText)!=null?Fe:ze.error:ze[Q]};Qe.textContent=me(W)}},open(){w&&nt(!0,"api")},close(){w&&nt(!1,"api")},toggle(){w&&nt(!C,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zt}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},b.syncFromMetadata()},setMessage(a){return!se||F.isStreaming()?!1:(!C&&w&&nt(!0,"system"),se.value=a,se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(F.isStreaming())return!1;let p=(a==null?void 0:a.trim())||se.value.trim();return p?(!C&&w&&nt(!0,"system"),se.value="",F.sendMessage(p),!0):!1},startVoiceRecognition(){return X||F.isStreaming()||!Re()?!1:(!C&&w&&nt(!0,"system"),de.manuallyDeactivated=!1,ve(),Ie("user"),!0)},stopVoiceRecognition(){return X?(de.manuallyDeactivated=!0,ve(),ce("user"),!0):!1},injectTestMessage(a){!C&&w&&nt(!0,"system"),F.injectTestEvent(a)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,p){return s.on(a,p)},off(a,p){s.off(a,p)},isOpen(){return w&&C},isVoiceActive(){return de.active},getState(){return{open:w&&C,launcherEnabled:w,voiceActive:de.active,streaming:F.isStreaming()}},destroy(){ke.forEach(a=>a()),te.remove(),g==null||g.destroy(),B==null||B.remove(),qe&&D.removeEventListener("click",qe)}};if((((Xn=r==null?void 0:r.debugTools)!=null?Xn:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:be,getMessages:be.getMessages,getStatus:be.getStatus,getMetadata:be.getPersistentMetadata,updateMetadata:be.updatePersistentMetadata,clearHistory:()=>be.clearChat(),setVoiceActive:E=>E?be.startVoiceRecognition():be.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ke.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return be};var _n={},Go=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},Zo=()=>{try{if(typeof _n!="undefined"&&_n.url)return new URL("../widget.css",_n.url).href}catch{}return null},xo=n=>{let e=Zo(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let o=t.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},Co=n=>{var h,d,T,f;let e=Go(n.target),r=document.createElement("div");r.className="vanilla-agent-host";let t=(T=(d=(h=n.config)==null?void 0:h.launcher)==null?void 0:d.enabled)!=null?T:!0;t||(r.style.height="100%",r.style.display="flex",r.style.flexDirection="column"),e.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let b=r.attachShadow({mode:"open"});i=b,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),b.appendChild(s),xo(b)}else i=r,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),xo(r);let l=jn(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let u={...l,host:r,destroy(){l.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=u),u};function Qo(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function hn(n){var e,r;return(r=(e=n.parserType)!=null?e:Qo(n.streamParser))!=null?r:"plain"}function er(n,e="esm"){let r={...n};return delete r.postprocessMessage,delete r.initialMessages,e==="esm"?tr(r):e==="script-installer"?or(r):e==="script-advanced"?ir(r):e==="react-component"?nr(r):e==="react-advanced"?sr(r):rr(r)}function tr(n){let e=hn(n),r=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
56
56
  `)}function nr(n){let e=hn(n),r=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
57
57
  `)}function sr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","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('.vanilla-agent-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 n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"?e.push(` ${r}: ${t},`):typeof t=="number"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,t])=>{e.push(` ${r}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
58
58
  `)}function or(n){let e=hn(n),r=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`