vanilla-agent 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{marked as Co}from"marked";Co.setOptions({breaks:!0});var So=t=>Co.parse(t),nn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),zo=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),bo=t=>`%%FORM_PLACEHOLDER_${t}%%`,_o=(t,n)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=bo(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=bo(n.length);return n.push({token:s,type:o}),s}),r},Oo=t=>{let n=[],r=_o(t,n),e=So(r);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${zo(s)}"></div>`;e=e.replace(a,v)}),e};import{parse as To,STR as Ao,OBJ as Mo}from"partial-json";var on=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},$o=t=>{var a,d;let n=(a=t.completedAt)!=null?a:Date.now(),r=(d=t.startedAt)!=null?d:n,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Wo=t=>t.status==="complete"?$o(t):t.status==="pending"?"Waiting":"",jo=t=>{var o,s,a;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a: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 Eo=t=>t.status==="complete"?jo(t):"Using tool...",Vo=()=>{let t=null,n=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,d=e.match(a);if(d&&d[1])try{return d[1].replace(/\\n/g,`
3
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return d[1]}return null};return{getExtractedText:()=>t,processChunk:async e=>{if(e.length<=n)return t!==null?{text:t,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(t=s),n=e.length,t!==null?{text:t,raw:e}:null},close:async()=>{}}},Gt=t=>{try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},rn=()=>{let t={processChunk:n=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},sn=()=>{var n;let t=Vo();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(n=t.close)==null?void 0:n.bind(t)}},an=()=>{let t=null,n=0;return{getExtractedText:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t!==null?{text:t,raw:r}:null;try{let o=To(r,Ao|Mo);o&&typeof o=="object"&&typeof o.text=="string"&&(t=o.text)}catch{}return n=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Uo=t=>{let n=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;if(s.action)switch(s.action){case"nav_then_click":return s.on_load_text||s.text||null;case"message":case"message_and_click":case"checkout":return s.text||null;default:return s.text||s.display_text||s.message||null}return s.text||s.display_text||s.message||s.content||null});return{getExtractedText:()=>n,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let d=To(s,Ao|Mo),v=o(d);v!==null&&(n=v)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},ln=()=>{let t=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let e=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(t=e[1],{text:t,raw:n}):null},getExtractedText:()=>t}};var Ko="https://api.travrse.ai/v1/dispatch";function Xo(t){switch(t){case"json":return an;case"regex-json":return sn;case"xml":return ln;case"plain":default:return rn}}var Kt=class{constructor(n={}){this.config=n;var r,e,o;this.apiUrl=(r=n.apiUrl)!=null?r:Ko,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(e=n.streamParser)!=null?e:Xo(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware}async dispatch(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch body",o);let s=await fetch(this.apiUrl,{method:"POST",headers:this.headers,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(n){let e={messages:n.slice().sort((o,s)=>{let a=new Date(o.createdAt).getTime(),d=new Date(s.createdAt).getTime();return a-d}).map(o=>({role:o.role,content: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 a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async streamResponse(n,r){var Dt,Z,E,rt,bt,qt,st,se,L,ye,C,X,ze,ut,Qe,P,Ct,_e,gt,Ne,Ue,q,xe,Wt,J,it,Ut,mt,St,ae,Et,Lt,at,zt,_t,kt,ft,lt,Ot,$t,jt,wt,ht,Oe,Tt,Bt,Rt,Ht,De,$e,dt,et,It,vt,Xe;let e=n.getReader(),o=new TextDecoder,s="",a=Date.now(),d=0,v=()=>a+d++,z=m=>{let $=m.reasoning?{...m.reasoning,chunks:[...m.reasoning.chunks]}:void 0,G=m.toolCall?{...m.toolCall,chunks:m.toolCall.chunks?[...m.toolCall.chunks]:void 0}:void 0,me=m.tools?m.tools.map(_=>({..._,chunks:_.chunks?[..._.chunks]:void 0})):void 0;return{...m,reasoning:$,toolCall:G,tools:me}},g=m=>{r({type:"message",message:z(m)})},F=null,I=new Map,B=new Map,h={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},R=m=>{if(m==null)return null;try{return String(m)}catch{return null}},x=m=>{var $,G,me,_,be;return R((be=(_=(me=(G=($=m.stepId)!=null?$:m.step_id)!=null?G:m.step)!=null?me:m.parentId)!=null?_:m.flowStepId)!=null?be:m.flow_step_id)},A=m=>{var $,G,me,_,be,ue,y;return R((y=(ue=(be=(_=(me=(G=($=m.callId)!=null?$:m.call_id)!=null?G:m.requestId)!=null?me:m.request_id)!=null?_:m.toolCallId)!=null?be:m.tool_call_id)!=null?ue:m.stepId)!=null?y:m.step_id)},p=()=>F||(F={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:v()},g(F),F),ke=(m,$)=>{h.lastId=$,m&&h.byStep.set(m,$)},re=(m,$)=>{var be;let G=(be=m.reasoningId)!=null?be:m.id,me=x(m);if(G){let ue=String(G);return ke(me,ue),ue}if(me){let ue=h.byStep.get(me);if(ue)return h.lastId=ue,ue}if(h.lastId&&!$)return h.lastId;if(!$)return null;let _=`reason-${v()}`;return ke(me,_),_},Fe=m=>{let $=I.get(m);if($)return $;let G={id:`reason-${m}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:v(),reasoning:{id:m,status:"streaming",chunks:[]}};return I.set(m,G),g(G),G},Be=(m,$)=>{Q.lastId=$,m&&Q.byCall.set(m,$)},he=(m,$)=>{var be;let G=(be=m.toolId)!=null?be:m.id,me=A(m);if(G){let ue=String(G);return Be(me,ue),ue}if(me){let ue=Q.byCall.get(me);if(ue)return Q.lastId=ue,ue}if(Q.lastId&&!$)return Q.lastId;if(!$)return null;let _=`tool-${v()}`;return Be(me,_),_},ee=m=>{let $=B.get(m);if($)return $;let G={id:`tool-${m}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:v(),toolCall:{id:m,status:"pending"}};return B.set(m,G),g(G),G},Ae=m=>{if(typeof m=="number"&&Number.isFinite(m))return m;if(typeof m=="string"){let $=Number(m);if(!Number.isNaN($)&&Number.isFinite($))return $;let G=Date.parse(m);if(!Number.isNaN(G))return G}return Date.now()},ve=m=>{if(typeof m=="string")return m;if(m==null)return"";try{return JSON.stringify(m)}catch{return String(m)}},Y=new Map,ne=new Map;for(;;){let{done:m,value:$}=await e.read();if(m)break;s+=o.decode($,{stream:!0});let G=s.split(`
1
+ import{marked as Mo}from"marked";Mo.setOptions({breaks:!0});var Wo=t=>Mo.parse(t),rn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),jo=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ao=t=>`%%FORM_PLACEHOLDER_${t}%%`,Vo=(t,n)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Ao(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=Ao(n.length);return n.push({token:s,type:o}),s}),r},Uo=t=>{let n=[],r=Vo(t,n),e=Wo(r);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),b=`<div class="tvw-form-directive" data-tv-form="${jo(s)}"></div>`;e=e.replace(a,b)}),e};import{parse as Eo,STR as Lo,OBJ as ko}from"partial-json";var sn=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Ko=t=>{var a,c;let n=(a=t.completedAt)!=null?a:Date.now(),r=(c=t.startedAt)!=null?c:n,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Bo=t=>t.status==="complete"?Ko(t):t.status==="pending"?"Waiting":"",Xo=t=>{var o,s,a;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a: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 Ro=t=>t.status==="complete"?Xo(t):"Using tool...",Yo=()=>{let t=null,n=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,c=e.match(a);if(c&&c[1])try{return c[1].replace(/\\n/g,`
3
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return c[1]}return null};return{getExtractedText:()=>t,processChunk:async e=>{if(e.length<=n)return t!==null?{text:t,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(t=s),n=e.length,t!==null?{text:t,raw:e}:null},close:async()=>{}}},Qt=t=>{try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},an=()=>{let t={processChunk:n=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},ln=()=>{var n;let t=Yo();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(n=t.close)==null?void 0:n.bind(t)}},dn=()=>{let t=null,n=0;return{getExtractedText:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t!==null?{text:t,raw:r}:null;try{let o=Eo(r,Lo|ko);o&&typeof o=="object"&&typeof o.text=="string"&&(t=o.text)}catch{}return n=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Jo=t=>{let n=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;if(s.action)switch(s.action){case"nav_then_click":return s.on_load_text||s.text||null;case"message":case"message_and_click":case"checkout":return s.text||null;default:return s.text||s.display_text||s.message||null}return s.text||s.display_text||s.message||s.content||null});return{getExtractedText:()=>n,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let c=Eo(s,Lo|ko),b=o(c);b!==null&&(n=b)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},cn=()=>{let t=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let e=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(t=e[1],{text:t,raw:n}):null},getExtractedText:()=>t}};var Go="https://api.travrse.ai/v1/dispatch";function Zo(t){switch(t){case"json":return dn;case"regex-json":return ln;case"xml":return cn;case"plain":default:return an}}var Ut=class{constructor(n={}){this.config=n;var r,e,o;this.apiUrl=(r=n.apiUrl)!=null?r:Go,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(e=n.streamParser)!=null?e:Zo(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware}async dispatch(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch body",o);let s=await fetch(this.apiUrl,{method:"POST",headers:this.headers,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(n){let e={messages:n.slice().sort((o,s)=>{let a=new Date(o.createdAt).getTime(),c=new Date(s.createdAt).getTime();return a-c}).map(o=>({role:o.role,content: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 a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async streamResponse(n,r){var Ht,J,E,ot,yt,It,rt,oe,L,we,Pt,he,S,Ne,_e,dt,st,R,ct,Te,Ze,O,ie,ut,U,Ke,Vt,bt,Ft,Nt,xt,re,Tt,At,it,Dt,qt,Mt,ft,at,zt,_t,Ot,wt,ht,Oe,Ct,Wt,Et,Lt,De,$e,lt,Qe,kt;let e=n.getReader(),o=new TextDecoder,s="",a=Date.now(),c=0,b=()=>a+c++,z=f=>{let _=f.reasoning?{...f.reasoning,chunks:[...f.reasoning.chunks]}:void 0,X=f.toolCall?{...f.toolCall,chunks:f.toolCall.chunks?[...f.toolCall.chunks]:void 0}:void 0,ce=f.tools?f.tools.map(Ae=>({...Ae,chunks:Ae.chunks?[...Ae.chunks]:void 0})):void 0;return{...f,reasoning:_,toolCall:X,tools:ce}},g=f=>{r({type:"message",message:z(f)})},F=null,H=new Map,B=new Map,y={lastId:null,byStep:new Map},G={lastId:null,byCall:new Map},I=f=>{if(f==null)return null;try{return String(f)}catch{return null}},x=f=>{var _,X,ce,Ae,Le;return I((Le=(Ae=(ce=(X=(_=f.stepId)!=null?_:f.step_id)!=null?X:f.step)!=null?ce:f.parentId)!=null?Ae:f.flowStepId)!=null?Le:f.flow_step_id)},M=f=>{var _,X,ce,Ae,Le,D,v;return I((v=(D=(Le=(Ae=(ce=(X=(_=f.callId)!=null?_:f.call_id)!=null?X:f.requestId)!=null?ce:f.request_id)!=null?Ae:f.toolCallId)!=null?Le:f.tool_call_id)!=null?D:f.stepId)!=null?v:f.step_id)},m=()=>F||(F={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:b()},g(F),F),ke=(f,_)=>{y.lastId=_,f&&y.byStep.set(f,_)},ne=(f,_)=>{var Le;let X=(Le=f.reasoningId)!=null?Le:f.id,ce=x(f);if(X){let D=String(X);return ke(ce,D),D}if(ce){let D=y.byStep.get(ce);if(D)return y.lastId=D,D}if(y.lastId&&!_)return y.lastId;if(!_)return null;let Ae=`reason-${b()}`;return ke(ce,Ae),Ae},Fe=f=>{let _=H.get(f);if(_)return _;let X={id:`reason-${f}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:b(),reasoning:{id:f,status:"streaming",chunks:[]}};return H.set(f,X),g(X),X},Be=(f,_)=>{G.lastId=_,f&&G.byCall.set(f,_)},me=(f,_)=>{var Le;let X=(Le=f.toolId)!=null?Le:f.id,ce=M(f);if(X){let D=String(X);return Be(ce,D),D}if(ce){let D=G.byCall.get(ce);if(D)return G.lastId=D,D}if(G.lastId&&!_)return G.lastId;if(!_)return null;let Ae=`tool-${b()}`;return Be(ce,Ae),Ae},Z=f=>{let _=B.get(f);if(_)return _;let X={id:`tool-${f}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:b(),toolCall:{id:f,status:"pending"}};return B.set(f,X),g(X),X},Se=f=>{if(typeof f=="number"&&Number.isFinite(f))return f;if(typeof f=="string"){let _=Number(f);if(!Number.isNaN(_)&&Number.isFinite(_))return _;let X=Date.parse(f);if(!Number.isNaN(X))return X}return Date.now()},fe=f=>{if(typeof f=="string")return f;if(f==null)return"";try{return JSON.stringify(f)}catch{return String(f)}},K=new Map,Q=new Map;for(;;){let{done:f,value:_}=await e.read();if(f)break;s+=o.decode(_,{stream:!0});let X=s.split(`
4
4
 
5
- `);s=(Dt=G.pop())!=null?Dt:"";for(let me of G){let _=me.split(`
6
- `),be="message",ue="";for(let N of _)N.startsWith("event:")?be=N.replace("event:","").trim():N.startsWith("data:")&&(ue+=N.replace("data:","").trim());if(!ue)continue;let y;try{y=JSON.parse(ue)}catch(N){r({type:"error",error:N instanceof Error?N:new Error("Failed to parse chat stream payload")});continue}let Ye=be!=="message"?be:(Z=y.type)!=null?Z:"message";if(Ye==="reason_start"){let N=(E=re(y,!0))!=null?E:`reason-${v()}`,f=Fe(N);f.reasoning=(rt=f.reasoning)!=null?rt:{id:N,status:"streaming",chunks:[]},f.reasoning.startedAt=(qt=f.reasoning.startedAt)!=null?qt:Ae((bt=y.startedAt)!=null?bt:y.timestamp),f.reasoning.completedAt=void 0,f.reasoning.durationMs=void 0,f.streaming=!0,f.reasoning.status="streaming",g(f)}else if(Ye==="reason_chunk"){let N=(se=(st=re(y,!1))!=null?st:re(y,!0))!=null?se:`reason-${v()}`,f=Fe(N);f.reasoning=(L=f.reasoning)!=null?L:{id:N,status:"streaming",chunks:[]},f.reasoning.startedAt=(C=f.reasoning.startedAt)!=null?C:Ae((ye=y.startedAt)!=null?ye:y.timestamp);let c=(ut=(ze=(X=y.reasoningText)!=null?X:y.text)!=null?ze:y.delta)!=null?ut:"";if(c&&y.hidden!==!0&&f.reasoning.chunks.push(String(c)),f.reasoning.status=y.done?"complete":"streaming",y.done){f.reasoning.completedAt=Ae((Qe=y.completedAt)!=null?Qe:y.timestamp);let H=(P=f.reasoning.startedAt)!=null?P:Date.now();f.reasoning.durationMs=Math.max(0,((Ct=f.reasoning.completedAt)!=null?Ct:Date.now())-H)}f.streaming=f.reasoning.status!=="complete",g(f)}else if(Ye==="reason_complete"){let N=(gt=(_e=re(y,!1))!=null?_e:re(y,!0))!=null?gt:`reason-${v()}`,f=I.get(N);if(f!=null&&f.reasoning){f.reasoning.status="complete",f.reasoning.completedAt=Ae((Ne=y.completedAt)!=null?Ne:y.timestamp);let H=(Ue=f.reasoning.startedAt)!=null?Ue:Date.now();f.reasoning.durationMs=Math.max(0,((q=f.reasoning.completedAt)!=null?q:Date.now())-H),f.streaming=!1,g(f)}let c=x(y);c&&h.byStep.delete(c)}else if(Ye==="tool_start"){let N=(xe=he(y,!0))!=null?xe:`tool-${v()}`,f=ee(N),c=(Wt=f.toolCall)!=null?Wt:{id:N,status:"pending"};c.name=(J=y.toolName)!=null?J:c.name,c.status="running",y.args!==void 0&&(c.args=y.args),c.startedAt=(Ut=c.startedAt)!=null?Ut:Ae((it=y.startedAt)!=null?it:y.timestamp),c.completedAt=void 0,c.durationMs=void 0,f.toolCall=c,f.streaming=!0,g(f)}else if(Ye==="tool_chunk"){let N=(St=(mt=he(y,!1))!=null?mt:he(y,!0))!=null?St:`tool-${v()}`,f=ee(N),c=(ae=f.toolCall)!=null?ae:{id:N,status:"running"};c.startedAt=(Lt=c.startedAt)!=null?Lt:Ae((Et=y.startedAt)!=null?Et:y.timestamp);let H=(_t=(zt=(at=y.text)!=null?at:y.delta)!=null?zt:y.message)!=null?_t:"";H&&(c.chunks=(kt=c.chunks)!=null?kt:[],c.chunks.push(String(H))),c.status="running",f.toolCall=c,f.streaming=!0,g(f)}else if(Ye==="tool_complete"){let N=(lt=(ft=he(y,!1))!=null?ft:he(y,!0))!=null?lt:`tool-${v()}`,f=ee(N),c=(Ot=f.toolCall)!=null?Ot:{id:N,status:"running"};if(c.status="complete",y.result!==void 0&&(c.result=y.result),typeof y.duration=="number"&&(c.duration=y.duration),c.completedAt=Ae(($t=y.completedAt)!=null?$t:y.timestamp),typeof y.duration=="number")c.durationMs=y.duration;else{let le=(jt=c.startedAt)!=null?jt:Date.now();c.durationMs=Math.max(0,((wt=c.completedAt)!=null?wt:Date.now())-le)}f.toolCall=c,f.streaming=!1,g(f);let H=A(y);H&&Q.byCall.delete(H)}else if(Ye==="step_chunk"){let N=y.stepType,f=y.executionType;if(N==="tool"||f==="context")continue;let c=p(),H=(Tt=(Oe=(ht=y.text)!=null?ht:y.delta)!=null?Oe:y.content)!=null?Tt:"";if(H){let de=((Bt=ne.get(c.id))!=null?Bt:"")+H;c.rawContent=de,Y.has(c.id)||Y.set(c.id,this.createStreamParser());let ge=Y.get(c.id),Re=de.trim().startsWith("{")||de.trim().startsWith("[");if(Re&&ne.set(c.id,de),ge.__isPlainTextParser===!0){c.content+=H,ne.delete(c.id),Y.delete(c.id),c.rawContent=void 0,g(c);continue}let ce=ge.processChunk(de);if(ce instanceof Promise)ce.then(j=>{var fe;let ie=typeof j=="string"?j:(fe=j==null?void 0:j.text)!=null?fe:null;if(ie!==null&&ie.trim()!==""){let Ce=F;Ce&&Ce.id===c.id&&(Ce.content=ie,g(Ce))}else if(!Re&&!de.trim().startsWith("<")){let Ce=F;Ce&&Ce.id===c.id&&(Ce.content+=H,ne.delete(Ce.id),Y.delete(Ce.id),Ce.rawContent=void 0,g(Ce))}}).catch(()=>{c.content+=H,ne.delete(c.id),Y.delete(c.id),c.rawContent=void 0,g(c)});else{let j=typeof ce=="string"?ce:(Rt=ce==null?void 0:ce.text)!=null?Rt:null;j!==null&&j.trim()!==""?(c.content=j,g(c)):!Re&&!de.trim().startsWith("<")&&(c.content+=H,ne.delete(c.id),Y.delete(c.id),c.rawContent=void 0,g(c))}}if(y.isComplete){let le=(De=(Ht=y.result)==null?void 0:Ht.response)!=null?De:c.content;if(le){let de=ne.get(c.id),ge=de!=null?de:ve(le);c.rawContent=ge;let Re=Y.get(c.id),Me=null;if(Re&&(Me=Re.getExtractedText(),Me===null&&(Me=Gt(ge)),Me===null)){let j=Re.processChunk(ge);j instanceof Promise?j.then(ie=>{var Ce;let fe=typeof ie=="string"?ie:(Ce=ie==null?void 0:ie.text)!=null?Ce:null;if(fe!==null){let He=F;He&&He.id===c.id&&(He.content=fe,He.streaming=!1,g(He))}}):Me=typeof j=="string"?j:($e=j==null?void 0:j.text)!=null?$e:null}Me!==null&&Me.trim()!==""?c.content=Me:ne.has(c.id)||(c.content=ve(le));let ce=Y.get(c.id);if(ce){let j=(dt=ce.close)==null?void 0:dt.call(ce);j instanceof Promise&&j.catch(()=>{}),Y.delete(c.id)}ne.delete(c.id),c.streaming=!1,g(c)}}}else if(Ye==="step_complete"){let N=y.stepType,f=y.executionType;if(N==="tool"||f==="context")continue;let c=(et=y.result)==null?void 0:et.response,H=p();if(c!=null){let le=Y.get(H.id),de=!1;if(le){let ge=le.getExtractedText(),Re=ne.get(H.id),Me=Re!=null?Re:ve(c);if(H.rawContent=Me,ge!==null&&ge.trim()!=="")H.content=ge,de=!0;else{let ce=Gt(Me);if(ce!==null)H.content=ce,de=!0;else{let j=le.processChunk(Me);if(j instanceof Promise)j.then(ie=>{var Ce;let fe=typeof ie=="string"?ie:(Ce=ie==null?void 0:ie.text)!=null?Ce:null;if(fe!==null&&fe.trim()!==""){let He=F;He&&He.id===H.id&&(He.content=fe,He.streaming=!1,g(He))}else{let He=le.getExtractedText();if(He===null||He.trim()===""){let i=F;i&&i.id===H.id&&(ne.has(H.id)||(i.content=ve(c)),i.streaming=!1,g(i))}}});else{let ie=typeof j=="string"?j:(It=j==null?void 0:j.text)!=null?It:null;if(ie!==null&&ie.trim()!=="")H.content=ie,de=!0;else{let fe=le.getExtractedText();fe!==null&&fe.trim()!==""&&(H.content=fe,de=!0)}}}}}if(!H.rawContent){let ge=ne.get(H.id);H.rawContent=ge!=null?ge:ve(c)}if(!de&&!ne.has(H.id)&&(H.content=ve(c)),le){let ge=(vt=le.close)==null?void 0:vt.call(le);ge instanceof Promise&&ge.catch(()=>{})}Y.delete(H.id),ne.delete(H.id),H.streaming=!1,g(H)}else Y.delete(H.id),ne.delete(H.id),H.streaming=!1,g(H)}else if(Ye==="flow_complete"){let N=(Xe=y.result)==null?void 0:Xe.response;if(N!=null){let f=p(),c=ne.get(f.id),H=c!=null?c:ve(N);f.rawContent=H;let le=ve(N),de=Y.get(f.id);if(de){let ge=Gt(H);if(ge!==null)le=ge;else{let Re=de.processChunk(H);Re instanceof Promise&&Re.then(ce=>{var ie;let j=typeof ce=="string"?ce:(ie=ce==null?void 0:ce.text)!=null?ie:null;if(j!==null){let fe=F;fe&&fe.id===f.id&&(fe.content=j,fe.streaming=!1,g(fe))}});let Me=de.getExtractedText();Me!==null&&(le=Me)}}Y.delete(f.id),ne.delete(f.id),le!==f.content&&(f.content=le,g(f)),f.streaming=!1,g(f)}else if(F!==null){let f=F;Y.delete(f.id),ne.delete(f.id),f.streaming=!1,g(f)}r({type:"status",status:"idle"})}else Ye==="error"&&y.error&&r({type:"error",error:y.error instanceof Error?y.error:new Error(String(y.error))})}}}};var Jt=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=n=>{var r,e;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(r=this.callbacks).onError)==null||e.call(r,n.error))};var e;this.messages=[...(e=n.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Kt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(n){this.config={...this.config,...n},this.client=new Kt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}async sendMessage(n,r){var d,v,z,g,F;let e=n.trim();if(!e)return;(d=this.abortController)==null||d.abort();let o={id:`user-${Date.now()}`,role:"user",content:e,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 a=[...this.messages];try{await this.client.dispatch({messages:a,signal:s.signal},this.handleEvent)}catch(I){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,I instanceof Error?(z=(v=this.callbacks).onError)==null||z.call(v,I):(F=(g=this.callbacks).onError)==null||F.call(g,new Error(String(I)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,e)=>{var v,z;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(v=r.sequence)!=null?v:0,d=(z=e.sequence)!=null?z:0;return a!==d?a-d:r.id.localeCompare(e.id)})}};var dn=(t,n)=>{var e;let r=(e=n==null?void 0:n.theme)!=null?e:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let a=o.replace(/[A-Z]/g,d=>`-${d.toLowerCase()}`);t.style.setProperty(`--cw-${a}`,String(s))})};import*as Yo from"lucide";var Le=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),s=Yo[o];return s?Jo(s,n,r,e):(console.warn(`Lucide icon "${t}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${t}":`,o),null}};function Jo(t,n,r,e){if(!t||!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let a=s[0],d=s[1];if(d){let v=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(d).forEach(([z,g])=>{z!=="stroke"&&v.setAttribute(z,String(g))}),o.appendChild(v)}}}),o}var u=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Ve={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Nt={"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 cn=(t,n)=>{let r=u("button");r.type="button",r.innerHTML=`
5
+ `);s=(Ht=X.pop())!=null?Ht:"";for(let ce of X){let Ae=ce.split(`
6
+ `),Le="message",D="";for(let $ of Ae)$.startsWith("event:")?Le=$.replace("event:","").trim():$.startsWith("data:")&&(D+=$.replace("data:","").trim());if(!D)continue;let v;try{v=JSON.parse(D)}catch($){r({type:"error",error:$ instanceof Error?$:new Error("Failed to parse chat stream payload")});continue}let je=Le!=="message"?Le:(J=v.type)!=null?J:"message";if(je==="reason_start"){let $=(E=ne(v,!0))!=null?E:`reason-${b()}`,h=Fe($);h.reasoning=(ot=h.reasoning)!=null?ot:{id:$,status:"streaming",chunks:[]},h.reasoning.startedAt=(It=h.reasoning.startedAt)!=null?It:Se((yt=v.startedAt)!=null?yt:v.timestamp),h.reasoning.completedAt=void 0,h.reasoning.durationMs=void 0,h.streaming=!0,h.reasoning.status="streaming",g(h)}else if(je==="reason_chunk"){let $=(oe=(rt=ne(v,!1))!=null?rt:ne(v,!0))!=null?oe:`reason-${b()}`,h=Fe($);h.reasoning=(L=h.reasoning)!=null?L:{id:$,status:"streaming",chunks:[]},h.reasoning.startedAt=(Pt=h.reasoning.startedAt)!=null?Pt:Se((we=v.startedAt)!=null?we:v.timestamp);let d=(Ne=(S=(he=v.reasoningText)!=null?he:v.text)!=null?S:v.delta)!=null?Ne:"";if(d&&v.hidden!==!0&&h.reasoning.chunks.push(String(d)),h.reasoning.status=v.done?"complete":"streaming",v.done){h.reasoning.completedAt=Se((_e=v.completedAt)!=null?_e:v.timestamp);let P=(dt=h.reasoning.startedAt)!=null?dt:Date.now();h.reasoning.durationMs=Math.max(0,((st=h.reasoning.completedAt)!=null?st:Date.now())-P)}h.streaming=h.reasoning.status!=="complete",g(h)}else if(je==="reason_complete"){let $=(ct=(R=ne(v,!1))!=null?R:ne(v,!0))!=null?ct:`reason-${b()}`,h=H.get($);if(h!=null&&h.reasoning){h.reasoning.status="complete",h.reasoning.completedAt=Se((Te=v.completedAt)!=null?Te:v.timestamp);let P=(Ze=h.reasoning.startedAt)!=null?Ze:Date.now();h.reasoning.durationMs=Math.max(0,((O=h.reasoning.completedAt)!=null?O:Date.now())-P),h.streaming=!1,g(h)}let d=x(v);d&&y.byStep.delete(d)}else if(je==="tool_start"){let $=(ie=me(v,!0))!=null?ie:`tool-${b()}`,h=Z($),d=(ut=h.toolCall)!=null?ut:{id:$,status:"pending"};d.name=(U=v.toolName)!=null?U:d.name,d.status="running",v.args!==void 0&&(d.args=v.args),d.startedAt=(Vt=d.startedAt)!=null?Vt:Se((Ke=v.startedAt)!=null?Ke:v.timestamp),d.completedAt=void 0,d.durationMs=void 0,h.toolCall=d,h.streaming=!0,g(h)}else if(je==="tool_chunk"){let $=(Ft=(bt=me(v,!1))!=null?bt:me(v,!0))!=null?Ft:`tool-${b()}`,h=Z($),d=(Nt=h.toolCall)!=null?Nt:{id:$,status:"running"};d.startedAt=(re=d.startedAt)!=null?re:Se((xt=v.startedAt)!=null?xt:v.timestamp);let P=(it=(At=(Tt=v.text)!=null?Tt:v.delta)!=null?At:v.message)!=null?it:"";P&&(d.chunks=(Dt=d.chunks)!=null?Dt:[],d.chunks.push(String(P))),d.status="running",h.toolCall=d,h.streaming=!0,g(h)}else if(je==="tool_complete"){let $=(Mt=(qt=me(v,!1))!=null?qt:me(v,!0))!=null?Mt:`tool-${b()}`,h=Z($),d=(ft=h.toolCall)!=null?ft:{id:$,status:"running"};if(d.status="complete",v.result!==void 0&&(d.result=v.result),typeof v.duration=="number"&&(d.duration=v.duration),d.completedAt=Se((at=v.completedAt)!=null?at:v.timestamp),typeof v.duration=="number")d.durationMs=v.duration;else{let ae=(zt=d.startedAt)!=null?zt:Date.now();d.durationMs=Math.max(0,((_t=d.completedAt)!=null?_t:Date.now())-ae)}h.toolCall=d,h.streaming=!1,g(h);let P=M(v);P&&G.byCall.delete(P)}else if(je==="step_chunk"){let $=v.stepType,h=v.executionType;if($==="tool"||h==="context")continue;let d=m(),P=(ht=(wt=(Ot=v.text)!=null?Ot:v.delta)!=null?wt:v.content)!=null?ht:"";if(P){let le=((Oe=Q.get(d.id))!=null?Oe:"")+P;d.rawContent=le,K.has(d.id)||K.set(d.id,this.createStreamParser());let ue=K.get(d.id),Re=le.trim().startsWith("{")||le.trim().startsWith("[");if(Re&&Q.set(d.id,le),ue.__isPlainTextParser===!0){d.content+=P,Q.delete(d.id),K.delete(d.id),d.rawContent=void 0,g(d);continue}let de=ue.processChunk(le);if(de instanceof Promise)de.then(j=>{var pe;let se=typeof j=="string"?j:(pe=j==null?void 0:j.text)!=null?pe:null;if(se!==null&&se.trim()!==""){let ve=F;ve&&ve.id===d.id&&(ve.content=se,g(ve))}else if(!Re&&!le.trim().startsWith("<")){let ve=F;ve&&ve.id===d.id&&(ve.content+=P,Q.delete(ve.id),K.delete(ve.id),ve.rawContent=void 0,g(ve))}}).catch(()=>{d.content+=P,Q.delete(d.id),K.delete(d.id),d.rawContent=void 0,g(d)});else{let j=typeof de=="string"?de:(Ct=de==null?void 0:de.text)!=null?Ct:null;j!==null&&j.trim()!==""?(d.content=j,g(d)):!Re&&!le.trim().startsWith("<")&&(d.content+=P,Q.delete(d.id),K.delete(d.id),d.rawContent=void 0,g(d))}}if(v.isComplete){let ae=(Et=(Wt=v.result)==null?void 0:Wt.response)!=null?Et:d.content;if(ae){let le=Q.get(d.id),ue=le!=null?le:fe(ae);d.rawContent=ue;let Re=K.get(d.id),Me=null;if(Re&&(Me=Re.getExtractedText(),Me===null&&(Me=Qt(ue)),Me===null)){let j=Re.processChunk(ue);j instanceof Promise?j.then(se=>{var ve;let pe=typeof se=="string"?se:(ve=se==null?void 0:se.text)!=null?ve:null;if(pe!==null){let He=F;He&&He.id===d.id&&(He.content=pe,He.streaming=!1,g(He))}}):Me=typeof j=="string"?j:(Lt=j==null?void 0:j.text)!=null?Lt:null}Me!==null&&Me.trim()!==""?d.content=Me:Q.has(d.id)||(d.content=fe(ae));let de=K.get(d.id);if(de){let j=(De=de.close)==null?void 0:De.call(de);j instanceof Promise&&j.catch(()=>{}),K.delete(d.id)}Q.delete(d.id),d.streaming=!1,g(d)}}}else if(je==="step_complete"){let $=v.stepType,h=v.executionType;if($==="tool"||h==="context")continue;let d=($e=v.result)==null?void 0:$e.response,P=m();if(d!=null){let ae=K.get(P.id),le=!1;if(ae){let ue=ae.getExtractedText(),Re=Q.get(P.id),Me=Re!=null?Re:fe(d);if(P.rawContent=Me,ue!==null&&ue.trim()!=="")P.content=ue,le=!0;else{let de=Qt(Me);if(de!==null)P.content=de,le=!0;else{let j=ae.processChunk(Me);if(j instanceof Promise)j.then(se=>{var ve;let pe=typeof se=="string"?se:(ve=se==null?void 0:se.text)!=null?ve:null;if(pe!==null&&pe.trim()!==""){let He=F;He&&He.id===P.id&&(He.content=pe,He.streaming=!1,g(He))}else{let He=ae.getExtractedText();if(He===null||He.trim()===""){let gt=F;gt&&gt.id===P.id&&(Q.has(P.id)||(gt.content=fe(d)),gt.streaming=!1,g(gt))}}});else{let se=typeof j=="string"?j:(lt=j==null?void 0:j.text)!=null?lt:null;if(se!==null&&se.trim()!=="")P.content=se,le=!0;else{let pe=ae.getExtractedText();pe!==null&&pe.trim()!==""&&(P.content=pe,le=!0)}}}}}if(!P.rawContent){let ue=Q.get(P.id);P.rawContent=ue!=null?ue:fe(d)}if(!le&&!Q.has(P.id)&&(P.content=fe(d)),ae){let ue=(Qe=ae.close)==null?void 0:Qe.call(ae);ue instanceof Promise&&ue.catch(()=>{})}K.delete(P.id),Q.delete(P.id),P.streaming=!1,g(P)}else K.delete(P.id),Q.delete(P.id),P.streaming=!1,g(P)}else if(je==="flow_complete"){let $=(kt=v.result)==null?void 0:kt.response;if($!=null){let h=m(),d=Q.get(h.id),P=d!=null?d:fe($);h.rawContent=P;let ae=fe($),le=K.get(h.id);if(le){let ue=Qt(P);if(ue!==null)ae=ue;else{let Re=le.processChunk(P);Re instanceof Promise&&Re.then(de=>{var se;let j=typeof de=="string"?de:(se=de==null?void 0:de.text)!=null?se:null;if(j!==null){let pe=F;pe&&pe.id===h.id&&(pe.content=j,pe.streaming=!1,g(pe))}});let Me=le.getExtractedText();Me!==null&&(ae=Me)}}K.delete(h.id),Q.delete(h.id),ae!==h.content&&(h.content=ae,g(h)),h.streaming=!1,g(h)}else if(F!==null){let h=F;K.delete(h.id),Q.delete(h.id),h.streaming=!1,g(h)}r({type:"status",status:"idle"})}else je==="error"&&v.error&&r({type:"error",error:v.error instanceof Error?v.error:new Error(String(v.error))})}}}};var Zt=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=n=>{var r,e;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(r=this.callbacks).onError)==null||e.call(r,n.error))};var e;this.messages=[...(e=n.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ut(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(n){this.config={...this.config,...n},this.client=new Ut(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}async sendMessage(n,r){var c,b,z,g,F;let e=n.trim();if(!e)return;(c=this.abortController)==null||c.abort();let o={id:`user-${Date.now()}`,role:"user",content:e,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 a=[...this.messages];try{await this.client.dispatch({messages:a,signal:s.signal},this.handleEvent)}catch(H){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,H instanceof Error?(z=(b=this.callbacks).onError)==null||z.call(b,H):(F=(g=this.callbacks).onError)==null||F.call(g,new Error(String(H)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,e)=>{var b,z;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(b=r.sequence)!=null?b:0,c=(z=e.sequence)!=null?z:0;return a!==c?a-c:r.id.localeCompare(e.id)})}};var un=(t,n)=>{var e;let r=(e=n==null?void 0:n.theme)!=null?e:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let a=o.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);t.style.setProperty(`--cw-${a}`,String(s))})};import*as Qo from"lucide";var Ee=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),s=Qo[o];return s?er(s,n,r,e):(console.warn(`Lucide icon "${t}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${t}":`,o),null}};function er(t,n,r,e){if(!t||!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let a=s[0],c=s[1];if(c){let b=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(c).forEach(([z,g])=>{z!=="stroke"&&b.setAttribute(z,String(g))}),o.appendChild(b)}}}),o}var u=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Ve={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Rt={"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 gn=(t,n)=>{let r=u("button");r.type="button",r.innerHTML=`
7
7
  <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>
8
8
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
9
9
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -11,6 +11,6 @@ import{marked as Co}from"marked";Co.setOptions({breaks:!0});var So=t=>Co.parse(t
11
11
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
12
12
  </span>
13
13
  <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>
14
- `,r.addEventListener("click",n);let e=s=>{var Q,R,x,A,p,ke,re,Fe,Be,he;let a=(Q=s.launcher)!=null?Q:{},d=r.querySelector("[data-role='launcher-title']");d&&(d.textContent=(R=a.title)!=null?R:"Chat Assistant");let v=r.querySelector("[data-role='launcher-subtitle']");v&&(v.textContent=(x=a.subtitle)!=null?x:"Get answers fast");let z=r.querySelector(".tvw-flex-col");z&&(a.textHidden?z.style.display="none":z.style.display="");let g=r.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let ee=(A=a.agentIconSize)!=null?A:"40px";if(g.style.height=ee,g.style.width=ee,g.innerHTML="",a.agentIconName){let Ae=parseFloat(ee)||24,ve=Le(a.agentIconName,Ae*.6,"#ffffff",2);ve?(g.appendChild(ve),g.style.display=""):(g.textContent=(p=a.agentIconText)!=null?p:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(ke=a.agentIconText)!=null?ke:"\u{1F4AC}",g.style.display="")}let F=r.querySelector("[data-role='launcher-image']");if(F){let ee=(re=a.agentIconSize)!=null?re:"40px";F.style.height=ee,F.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(F.src=a.iconUrl,F.style.display="block"):F.style.display="none"}let I=r.querySelector("[data-role='launcher-call-to-action-icon']");if(I){let ee=(Fe=a.callToActionIconSize)!=null?Fe:"32px";I.style.height=ee,I.style.width=ee,a.callToActionIconBackgroundColor?(I.style.backgroundColor=a.callToActionIconBackgroundColor,I.classList.remove("tvw-bg-cw-primary")):(I.style.backgroundColor="",I.classList.add("tvw-bg-cw-primary"));let Ae=0;if(a.callToActionIconPadding?(I.style.boxSizing="border-box",I.style.padding=a.callToActionIconPadding,Ae=(parseFloat(a.callToActionIconPadding)||0)*2):(I.style.boxSizing="",I.style.padding=""),a.callToActionIconHidden)I.style.display="none";else if(I.style.display="",I.innerHTML="",a.callToActionIconName){let ve=parseFloat(ee)||24,Y=Math.max(ve-Ae,8),ne=Le(a.callToActionIconName,Y,"currentColor",2);ne?I.appendChild(ne):I.textContent=(Be=a.callToActionIconText)!=null?Be:"\u2197"}else I.textContent=(he=a.callToActionIconText)!=null?he:"\u2197"}let B=a.position&&Nt[a.position]?Nt[a.position]:Nt["bottom-right"],h="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=`${h} ${B}`},o=()=>{r.removeEventListener("click",n),r.remove()};return t&&e(t),{element:r,update:e,destroy:o}};var Lo=t=>{var v,z,g,F,I;if(!((z=(v=t==null?void 0:t.launcher)==null?void 0:v.enabled)!=null?z:!0)){let B=u("div","tvw-relative tvw-w-full tvw-h-full"),h=u("div","tvw-relative tvw-w-full tvw-h-full tvw-min-h-[360px]");return B.appendChild(h),{wrapper:B,panel:h}}let r=(g=t==null?void 0:t.launcher)!=null?g:{},e=r.position&&Nt[r.position]?Nt[r.position]:Nt["bottom-right"],o=u("div",`tvw-fixed ${e} tvw-z-50 tvw-transition`),s=u("div","tvw-relative tvw-min-h-[320px]"),a=(I=(F=t==null?void 0:t.launcher)==null?void 0:F.width)!=null?I:t==null?void 0:t.launcherWidth,d=a!=null?a:"min(400px, calc(100vw - 24px))";return s.style.width=d,s.style.maxWidth=d,o.appendChild(s),{wrapper:o,panel:s}},ko=(t,n=!0)=>{var Et,Lt,at,zt,_t,kt,ft,lt,Ot,$t,jt,wt,ht,Oe,Tt,Bt,Rt,Ht,De,$e,dt,et,It,vt,Xe,m,$,G,me,_,be,ue,y,Ye,N,f,c,H,le,de,ge,Re,Me,ce,j,ie,fe,Ce,He,i,l,b,D,M,k,S,V,Se,O,W;let r=u("div","tvw-flex tvw-h-full tvw-w-full 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"),e=u("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=(Et=t==null?void 0:t.launcher)!=null?Et:{},s=(Lt=o.headerIconSize)!=null?Lt:"48px",a=(at=o.closeButtonSize)!=null?at:"32px",d=(zt=o.closeButtonPlacement)!=null?zt:"inline",v=(_t=o.headerIconHidden)!=null?_t:!1,z=o.headerIconName,g=u("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(g.style.height=s,g.style.width=s,!v)if(z){let w=parseFloat(s)||24,U=Le(z,w*.6,"#ffffff",2);U?g.replaceChildren(U):g.textContent=(ft=(kt=t==null?void 0:t.launcher)==null?void 0:kt.agentIconText)!=null?ft:"\u{1F4AC}"}else if((lt=t==null?void 0:t.launcher)!=null&&lt.iconUrl){let w=u("img");w.src=t.launcher.iconUrl,w.alt="",w.className="tvw-rounded-xl tvw-object-cover",w.style.height=s,w.style.width=s,g.replaceChildren(w)}else g.textContent=($t=(Ot=t==null?void 0:t.launcher)==null?void 0:Ot.agentIconText)!=null?$t:"\u{1F4AC}";let F=u("div","tvw-flex tvw-flex-col"),I=u("span","tvw-text-base tvw-font-semibold");I.textContent=(wt=(jt=t==null?void 0:t.launcher)==null?void 0:jt.title)!=null?wt:"Chat Assistant";let B=u("span","tvw-text-xs tvw-text-cw-muted");B.textContent=(Oe=(ht=t==null?void 0:t.launcher)==null?void 0:ht.subtitle)!=null?Oe:"Here to help you get answers fast",F.append(I,B),v?e.append(F):e.append(g,F);let h=(Tt=o.clearChat)!=null?Tt:{},Q=(Bt=h.enabled)!=null?Bt:!0,R=null,x=null;if(Q){let w=(Rt=h.size)!=null?Rt:"32px",U=(Ht=h.iconName)!=null?Ht:"refresh-cw",K=(De=h.iconColor)!=null?De:"",Ie=($e=h.backgroundColor)!=null?$e:"",we=(dt=h.borderWidth)!=null?dt:"",Je=(et=h.borderColor)!=null?et:"",te=(It=h.borderRadius)!=null?It:"",tt=(vt=h.paddingX)!=null?vt:"",yt=(Xe=h.paddingY)!=null?Xe:"",ct=(m=h.tooltipText)!=null?m:"Clear chat",Pt=($=h.showTooltip)!=null?$:!0;x=u("div","tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),R=u("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"),R.style.height=w,R.style.width=w,R.type="button",R.setAttribute("aria-label",ct);let Vt=Le(U,"20px",K||"",2);if(Vt&&R.appendChild(Vt),K&&(R.style.color=K,R.classList.remove("tvw-text-cw-muted")),Ie&&(R.style.backgroundColor=Ie,R.classList.remove("hover:tvw-bg-gray-100")),we||Je){let We=we||"0px",pt=Je||"transparent";R.style.border=`${We} solid ${pt}`,R.classList.remove("tvw-border-none")}if(te&&(R.style.borderRadius=te,R.classList.remove("tvw-rounded-full")),tt?(R.style.paddingLeft=tt,R.style.paddingRight=tt):(R.style.paddingLeft="",R.style.paddingRight=""),yt?(R.style.paddingTop=yt,R.style.paddingBottom=yt):(R.style.paddingTop="",R.style.paddingBottom=""),x.appendChild(R),Pt&&ct&&R&&x){let We=null,pt=()=>{if(We||!R)return;We=u("div","tvw-clear-chat-tooltip"),We.textContent=ct;let Ft=u("div");Ft.className="tvw-clear-chat-tooltip-arrow",We.appendChild(Ft);let At=R.getBoundingClientRect();We.style.position="fixed",We.style.left=`${At.left+At.width/2}px`,We.style.top=`${At.top-8}px`,We.style.transform="translate(-50%, -100%)",document.body.appendChild(We)},je=()=>{We&&We.parentNode&&(We.parentNode.removeChild(We),We=null)};x.addEventListener("mouseenter",pt),x.addEventListener("mouseleave",je),R.addEventListener("focus",pt),R.addEventListener("blur",je),x._cleanupTooltip=()=>{je(),x&&(x.removeEventListener("mouseenter",pt),x.removeEventListener("mouseleave",je)),R&&(R.removeEventListener("focus",pt),R.removeEventListener("blur",je))}}e.appendChild(x)}let A=u("div",d==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":Q?"":"tvw-ml-auto"),p=u("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");p.style.height=a,p.style.width=a,p.type="button";let ke=(G=o.closeButtonTooltipText)!=null?G:"Close chat",re=(me=o.closeButtonShowTooltip)!=null?me:!0;p.setAttribute("aria-label",ke),p.style.display=n?"":"none";let Fe=(_=o.closeButtonIconName)!=null?_:"x",Be=(be=o.closeButtonIconText)!=null?be:"\xD7",he=Le(Fe,"20px",o.closeButtonColor||"",2);if(he?p.appendChild(he):p.textContent=Be,o.closeButtonColor?(p.style.color=o.closeButtonColor,p.classList.remove("tvw-text-cw-muted")):(p.style.color="",p.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(p.style.backgroundColor=o.closeButtonBackgroundColor,p.classList.remove("hover:tvw-bg-gray-100")):(p.style.backgroundColor="",p.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let w=o.closeButtonBorderWidth||"0px",U=o.closeButtonBorderColor||"transparent";p.style.border=`${w} solid ${U}`,p.classList.remove("tvw-border-none")}else p.style.border="",p.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(p.style.borderRadius=o.closeButtonBorderRadius,p.classList.remove("tvw-rounded-full")):(p.style.borderRadius="",p.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(p.style.paddingLeft=o.closeButtonPaddingX,p.style.paddingRight=o.closeButtonPaddingX):(p.style.paddingLeft="",p.style.paddingRight=""),o.closeButtonPaddingY?(p.style.paddingTop=o.closeButtonPaddingY,p.style.paddingBottom=o.closeButtonPaddingY):(p.style.paddingTop="",p.style.paddingBottom=""),A.appendChild(p),re&&ke){let w=null,U=()=>{if(w)return;w=u("div","tvw-clear-chat-tooltip"),w.textContent=ke;let Ie=u("div");Ie.className="tvw-clear-chat-tooltip-arrow",w.appendChild(Ie);let we=p.getBoundingClientRect();w.style.position="fixed",w.style.left=`${we.left+we.width/2}px`,w.style.top=`${we.top-8}px`,w.style.transform="translate(-50%, -100%)",document.body.appendChild(w)},K=()=>{w&&w.parentNode&&(w.parentNode.removeChild(w),w=null)};A.addEventListener("mouseenter",U),A.addEventListener("mouseleave",K),p.addEventListener("focus",U),p.addEventListener("blur",K),A._cleanupTooltip=()=>{K(),A.removeEventListener("mouseenter",U),A.removeEventListener("mouseleave",K),p.removeEventListener("focus",U),p.removeEventListener("blur",K)}}d==="top-right"?(r.style.position="relative",r.appendChild(A)):e.appendChild(A);let ee=u("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");ee.id="vanilla-agent-scroll-container";let Ae=u("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),ve=u("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");ve.textContent=(y=(ue=t==null?void 0:t.copy)==null?void 0:ue.welcomeTitle)!=null?y:"Hello \u{1F44B}";let Y=u("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");Y.textContent=(N=(Ye=t==null?void 0:t.copy)==null?void 0:Ye.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",Ae.append(ve,Y);let ne=u("div","tvw-flex tvw-flex-col tvw-gap-3");ee.append(Ae,ne);let Dt=u("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),Z=u("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),E=((f=t==null?void 0:t.voiceRecognition)==null?void 0:f.enabled)===!0,rt=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),st=u("form",`tvw-flex tvw-items-end ${E&&rt?"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`);st.style.outline="none";let se=u("textarea");se.placeholder=(H=(c=t==null?void 0:t.copy)==null?void 0:c.inputPlaceholder)!=null?H:"Type your message\u2026",se.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",se.rows=1;let L=(de=(le=t==null?void 0:t.theme)==null?void 0:le.inputFontFamily)!=null?de:"sans-serif",ye=(Re=(ge=t==null?void 0:t.theme)==null?void 0:ge.inputFontWeight)!=null?Re:"400",C=w=>{switch(w){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=C(L),se.style.fontWeight=ye,se.style.border="none",se.style.outline="none",se.style.borderWidth="0",se.style.borderStyle="none",se.style.borderColor="transparent",se.addEventListener("focus",()=>{se.style.border="none",se.style.outline="none",se.style.borderWidth="0",se.style.borderStyle="none",se.style.borderColor="transparent",se.style.boxShadow="none"}),se.addEventListener("blur",()=>{se.style.border="none",se.style.outline="none"});let X=(Me=t==null?void 0:t.sendButton)!=null?Me:{},ze=(ce=X.useIcon)!=null?ce:!1,ut=(j=X.iconText)!=null?j:"\u2191",Qe=X.iconName,P=(ie=X.tooltipText)!=null?ie:"Send message",Ct=(fe=X.showTooltip)!=null?fe:!1,_e=(Ce=X.size)!=null?Ce:"40px",gt=X.backgroundColor,Ne=X.textColor,Ue=u("div","tvw-send-button-wrapper"),q=u("button",ze?"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(q.type="submit",ze){if(q.style.width=_e,q.style.height=_e,q.style.minWidth=_e,q.style.minHeight=_e,q.style.fontSize="18px",q.style.lineHeight="1",q.innerHTML="",Qe){let w=parseFloat(_e)||24,U=Ne&&typeof Ne=="string"&&Ne.trim()?Ne.trim():"currentColor",K=Le(Qe,w,U,2);K?(q.appendChild(K),q.style.color=U):(q.textContent=ut,Ne?q.style.color=Ne:q.classList.add("tvw-text-white"))}else q.textContent=ut,Ne?q.style.color=Ne:q.classList.add("tvw-text-white");gt?q.style.backgroundColor=gt:q.classList.add("tvw-bg-cw-primary")}else q.textContent=(i=(He=t==null?void 0:t.copy)==null?void 0:He.sendButtonLabel)!=null?i:"Send",Ne?q.style.color=Ne:q.classList.add("tvw-text-white");if(X.borderWidth&&(q.style.borderWidth=X.borderWidth,q.style.borderStyle="solid"),X.borderColor&&(q.style.borderColor=X.borderColor),X.paddingX?(q.style.paddingLeft=X.paddingX,q.style.paddingRight=X.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),X.paddingY?(q.style.paddingTop=X.paddingY,q.style.paddingBottom=X.paddingY):(q.style.paddingTop="",q.style.paddingBottom=""),Ct&&P){let w=u("div","tvw-send-button-tooltip");w.textContent=P,Ue.appendChild(w)}Ue.appendChild(q);let xe=(l=t==null?void 0:t.voiceRecognition)!=null?l:{},Wt=xe.enabled===!0,J=null,it=null,Ut=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Wt&&Ut){it=u("div","tvw-send-button-wrapper"),J=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),J.type="button",J.setAttribute("aria-label","Start voice recognition");let w=(b=xe.iconName)!=null?b:"mic",U=(D=xe.iconSize)!=null?D:_e,K=parseFloat(U)||24,Ie=(M=xe.backgroundColor)!=null?M:gt,we=(k=xe.iconColor)!=null?k:Ne;J.style.width=U,J.style.height=U,J.style.minWidth=U,J.style.minHeight=U,J.style.fontSize="18px",J.style.lineHeight="1";let Je=we||"currentColor",te=Le(w,K,Je,1.5);te?(J.appendChild(te),J.style.color=Je):(J.textContent="\u{1F3A4}",J.style.color=Je),Ie?J.style.backgroundColor=Ie:J.classList.add("tvw-bg-cw-primary"),we?J.style.color=we:!we&&!Ne&&J.classList.add("tvw-text-white"),xe.borderWidth&&(J.style.borderWidth=xe.borderWidth,J.style.borderStyle="solid"),xe.borderColor&&(J.style.borderColor=xe.borderColor),xe.paddingX&&(J.style.paddingLeft=xe.paddingX,J.style.paddingRight=xe.paddingX),xe.paddingY&&(J.style.paddingTop=xe.paddingY,J.style.paddingBottom=xe.paddingY),it.appendChild(J);let tt=(S=xe.tooltipText)!=null?S:"Start voice recognition";if(((V=xe.showTooltip)!=null?V:!1)&&tt){let ct=u("div","tvw-send-button-tooltip");ct.textContent=tt,it.appendChild(ct)}}st.addEventListener("click",w=>{w.target!==q&&w.target!==Ue&&w.target!==J&&w.target!==it&&se.focus()}),st.append(se),it&&st.append(it),st.append(Ue);let mt=u("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),St=(Se=t==null?void 0:t.statusIndicator)!=null?Se:{},ae=(O=St.visible)!=null?O:!0;return mt.style.display=ae?"":"none",mt.textContent=(W=St.idleText)!=null?W:"Online",Dt.append(Z,st,mt),r.append(e,ee,Dt),{container:r,body:ee,messagesWrapper:ne,suggestions:Z,textarea:se,sendButton:q,sendButtonWrapper:Ue,micButton:J,micButtonWrapper:it,composerForm:st,statusText:mt,introTitle:ve,introSubtitle:Y,closeButton:p,closeButtonWrapper:A,clearChatButton:R,clearChatButtonWrapper:x,iconHolder:g}};var un=()=>{let t=document.createElement("div");t.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.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 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="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",t.appendChild(n),t.appendChild(r),t.appendChild(e),t.appendChild(o),t},gn=(t,n)=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"];t.role==="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");let e=u("div",r.join(" ")),o=document.createElement("div");if(o.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(o),t.streaming&&t.role==="assistant"&&(!t.content||!t.content.trim())){let s=un();e.appendChild(s)}return e};var pn=new Set,mn=t=>{let n=t.reasoning,r=u("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(!n)return r;let e=pn.has(t.id),o=u("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",e?"true":"false");let s=u("div","tvw-flex tvw-flex-col tvw-text-left"),a=u("span","tvw-text-xs tvw-text-cw-primary");a.textContent="Thinking...",s.appendChild(a);let d=u("span","tvw-text-xs tvw-text-cw-primary");d.textContent=Wo(n),s.appendChild(d),n.status==="complete"?a.style.display="none":a.style.display="";let v=u("div","tvw-flex tvw-items-center"),g=Le(e?"chevron-up":"chevron-down",16,"currentColor",2);g?v.appendChild(g):v.textContent=e?"Hide":"Show";let F=u("div","tvw-flex tvw-items-center tvw-ml-auto");F.append(v),o.append(s,F);let I=u("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");I.style.display=e?"":"none";let B=n.chunks.join(""),h=u("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");h.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),I.appendChild(h);let Q=()=>{o.setAttribute("aria-expanded",e?"true":"false"),v.innerHTML="";let A=Le(e?"chevron-up":"chevron-down",16,"currentColor",2);A?v.appendChild(A):v.textContent=e?"Hide":"Show",I.style.display=e?"":"none"},R=()=>{e=!e,e?pn.add(t.id):pn.delete(t.id),Q()};return o.addEventListener("pointerdown",x=>{x.preventDefault(),R()}),o.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),R())}),Q(),r.append(o,I),r};var fn=new Set,wn=(t,n)=>{var R;let r=t.toolCall,e=(R=n==null?void 0:n.toolCall)!=null?R:{},o=u("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(e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=fn.has(t.id),a=u("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");a.type="button",a.setAttribute("aria-expanded",s?"true":"false"),e.headerBackgroundColor&&(a.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(a.style.paddingLeft=e.headerPaddingX,a.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(a.style.paddingTop=e.headerPaddingY,a.style.paddingBottom=e.headerPaddingY);let d=u("div","tvw-flex tvw-flex-col tvw-text-left"),v=u("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(v.style.color=e.headerTextColor),v.textContent=Eo(r),d.appendChild(v);let z=u("div","tvw-flex tvw-items-center"),g=e.toggleTextColor||e.headerTextColor||"currentColor",F=Le(s?"chevron-up":"chevron-down",16,g,2);F?z.appendChild(F):z.textContent=s?"Hide":"Show";let I=u("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");I.append(z),a.append(d,I);let B=u("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",e.contentBackgroundColor&&(B.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(B.style.color=e.contentTextColor),e.contentPaddingX&&(B.style.paddingLeft=e.contentPaddingX,B.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(B.style.paddingTop=e.contentPaddingY,B.style.paddingBottom=e.contentPaddingY),r.name){let x=u("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?x.style.color=e.contentTextColor:e.headerTextColor&&(x.style.color=e.headerTextColor),x.textContent=r.name,B.appendChild(x)}if(r.args!==void 0){let x=u("div","tvw-space-y-1"),A=u("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(A.style.color=e.labelTextColor),A.textContent="Arguments";let p=u("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");p.style.fontSize="0.75rem",p.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(p.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(p.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(p.style.color=e.codeBlockTextColor),p.textContent=on(r.args),x.append(A,p),B.appendChild(x)}if(r.chunks&&r.chunks.length){let x=u("div","tvw-space-y-1"),A=u("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(A.style.color=e.labelTextColor),A.textContent="Activity";let p=u("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");p.style.fontSize="0.75rem",p.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(p.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(p.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(p.style.color=e.codeBlockTextColor),p.textContent=r.chunks.join(`
15
- `),x.append(A,p),B.appendChild(x)}if(r.status==="complete"&&r.result!==void 0){let x=u("div","tvw-space-y-1"),A=u("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(A.style.color=e.labelTextColor),A.textContent="Result";let p=u("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");p.style.fontSize="0.75rem",p.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(p.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(p.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(p.style.color=e.codeBlockTextColor),p.textContent=on(r.result),x.append(A,p),B.appendChild(x)}if(r.status==="complete"&&typeof r.duration=="number"){let x=u("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(x.style.color=e.contentTextColor),x.textContent=`Duration: ${r.duration}ms`,B.appendChild(x)}let h=()=>{a.setAttribute("aria-expanded",s?"true":"false"),z.innerHTML="";let x=e.toggleTextColor||e.headerTextColor||"currentColor",A=Le(s?"chevron-up":"chevron-down",16,x,2);A?z.appendChild(A):z.textContent=s?"Hide":"Show",B.style.display=s?"":"none"},Q=()=>{s=!s,s?fn.add(t.id):fn.delete(t.id),h()};return a.addEventListener("pointerdown",x=>{x.preventDefault(),Q()}),a.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),Q())}),h(),o.append(a,B),o};var Bo=t=>{let n=[];return{buttons:n,render:(e,o,s,a,d)=>{if(t.innerHTML="",n.length=0,!e||!e.length||(a!=null?a:o?o.getMessages():[]).some(B=>B.role==="user"))return;let g=document.createDocumentFragment(),F=o?o.isStreaming():!1,I=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'}};e.forEach(B=>{let h=u("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");h.type="button",h.textContent=B,h.disabled=F,d!=null&&d.fontFamily&&(h.style.fontFamily=I(d.fontFamily)),d!=null&&d.fontWeight&&(h.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(h.style.paddingLeft=d.paddingX,h.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(h.style.paddingTop=d.paddingY,h.style.paddingBottom=d.paddingY),h.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(B))}),g.appendChild(h),n.push(h)}),t.appendChild(g)}}};var Ro={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"}},hn=(t,n,r,e)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var h,Q,R;if(s.dataset.enhanced==="true")return;let a=(h=s.dataset.tvForm)!=null?h:"init";s.dataset.enhanced="true";let d=(Q=Ro[a])!=null?Q:Ro.init;s.classList.add("tvw-form-card","tvw-space-y-4");let v=u("div","tvw-space-y-1"),z=u("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(z.textContent=d.title,v.appendChild(z),d.description){let x=u("p","tvw-text-sm tvw-text-cw-muted");x.textContent=d.description,v.appendChild(x)}let g=document.createElement("form");g.className="tvw-form-grid tvw-space-y-3",d.fields.forEach(x=>{var Fe,Be;let A=u("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");A.htmlFor=`${n.id}-${a}-${x.name}`;let p=u("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");p.textContent=x.label,A.appendChild(p);let ke=(Fe=x.type)!=null?Fe:"text",re;ke==="textarea"?(re=document.createElement("textarea"),re.rows=3):(re=document.createElement("input"),re.type=ke),re.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",re.id=`${n.id}-${a}-${x.name}`,re.name=x.name,re.placeholder=(Be=x.placeholder)!=null?Be:"",x.required&&(re.required=!0),A.appendChild(re),g.appendChild(A)});let F=u("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),I=u("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),B=u("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=(R=d.submitLabel)!=null?R:"Submit",F.appendChild(I),F.appendChild(B),g.appendChild(F),s.replaceChildren(v,g),g.addEventListener("submit",async x=>{var re,Fe;x.preventDefault();let A=(re=r.formEndpoint)!=null?re:"/form",p=new FormData(g),ke={};p.forEach((Be,he)=>{ke[he]=Be}),ke.type=a,B.disabled=!0,I.textContent="Submitting\u2026";try{let Be=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ke)});if(!Be.ok)throw new Error(`Form submission failed (${Be.status})`);let he=await Be.json();I.textContent=(Fe=he.message)!=null?Fe:"Thanks! We'll be in touch soon.",he.success&&he.nextPrompt&&await e.sendMessage(String(he.nextPrompt))}catch(Be){I.textContent=Be instanceof Error?Be.message:"Something went wrong. Please try again."}finally{B.disabled=!1}})})};var vn=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var e;let r=this.plugins.get(n);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let e=new Set(n.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...n].sort((s,a)=>{var d,v;return((d=a.priority)!=null?d:0)-((v=s.priority)!=null?v:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},Zt=new vn;var ot={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,iconName:"refresh-cw",size:"29px",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"},debug:!1};function yn(t){var n,r,e;return t?{...ot,...t,theme:{...ot.theme,...t.theme},launcher:{...ot.launcher,...t.launcher,clearChat:{...(n=ot.launcher)==null?void 0:n.clearChat,...(r=t.launcher)==null?void 0:r.clearChat}},copy:{...ot.copy,...t.copy},sendButton:{...ot.sendButton,...t.sendButton},statusIndicator:{...ot.statusIndicator,...t.statusIndicator},voiceRecognition:{...ot.voiceRecognition,...t.voiceRecognition},features:{...ot.features,...t.features},suggestionChips:(e=t.suggestionChips)!=null?e:ot.suggestionChips,suggestionChipsConfig:{...ot.suggestionChipsConfig,...t.suggestionChipsConfig}}:ot}var Ho=()=>{let t=new Map,n=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:n,off:r,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(d=>{try{d(s)}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",v)}})}}};var Go=t=>{let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:t},Zo=t=>{let n=t.trim(),r=n.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return n.slice(r,o+1)}return null},Qt=({text:t})=>{if(!t||!t.includes("{"))return null;try{let n=Go(t),r=Zo(n);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},xn=t=>typeof t=="string"?t:t==null?"":String(t),Xt={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:xn(t.payload.text)},messageAndClick:(t,n)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,e=xn(r.element);if(e&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:xn(r.text)}}},Io=t=>Array.isArray(t)?t.map(n=>String(n)):[],en=t=>{let n=new Set(Io(t.getMetadata().processedActionMessageIds)),r=()=>{n=new Set(Io(t.getMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(n);t.updateMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&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 d=a?t.parsers.reduce((z,g)=>z||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!d)return null;n.add(s.message.id),e();let v={action:d,message:s.message};t.emit("action:detected",v);for(let z of t.handlers)if(z)try{let g=z(d,{message:s.message,metadata:t.getMetadata(),updateMetadata:t.updateMetadata,document:t.documentRef});if(!g)continue;if(g.handled){let F=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:F}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:r}};var Yt="vanilla-agent-chat-history",Qo=30*1e3,bn=t=>!t||typeof t!="object"?{}:{...t},Po=t=>t.map(n=>({...n,streaming:!1})),Fo=(t,n)=>r=>{var s,a,d;let e=(s=r.text)!=null?s:"",o=(a=r.message.rawContent)!=null?a:null;if(n){let v=n.process({text:e,raw:o!=null?o:e,message:r.message,streaming:r.streaming});v!==null&&(e=v.text,v.persist||(r.message.__skipPersist=!0))}return t!=null&&t.postprocessMessage?t.postprocessMessage({...r,text:e,raw:(d=o!=null?o:r.text)!=null?d:""}):nn(e)},Cn=(t,n,r)=>{var c,H,le,de,ge,Re,Me,ce,j,ie,fe,Ce,He;(!t.id||t.id!=="vanilla-agent-root")&&(t.id="vanilla-agent-root");let e=yn(n);dn(t,e);let o=Zt.getForInstance(e.plugins),s=Ho(),a=e.storageAdapter,d={},v=null;if(a!=null&&a.load)try{let i=a.load();if(i&&typeof i.then=="function")v=i;else if(i){let l=i;l.metadata&&(d=bn(l.metadata)),(c=l.messages)!=null&&c.length&&(e={...e,initialMessages:l.messages})}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",i)}let z=()=>d,g=i=>{var b;d=(b=i({...d}))!=null?b:{},kt()},F=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Qt],I=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xt.message,Xt.messageAndClick],B=en({parsers:F,handlers:I,getMetadata:z,updateMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});B.syncFromMetadata();let h=(le=(H=e.launcher)==null?void 0:H.enabled)!=null?le:!0,Q=(ge=(de=e.launcher)==null?void 0:de.autoExpand)!=null?ge:!1,R=Q,x=h,A=h?Q:!0,p=Fo(e,B),ke=(Me=(Re=e.features)==null?void 0:Re.showReasoning)!=null?Me:!0,re=(j=(ce=e.features)==null?void 0:ce.showToolCalls)!=null?j:!0,Fe=(ie=e.statusIndicator)!=null?ie:{},Be=i=>{var l,b,D,M;return i==="idle"?(l=Fe.idleText)!=null?l:Ve.idle:i==="connecting"?(b=Fe.connectingText)!=null?b:Ve.connecting:i==="connected"?(D=Fe.connectedText)!=null?D:Ve.connected:i==="error"?(M=Fe.errorText)!=null?M:Ve.error:Ve[i]},{wrapper:he,panel:ee}=Lo(e),Ae=ko(e,h),{container:ve,body:Y,messagesWrapper:ne,suggestions:Dt,textarea:Z,sendButton:E,sendButtonWrapper:rt,composerForm:bt,statusText:qt,introTitle:st,introSubtitle:se,closeButton:L,iconHolder:ye}=Ae,C=Ae.micButton,X=Ae.micButtonWrapper;ee.appendChild(ve),t.appendChild(he);let ze=[],ut=Bo(Dt),Qe=null,P,Ct=!1,_e=!0,gt=0,Ne=0,Ue=null,q=!1,xe=0,Wt=!1,J=125,it=2e3,Ut=5,mt=50,St=new Map,ae={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Et=(Ce=(fe=e.voiceRecognition)==null?void 0:fe.autoResume)!=null?Ce:!1,Lt=i=>{s.emit("voice:state",{active:ae.active,source:i,timestamp:Date.now()})},at=()=>{g(i=>({...i,voiceState:{active:ae.active,timestamp:Date.now(),manuallyDeactivated:ae.manuallyDeactivated}}))},zt=()=>{var D,M;if(((D=e.voiceRecognition)==null?void 0:D.enabled)===!1)return;let i=bn(d.voiceState),l=!!i.active,b=Number((M=i.timestamp)!=null?M:0);ae.manuallyDeactivated=!!i.manuallyDeactivated,l&&Date.now()-b<Qo&&setTimeout(()=>{ae.active||(ae.manuallyDeactivated=!1,vt("restore"))},1e3)},_t=()=>P?Po(P.getMessages()).filter(i=>!i.__skipPersist):[];function kt(i){if(!(a!=null&&a.save)||!P)return;let l={messages:i?Po(i):_t(),metadata:d};try{let b=a.save(l);b instanceof Promise&&b.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let ft=(i=!1)=>{if(!_e)return;let l=Date.now();q&&l<xe&&!i||(q&&l>=xe&&(q=!1),!(!i&&!Ct)&&(l-Ne<J||(Ne=l,Ue&&cancelAnimationFrame(Ue),Ue=requestAnimationFrame(()=>{q||!_e||(Wt=!0,Y.scrollTop=Y.scrollHeight,gt=Y.scrollTop,requestAnimationFrame(()=>{Wt=!1}),Ue=null)}))))},lt=null,Ot=()=>he.querySelector("#vanilla-agent-scroll-container")||Y,$t=(i,l=500)=>{let b=i.scrollTop,D=i.clientHeight,M=i.scrollHeight,k=M-b;if(b+D>=M-2||Math.abs(k)<5)return;lt!==null&&(cancelAnimationFrame(lt),lt=null);let V=performance.now(),Se=W=>1-Math.pow(1-W,3),O=W=>{let w=i.scrollHeight;w!==M&&(M=w,k=M-b);let U=W-V,K=Math.min(U/l,1),Ie=Se(K),we=b+k*Ie;i.scrollTop=we,K<1?lt=requestAnimationFrame(O):(i.scrollTop=i.scrollHeight,lt=null)};lt=requestAnimationFrame(O)},jt=i=>{let l=new Map;i.forEach(b=>{let D=St.get(b.id);l.set(b.id,{streaming:b.streaming,role:b.role}),!D&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(D!=null&&D.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b)}),St.clear(),l.forEach((b,D)=>{St.set(D,b)})},wt=(i,l,b)=>{i.innerHTML="";let D=document.createDocumentFragment();l.forEach(k=>{let S=null,V=o.find(O=>!!(k.variant==="reasoning"&&O.renderReasoning||k.variant==="tool"&&O.renderToolCall||!k.variant&&O.renderMessage));if(V)if(k.variant==="reasoning"&&k.reasoning&&V.renderReasoning){if(!ke)return;S=V.renderReasoning({message:k,defaultRenderer:()=>mn(k),config:e})}else if(k.variant==="tool"&&k.toolCall&&V.renderToolCall){if(!re)return;S=V.renderToolCall({message:k,defaultRenderer:()=>wn(k,e),config:e})}else V.renderMessage&&(S=V.renderMessage({message:k,defaultRenderer:()=>{let O=gn(k,b);return k.role!=="user"&&hn(O,k,e,P),O},config:e}));if(!S)if(k.variant==="reasoning"&&k.reasoning){if(!ke)return;S=mn(k)}else if(k.variant==="tool"&&k.toolCall){if(!re)return;S=wn(k,e)}else S=gn(k,b),k.role!=="user"&&hn(S,k,e,P);let Se=document.createElement("div");Se.className="tvw-flex",k.role==="user"&&Se.classList.add("tvw-justify-end"),Se.appendChild(S),D.appendChild(Se)});let M=l.some(k=>k.role==="assistant"&&k.streaming);if(Ct&&l.some(k=>k.role==="user")&&!M){let k=un(),S=document.createElement("div");S.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(" "),S.appendChild(k);let V=document.createElement("div");V.className="tvw-flex",V.appendChild(S),D.appendChild(V)}i.appendChild(D),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let k=Ot();$t(k)})})},ht=()=>{h&&(A?(he.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ee.classList.remove("tvw-scale-95","tvw-opacity-0"),ee.classList.add("tvw-scale-100","tvw-opacity-100"),_&&(_.element.style.display="none")):(he.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ee.classList.remove("tvw-scale-100","tvw-opacity-100"),ee.classList.add("tvw-scale-95","tvw-opacity-0"),_&&(_.element.style.display="")))},Oe=(i,l="user")=>{if(!h||A===i)return;let b=A;A=i,ht(),A&&(be(),ft(!0));let D={open:A,source:l,timestamp:Date.now()};A&&!b?s.emit("widget:opened",D):!A&&b&&s.emit("widget:closed",D),s.emit("widget:state",{open:A,launcherEnabled:h,voiceActive:ae.active,streaming:P.isStreaming()})},Tt=i=>{Z.disabled=i,E.disabled=i,C&&(C.disabled=i),ut.buttons.forEach(l=>{l.disabled=i})},Bt=()=>{var M,k,S,V,Se,O,W,w,U,K,Ie,we,Je,te;st.textContent=(k=(M=e.copy)==null?void 0:M.welcomeTitle)!=null?k:"Hello \u{1F44B}",se.textContent=(V=(S=e.copy)==null?void 0:S.welcomeSubtitle)!=null?V:"Ask anything about your account or products.",Z.placeholder=(O=(Se=e.copy)==null?void 0:Se.inputPlaceholder)!=null?O:"How can I help...",((w=(W=e.sendButton)==null?void 0:W.useIcon)!=null?w:!1)||(E.textContent=(K=(U=e.copy)==null?void 0:U.sendButtonLabel)!=null?K:"Send");let l=(we=(Ie=e.theme)==null?void 0:Ie.inputFontFamily)!=null?we:"sans-serif",b=(te=(Je=e.theme)==null?void 0:Je.inputFontWeight)!=null?te:"400",D=tt=>{switch(tt){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'}};Z.style.fontFamily=D(l),Z.style.fontWeight=b};P=new Jt(e,{onMessagesChanged(i){wt(ne,i,p),P&&(i.some(D=>D.role==="user")?ut.render([],P,Z,i):ut.render(e.suggestionChips,P,Z,i,e.suggestionChipsConfig)),ft(!Ct),jt(i);let l=[...i].reverse().find(b=>b.role==="user");ae.lastUserMessageWasVoice=!!(l!=null&&l.viaVoice),kt(i)},onStatusChanged(i){var D;let l=(D=e.statusIndicator)!=null?D:{},b=M=>{var k,S,V,Se;return M==="idle"?(k=l.idleText)!=null?k:Ve.idle:M==="connecting"?(S=l.connectingText)!=null?S:Ve.connecting:M==="connected"?(V=l.connectedText)!=null?V:Ve.connected:M==="error"?(Se=l.errorText)!=null?Se:Ve.error:Ve[M]};qt.textContent=b(i)},onStreamingChanged(i){Ct=i,Tt(i),P&&wt(ne,P.getMessages(),p),i||ft(!0)}}),v&&v.then(i=>{var l;i&&(i.metadata&&(d=bn(i.metadata),B.syncFromMetadata()),(l=i.messages)!=null&&l.length&&P.hydrateMessages(i.messages))}).catch(i=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)});let Rt=i=>{i.preventDefault();let l=Z.value.trim();l&&(Z.value="",P.sendMessage(l))},Ht=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),E.click())},De=null,$e=!1,dt=null,et=null,It=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,vt=(i="user")=>{var k,S,V,Se;if($e||P.isStreaming())return;let l=It();if(!l)return;De=new l;let D=(S=((k=e.voiceRecognition)!=null?k:{}).pauseDuration)!=null?S:2e3;De.continuous=!0,De.interimResults=!0,De.lang="en-US";let M=Z.value;De.onresult=O=>{let W="",w="";for(let K=0;K<O.results.length;K++){let Ie=O.results[K],we=Ie[0].transcript;Ie.isFinal?W+=we+" ":w=we}let U=M+W+w;Z.value=U,dt&&clearTimeout(dt),(W||w)&&(dt=window.setTimeout(()=>{let K=Z.value.trim();K&&De&&$e&&(Xe(),Z.value="",P.sendMessage(K,{viaVoice:!0}))},D))},De.onerror=O=>{O.error!=="no-speech"&&Xe()},De.onend=()=>{if($e){let O=Z.value.trim();O&&O!==M.trim()&&(Z.value="",P.sendMessage(O,{viaVoice:!0})),Xe()}};try{if(De.start(),$e=!0,ae.active=!0,i!=="system"&&(ae.manuallyDeactivated=!1),Lt(i),at(),C){et={backgroundColor:C.style.backgroundColor,color:C.style.color,borderColor:C.style.borderColor};let O=(V=e.voiceRecognition)!=null?V:{},W=(Se=O.recordingBackgroundColor)!=null?Se:"#ef4444",w=O.recordingIconColor,U=O.recordingBorderColor;if(C.classList.add("tvw-voice-recording"),C.style.backgroundColor=W,w){C.style.color=w;let K=C.querySelector("svg");K&&K.setAttribute("stroke",w)}U&&(C.style.borderColor=U),C.setAttribute("aria-label","Stop voice recognition")}}catch{Xe("system")}},Xe=(i="user")=>{if($e){if($e=!1,dt&&(clearTimeout(dt),dt=null),De){try{De.stop()}catch{}De=null}if(ae.active=!1,Lt(i),at(),C){if(C.classList.remove("tvw-voice-recording"),et){C.style.backgroundColor=et.backgroundColor,C.style.color=et.color,C.style.borderColor=et.borderColor;let l=C.querySelector("svg");l&&l.setAttribute("stroke",et.color||"currentColor"),et=null}C.setAttribute("aria-label","Start voice recognition")}}},m=(i,l)=>{var we,Je,te,tt,yt,ct,Pt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let D=u("div","tvw-send-button-wrapper"),M=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");M.type="button",M.setAttribute("aria-label","Start voice recognition");let k=(we=i==null?void 0:i.iconName)!=null?we:"mic",S=(Je=l==null?void 0:l.size)!=null?Je:"40px",V=(te=i==null?void 0:i.iconSize)!=null?te:S,Se=parseFloat(V)||24,O=(tt=i==null?void 0:i.backgroundColor)!=null?tt:l==null?void 0:l.backgroundColor,W=(yt=i==null?void 0:i.iconColor)!=null?yt:l==null?void 0:l.textColor;M.style.width=V,M.style.height=V,M.style.minWidth=V,M.style.minHeight=V,M.style.fontSize="18px",M.style.lineHeight="1";let w=W||"currentColor",U=Le(k,Se,w,1.5);U?(M.appendChild(U),M.style.color=w):(M.textContent="\u{1F3A4}",M.style.color=w),O?M.style.backgroundColor=O:M.classList.add("tvw-bg-cw-primary"),W?M.style.color=W:!W&&!(l!=null&&l.textColor)&&M.classList.add("tvw-text-white"),i!=null&&i.borderWidth&&(M.style.borderWidth=i.borderWidth,M.style.borderStyle="solid"),i!=null&&i.borderColor&&(M.style.borderColor=i.borderColor),i!=null&&i.paddingX&&(M.style.paddingLeft=i.paddingX,M.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(M.style.paddingTop=i.paddingY,M.style.paddingBottom=i.paddingY),D.appendChild(M);let K=(ct=i==null?void 0:i.tooltipText)!=null?ct:"Start voice recognition";if(((Pt=i==null?void 0:i.showTooltip)!=null?Pt:!1)&&K){let Vt=u("div","tvw-send-button-tooltip");Vt.textContent=K,D.appendChild(Vt)}return{micButton:M,micButtonWrapper:D}},$=()=>{if($e){let i=Z.value.trim();ae.manuallyDeactivated=!0,at(),Xe("user"),i&&(Z.value="",P.sendMessage(i))}else ae.manuallyDeactivated=!1,at(),vt("user")};C&&(C.addEventListener("click",$),ze.push(()=>{Xe("system"),C&&C.removeEventListener("click",$)}));let G=s.on("assistant:complete",()=>{Et&&(ae.active||ae.manuallyDeactivated||Et==="assistant"&&!ae.lastUserMessageWasVoice||setTimeout(()=>{!ae.active&&!ae.manuallyDeactivated&&vt("auto")},600))});ze.push(G);let me=()=>{Oe(!A,"user")},_=h?cn(e,me):null;_&&t.appendChild(_.element),ht(),ut.render(e.suggestionChips,P,Z,void 0,e.suggestionChipsConfig),Bt(),Tt(P.isStreaming()),ft(!0),zt();let be=()=>{var S,V;if(!h){ee.style.height="",ee.style.width="";return}let i=(V=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?V:e==null?void 0:e.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";ee.style.width=l,ee.style.maxWidth=l;let b=window.innerHeight,M=Math.max(200,b-64),k=Math.min(640,M);ee.style.height=`${k}px`};be(),window.addEventListener("resize",be),ze.push(()=>window.removeEventListener("resize",be)),gt=Y.scrollTop;let ue=()=>{let i=Y.scrollTop,l=Y.scrollHeight,b=Y.clientHeight,D=l-i-b,M=Math.abs(i-gt);if(gt=i,!Wt&&!(M<=Ut)){if(!_e&&D<mt){q=!1,_e=!0;return}_e&&D>mt&&(q=!0,xe=Date.now()+it,_e=!1)}};Y.addEventListener("scroll",ue,{passive:!0}),ze.push(()=>Y.removeEventListener("scroll",ue)),ze.push(()=>{Ue&&cancelAnimationFrame(Ue)});let y=()=>{L&&(Qe&&(L.removeEventListener("click",Qe),Qe=null),h?(L.style.display="",Qe=()=>{A=!1,ht()},L.addEventListener("click",Qe)):L.style.display="none")};y(),(()=>{let{clearChatButton:i}=Ae;i&&i.addEventListener("click",()=>{P.clearMessages();try{localStorage.removeItem(Yt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Yt}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Yt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let l=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let b=a.clear();b instanceof Promise&&b.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",D)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},B.syncFromMetadata()})})(),bt.addEventListener("submit",Rt),Z.addEventListener("keydown",Ht),ze.push(()=>{bt.removeEventListener("submit",Rt),Z.removeEventListener("keydown",Ht)}),ze.push(()=>{P.cancel()}),_&&ze.push(()=>{_==null||_.destroy()});let N={update(i){var Tn,An,Mn,Wn,En,Ln,kn,Bn,Rn,Hn,In,Pn,Fn,Nn,Dn,qn,zn,_n,On,$n,jn,Vn,Un,Kn,Xn,Yn,Jn,Gn,Zn,Qn,eo,to,no,oo,ro,so,io,ao,lo,co,uo,go,po,mo,fo,wo,ho,vo,yo;let l=e.toolCall;e={...e,...i},dn(t,e);let b=Zt.getForInstance(e.plugins);o.length=0,o.push(...b),h=(An=(Tn=e.launcher)==null?void 0:Tn.enabled)!=null?An:!0,Q=(Wn=(Mn=e.launcher)==null?void 0:Mn.autoExpand)!=null?Wn:!1,ke=(Ln=(En=e.features)==null?void 0:En.showReasoning)!=null?Ln:!0,re=(Bn=(kn=e.features)==null?void 0:kn.showToolCalls)!=null?Bn:!0,((Rn=e.launcher)==null?void 0:Rn.enabled)===!1&&_&&(_.destroy(),_=null),((Hn=e.launcher)==null?void 0:Hn.enabled)!==!1&&!_&&(_=cn(e,me),t.appendChild(_.element)),_&&_.update(e),h!==x?h?Oe(Q,"auto"):(A=!0,ht()):Q!==R&&Oe(Q,"auto"),R=Q,x=h,be(),y(),JSON.stringify(i.toolCall)!==JSON.stringify(l)&&P&&wt(ne,P.getMessages(),p);let S=(In=e.launcher)!=null?In:{},V=(Pn=S.headerIconHidden)!=null?Pn:!1,Se=S.headerIconName,O=(Fn=S.headerIconSize)!=null?Fn:"48px";if(ye){let T=ve.querySelector(".tvw-border-b-cw-divider"),Ee=T==null?void 0:T.querySelector(".tvw-flex-col");if(V)ye.style.display="none",T&&Ee&&!T.contains(Ee)&&T.insertBefore(Ee,T.firstChild);else{if(ye.style.display="",ye.style.height=O,ye.style.width=O,T&&Ee&&(T.contains(ye)?ye.nextSibling!==Ee&&(ye.remove(),T.insertBefore(ye,Ee)):T.insertBefore(ye,Ee)),Se){let qe=parseFloat(O)||24,pe=Le(Se,qe*.6,"#ffffff",2);pe?ye.replaceChildren(pe):ye.textContent=(Nn=S.agentIconText)!=null?Nn:"\u{1F4AC}"}else if(S.iconUrl){let qe=ye.querySelector("img");if(qe)qe.src=S.iconUrl,qe.style.height=O,qe.style.width=O;else{let pe=document.createElement("img");pe.src=S.iconUrl,pe.alt="",pe.className="tvw-rounded-xl tvw-object-cover",pe.style.height=O,pe.style.width=O,ye.replaceChildren(pe)}}else{let qe=ye.querySelector("svg"),pe=ye.querySelector("img");(qe||pe)&&ye.replaceChildren(),ye.textContent=(Dn=S.agentIconText)!=null?Dn:"\u{1F4AC}"}let Pe=ye.querySelector("img");Pe&&(Pe.style.height=O,Pe.style.width=O)}}if(L){let T=(qn=S.closeButtonSize)!=null?qn:"32px",Ee=(zn=S.closeButtonPlacement)!=null?zn:"inline";L.style.height=T,L.style.width=T;let Pe=Ee==="top-right",qe=L.classList.contains("tvw-absolute");if(Pe!==qe)if(L.remove(),Pe)L.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50 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",ve.style.position="relative",ve.appendChild(L);else{L.className="tvw-ml-auto 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";let oe=ve.querySelector(".tvw-border-b-cw-divider");oe&&oe.appendChild(L)}if(S.closeButtonColor?(L.style.color=S.closeButtonColor,L.classList.remove("tvw-text-cw-muted")):(L.style.color="",L.classList.add("tvw-text-cw-muted")),S.closeButtonBackgroundColor?(L.style.backgroundColor=S.closeButtonBackgroundColor,L.classList.remove("hover:tvw-bg-gray-100")):(L.style.backgroundColor="",L.classList.add("hover:tvw-bg-gray-100")),S.closeButtonBorderWidth||S.closeButtonBorderColor){let oe=S.closeButtonBorderWidth||"0px",xt=S.closeButtonBorderColor||"transparent";L.style.border=`${oe} solid ${xt}`,L.classList.remove("tvw-border-none")}else L.style.border="",L.classList.add("tvw-border-none");S.closeButtonBorderRadius?(L.style.borderRadius=S.closeButtonBorderRadius,L.classList.remove("tvw-rounded-full")):(L.style.borderRadius="",L.classList.add("tvw-rounded-full")),S.closeButtonPaddingX?(L.style.paddingLeft=S.closeButtonPaddingX,L.style.paddingRight=S.closeButtonPaddingX):(L.style.paddingLeft="",L.style.paddingRight=""),S.closeButtonPaddingY?(L.style.paddingTop=S.closeButtonPaddingY,L.style.paddingBottom=S.closeButtonPaddingY):(L.style.paddingTop="",L.style.paddingBottom="");let pe=(_n=S.closeButtonIconName)!=null?_n:"x",Mt=(On=S.closeButtonIconText)!=null?On:"\xD7";L.innerHTML="";let Ge=Le(pe,"20px",S.closeButtonColor||"",2);Ge?L.appendChild(Ge):L.textContent=Mt;let{closeButtonWrapper:Ke}=Ae,Te=($n=S.closeButtonTooltipText)!=null?$n:"Close chat",Ze=(jn=S.closeButtonShowTooltip)!=null?jn:!0;if(L.setAttribute("aria-label",Te),Ke&&(Ke._cleanupTooltip&&(Ke._cleanupTooltip(),delete Ke._cleanupTooltip),Ze&&Te)){let oe=null,xt=()=>{if(oe||!L)return;oe=u("div","tvw-clear-chat-tooltip"),oe.textContent=Te;let xo=u("div");xo.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(xo);let tn=L.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${tn.left+tn.width/2}px`,oe.style.top=`${tn.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},nt=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};Ke.addEventListener("mouseenter",xt),Ke.addEventListener("mouseleave",nt),L.addEventListener("focus",xt),L.addEventListener("blur",nt),Ke._cleanupTooltip=()=>{nt(),Ke&&(Ke.removeEventListener("mouseenter",xt),Ke.removeEventListener("mouseleave",nt)),L&&(L.removeEventListener("focus",xt),L.removeEventListener("blur",nt))}}}let{clearChatButton:W,clearChatButtonWrapper:w}=Ae;if(W){let T=(Vn=S.clearChat)!=null?Vn:{},Ee=(Un=T.enabled)!=null?Un:!0;if(w&&(w.style.display=Ee?"":"none"),Ee){let Pe=(Kn=T.size)!=null?Kn:"32px";W.style.height=Pe,W.style.width=Pe;let qe=(Xn=T.iconName)!=null?Xn:"refresh-cw",pe=(Yn=T.iconColor)!=null?Yn:"";W.innerHTML="";let Mt=Le(qe,"20px",pe||"",2);if(Mt&&W.appendChild(Mt),pe?(W.style.color=pe,W.classList.remove("tvw-text-cw-muted")):(W.style.color="",W.classList.add("tvw-text-cw-muted")),T.backgroundColor?(W.style.backgroundColor=T.backgroundColor,W.classList.remove("hover:tvw-bg-gray-100")):(W.style.backgroundColor="",W.classList.add("hover:tvw-bg-gray-100")),T.borderWidth||T.borderColor){let Te=T.borderWidth||"0px",Ze=T.borderColor||"transparent";W.style.border=`${Te} solid ${Ze}`,W.classList.remove("tvw-border-none")}else W.style.border="",W.classList.add("tvw-border-none");T.borderRadius?(W.style.borderRadius=T.borderRadius,W.classList.remove("tvw-rounded-full")):(W.style.borderRadius="",W.classList.add("tvw-rounded-full")),T.paddingX?(W.style.paddingLeft=T.paddingX,W.style.paddingRight=T.paddingX):(W.style.paddingLeft="",W.style.paddingRight=""),T.paddingY?(W.style.paddingTop=T.paddingY,W.style.paddingBottom=T.paddingY):(W.style.paddingTop="",W.style.paddingBottom="");let Ge=(Jn=T.tooltipText)!=null?Jn:"Clear chat",Ke=(Gn=T.showTooltip)!=null?Gn:!0;if(W.setAttribute("aria-label",Ge),w&&(w._cleanupTooltip&&(w._cleanupTooltip(),delete w._cleanupTooltip),Ke&&Ge)){let Te=null,Ze=()=>{if(Te||!W)return;Te=u("div","tvw-clear-chat-tooltip"),Te.textContent=Ge;let xt=u("div");xt.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(xt);let nt=W.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${nt.left+nt.width/2}px`,Te.style.top=`${nt.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},oe=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};w.addEventListener("mouseenter",Ze),w.addEventListener("mouseleave",oe),W.addEventListener("focus",Ze),W.addEventListener("blur",oe),w._cleanupTooltip=()=>{oe(),w&&(w.removeEventListener("mouseenter",Ze),w.removeEventListener("mouseleave",oe)),W&&(W.removeEventListener("focus",Ze),W.removeEventListener("blur",oe))}}}}let U=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Qt],K=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xt.message,Xt.messageAndClick];B=en({parsers:U,handlers:K,getMetadata:z,updateMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),p=Fo(e,B),P.updateConfig(e),wt(ne,P.getMessages(),p),ut.render(e.suggestionChips,P,Z,void 0,e.suggestionChipsConfig),Bt(),Tt(P.isStreaming());let Ie=((Zn=e.voiceRecognition)==null?void 0:Zn.enabled)===!0,we=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Je=Ie&&we;if(bt.classList.remove("tvw-gap-1","tvw-gap-3"),bt.classList.add(Je?"tvw-gap-1":"tvw-gap-3"),Ie&&we)if(!C||!X){let T=m(e.voiceRecognition,e.sendButton);T&&(C=T.micButton,X=T.micButtonWrapper,bt.insertBefore(X,rt),C.addEventListener("click",$),C.disabled=P.isStreaming())}else{let T=(Qn=e.voiceRecognition)!=null?Qn:{},Ee=(eo=e.sendButton)!=null?eo:{},Pe=(to=T.iconName)!=null?to:"mic",qe=(no=Ee.size)!=null?no:"40px",pe=(oo=T.iconSize)!=null?oo:qe,Mt=parseFloat(pe)||24;C.style.width=pe,C.style.height=pe,C.style.minWidth=pe,C.style.minHeight=pe;let Ge=(so=(ro=T.iconColor)!=null?ro:Ee.textColor)!=null?so:"currentColor";C.innerHTML="";let Ke=Le(Pe,Mt,Ge,2);Ke?C.appendChild(Ke):C.textContent="\u{1F3A4}";let Te=(io=T.backgroundColor)!=null?io:Ee.backgroundColor;Te?(C.style.backgroundColor=Te,C.classList.remove("tvw-bg-cw-primary")):(C.style.backgroundColor="",C.classList.add("tvw-bg-cw-primary")),Ge?(C.style.color=Ge,C.classList.remove("tvw-text-white")):!Ge&&!Ee.textColor&&(C.style.color="",C.classList.add("tvw-text-white")),T.borderWidth?(C.style.borderWidth=T.borderWidth,C.style.borderStyle="solid"):(C.style.borderWidth="",C.style.borderStyle=""),T.borderColor?C.style.borderColor=T.borderColor:C.style.borderColor="",T.paddingX?(C.style.paddingLeft=T.paddingX,C.style.paddingRight=T.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),T.paddingY?(C.style.paddingTop=T.paddingY,C.style.paddingBottom=T.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let Ze=X==null?void 0:X.querySelector(".tvw-send-button-tooltip"),oe=(ao=T.tooltipText)!=null?ao:"Start voice recognition";if(((lo=T.showTooltip)!=null?lo:!1)&&oe)if(Ze)Ze.textContent=oe,Ze.style.display="";else{let nt=document.createElement("div");nt.className="tvw-send-button-tooltip",nt.textContent=oe,X==null||X.insertBefore(nt,C)}else Ze&&(Ze.style.display="none");X.style.display="",C.disabled=P.isStreaming()}else C&&X&&(X.style.display="none",$e&&Xe());let te=(co=e.sendButton)!=null?co:{},tt=(uo=te.useIcon)!=null?uo:!1,yt=(go=te.iconText)!=null?go:"\u2191",ct=te.iconName,Pt=(po=te.tooltipText)!=null?po:"Send message",Vt=(mo=te.showTooltip)!=null?mo:!1,We=(fo=te.size)!=null?fo:"40px",pt=te.backgroundColor,je=te.textColor;if(tt){if(E.style.width=We,E.style.height=We,E.style.minWidth=We,E.style.minHeight=We,E.style.fontSize="18px",E.style.lineHeight="1",E.innerHTML="",ct){let T=parseFloat(We)||24,Ee=je&&typeof je=="string"&&je.trim()?je.trim():"currentColor",Pe=Le(ct,T,Ee,2);Pe?(E.appendChild(Pe),E.style.color=Ee):(E.textContent=yt,je?E.style.color=je:E.classList.add("tvw-text-white"))}else E.textContent=yt,je?E.style.color=je:E.classList.add("tvw-text-white");E.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",pt?(E.style.backgroundColor=pt,E.classList.remove("tvw-bg-cw-primary")):E.classList.add("tvw-bg-cw-primary")}else E.textContent=(ho=(wo=e.copy)==null?void 0:wo.sendButtonLabel)!=null?ho:"Send",E.style.width="",E.style.height="",E.style.minWidth="",E.style.minHeight="",E.style.fontSize="",E.style.lineHeight="",E.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",pt?(E.style.backgroundColor=pt,E.classList.remove("tvw-bg-cw-accent")):E.classList.add("tvw-bg-cw-accent"),je?E.style.color=je:E.classList.add("tvw-text-white");te.borderWidth?(E.style.borderWidth=te.borderWidth,E.style.borderStyle="solid"):(E.style.borderWidth="",E.style.borderStyle=""),te.borderColor?E.style.borderColor=te.borderColor:E.style.borderColor="",te.paddingX?(E.style.paddingLeft=te.paddingX,E.style.paddingRight=te.paddingX):(E.style.paddingLeft="",E.style.paddingRight=""),te.paddingY?(E.style.paddingTop=te.paddingY,E.style.paddingBottom=te.paddingY):(E.style.paddingTop="",E.style.paddingBottom="");let Ft=rt==null?void 0:rt.querySelector(".tvw-send-button-tooltip");if(Vt&&Pt)if(Ft)Ft.textContent=Pt,Ft.style.display="";else{let T=document.createElement("div");T.className="tvw-send-button-tooltip",T.textContent=Pt,rt==null||rt.insertBefore(T,E)}else Ft&&(Ft.style.display="none");let At=(vo=e.statusIndicator)!=null?vo:{},qo=(yo=At.visible)!=null?yo:!0;if(qt.style.display=qo?"":"none",P){let T=P.getStatus(),Ee=Pe=>{var qe,pe,Mt,Ge;return Pe==="idle"?(qe=At.idleText)!=null?qe:Ve.idle:Pe==="connecting"?(pe=At.connectingText)!=null?pe:Ve.connecting:Pe==="connected"?(Mt=At.connectedText)!=null?Mt:Ve.connected:Pe==="error"?(Ge=At.errorText)!=null?Ge:Ve.error:Ve[Pe]};qt.textContent=Ee(T)}},open(){h&&Oe(!0,"api")},close(){h&&Oe(!1,"api")},toggle(){h&&Oe(!A,"api")},clearChat(){P.clearMessages();try{localStorage.removeItem(Yt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Yt}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Yt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let i=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(i),a!=null&&a.clear)try{let l=a.clear();l instanceof Promise&&l.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",l)}d={},B.syncFromMetadata()},setMessage(i){return!Z||P.isStreaming()?!1:(!A&&h&&Oe(!0,"system"),Z.value=i,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(P.isStreaming())return!1;let l=(i==null?void 0:i.trim())||Z.value.trim();return l?(!A&&h&&Oe(!0,"system"),Z.value="",P.sendMessage(l),!0):!1},startVoiceRecognition(){return $e||P.isStreaming()||!It()?!1:(!A&&h&&Oe(!0,"system"),ae.manuallyDeactivated=!1,at(),vt("user"),!0)},stopVoiceRecognition(){return $e?(ae.manuallyDeactivated=!0,at(),Xe("user"),!0):!1},injectTestMessage(i){!A&&h&&Oe(!0,"system"),P.injectTestEvent(i)},getMessages(){return P.getMessages()},getStatus(){return P.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(i){g(i)},on(i,l){return s.on(i,l)},off(i,l){s.off(i,l)},isOpen(){return h&&A},isVoiceActive(){return ae.active},getState(){return{open:h&&A,launcherEnabled:h,voiceActive:ae.active,streaming:P.isStreaming()}},destroy(){ze.forEach(i=>i()),he.remove(),_==null||_.destroy(),Qe&&L.removeEventListener("click",Qe)}};if((((He=r==null?void 0:r.debugTools)!=null?He:!1)||!!e.debug)&&typeof window!="undefined"){let i=window.AgentWidgetBrowser,l={controller:N,getMessages:N.getMessages,getStatus:N.getStatus,getMetadata:N.getPersistentMetadata,updateMetadata:N.updatePersistentMetadata,clearHistory:()=>N.clearChat(),setVoiceActive:b=>b?N.startVoiceRecognition():N.stopVoiceRecognition()};window.AgentWidgetBrowser=l,ze.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=i)})}return N};var Sn={},er=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let n=document.querySelector(t);if(!n)throw new Error(`Chat widget target "${t}" was not found`);return n}return t},tr=()=>{try{if(typeof Sn!="undefined"&&Sn.url)return new URL("../widget.css",Sn.url).href}catch{}return null},No=t=>{let n=tr(),r=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let o=e.cloneNode(!0);t.insertBefore(o,t.firstChild)};if(t instanceof ShadowRoot)if(n){let e=document.createElement("link");e.rel="stylesheet",e.href=n,e.setAttribute("data-vanilla-agent","true"),t.insertBefore(e,t.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},Do=t=>{var v;let n=er(t.target),r=document.createElement("div");r.className="vanilla-agent-host",n.appendChild(r);let e=t.useShadowDom!==!1,o,s;if(e){let z=r.attachShadow({mode:"open"});s=z,o=document.createElement("div"),o.id="vanilla-agent-root",z.appendChild(o),No(z)}else s=r,o=document.createElement("div"),o.id="vanilla-agent-root",r.appendChild(o),No(r);let a=Cn(o,t.config,{debugTools:t.debugTools});(v=t.onReady)==null||v.call(t);let d={...a,host:r,destroy(){a.destroy(),r.remove(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}};return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=d),d};var nr=t=>{if(!t)return null;try{return JSON.parse(t)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},or=t=>t.map(n=>({...n,streaming:!1})),rr=(t="vanilla-agent-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?nr(r.getItem(t)):null},save:r=>{let e=n();if(e)try{let o={...r,messages:r.messages?or(r.messages):void 0};e.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(t)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var ms=Do;export{Kt as AgentWidgetClient,Jt as AgentWidgetSession,ot as DEFAULT_WIDGET_CONFIG,en as createActionManager,Cn as createAgentExperience,Uo as createFlexibleJsonStreamParser,an as createJsonStreamParser,rr as createLocalStorageAdapter,rn as createPlainTextParser,sn as createRegexJsonParser,ln as createXmlParser,ms as default,Xt as defaultActionHandlers,Qt as defaultJsonActionParser,Oo as directivePostprocessor,nn as escapeHtml,Do as initAgentWidget,So as markdownPostprocessor,yn as mergeWithDefaults,Zt as pluginRegistry};
14
+ `,r.addEventListener("click",n);let e=s=>{var G,I,x,M,m,ke,ne,Fe,Be,me;let a=(G=s.launcher)!=null?G:{},c=r.querySelector("[data-role='launcher-title']");c&&(c.textContent=(I=a.title)!=null?I:"Chat Assistant");let b=r.querySelector("[data-role='launcher-subtitle']");b&&(b.textContent=(x=a.subtitle)!=null?x:"Get answers fast");let z=r.querySelector(".tvw-flex-col");z&&(a.textHidden?z.style.display="none":z.style.display="");let g=r.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let Z=(M=a.agentIconSize)!=null?M:"40px";if(g.style.height=Z,g.style.width=Z,g.innerHTML="",a.agentIconName){let Se=parseFloat(Z)||24,fe=Ee(a.agentIconName,Se*.6,"#ffffff",2);fe?(g.appendChild(fe),g.style.display=""):(g.textContent=(m=a.agentIconText)!=null?m:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(ke=a.agentIconText)!=null?ke:"\u{1F4AC}",g.style.display="")}let F=r.querySelector("[data-role='launcher-image']");if(F){let Z=(ne=a.agentIconSize)!=null?ne:"40px";F.style.height=Z,F.style.width=Z,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(F.src=a.iconUrl,F.style.display="block"):F.style.display="none"}let H=r.querySelector("[data-role='launcher-call-to-action-icon']");if(H){let Z=(Fe=a.callToActionIconSize)!=null?Fe:"32px";H.style.height=Z,H.style.width=Z,a.callToActionIconBackgroundColor?(H.style.backgroundColor=a.callToActionIconBackgroundColor,H.classList.remove("tvw-bg-cw-primary")):(H.style.backgroundColor="",H.classList.add("tvw-bg-cw-primary"));let Se=0;if(a.callToActionIconPadding?(H.style.boxSizing="border-box",H.style.padding=a.callToActionIconPadding,Se=(parseFloat(a.callToActionIconPadding)||0)*2):(H.style.boxSizing="",H.style.padding=""),a.callToActionIconHidden)H.style.display="none";else if(H.style.display="",H.innerHTML="",a.callToActionIconName){let fe=parseFloat(Z)||24,K=Math.max(fe-Se,8),Q=Ee(a.callToActionIconName,K,"currentColor",2);Q?H.appendChild(Q):H.textContent=(Be=a.callToActionIconText)!=null?Be:"\u2197"}else H.textContent=(me=a.callToActionIconText)!=null?me:"\u2197"}let B=a.position&&Rt[a.position]?Rt[a.position]:Rt["bottom-right"],y="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=`${y} ${B}`},o=()=>{r.removeEventListener("click",n),r.remove()};return t&&e(t),{element:r,update:e,destroy:o}};var Ho=t=>{var b,z,g,F,H;if(!((z=(b=t==null?void 0:t.launcher)==null?void 0:b.enabled)!=null?z:!0)){let B=u("div","tvw-relative tvw-w-full tvw-h-full"),y=u("div","tvw-relative tvw-w-full tvw-h-full tvw-min-h-[360px]");return B.appendChild(y),{wrapper:B,panel:y}}let r=(g=t==null?void 0:t.launcher)!=null?g:{},e=r.position&&Rt[r.position]?Rt[r.position]:Rt["bottom-right"],o=u("div",`tvw-fixed ${e} tvw-z-50 tvw-transition`),s=u("div","tvw-relative tvw-min-h-[320px]"),a=(H=(F=t==null?void 0:t.launcher)==null?void 0:F.width)!=null?H:t==null?void 0:t.launcherWidth,c=a!=null?a:"min(400px, calc(100vw - 24px))";return s.style.width=c,s.style.maxWidth=c,o.appendChild(s),{wrapper:o,panel:s}},Io=(t,n=!0)=>{var xt,re,Tt,At,it,Dt,qt,Mt,ft,at,zt,_t,Ot,wt,ht,Oe,Ct,Wt,Et,Lt,De,$e,lt,Qe,kt,f,_,X,ce,Ae,Le,D,v,je,$,h,d,P,ae,le,ue,Re,Me,de,j,se,pe,ve,He,gt,Yt,i,l,C,N,W,k,T,V,ye;let r=u("div","tvw-flex tvw-h-full tvw-w-full 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"),e=u("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=(xt=t==null?void 0:t.launcher)!=null?xt:{},s=(re=o.headerIconSize)!=null?re:"48px",a=(Tt=o.closeButtonSize)!=null?Tt:"32px",c=(At=o.closeButtonPlacement)!=null?At:"inline",b=(it=o.headerIconHidden)!=null?it:!1,z=o.headerIconName,g=u("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(g.style.height=s,g.style.width=s,!b)if(z){let p=parseFloat(s)||24,w=Ee(z,p*.6,"#ffffff",2);w?g.replaceChildren(w):g.textContent=(qt=(Dt=t==null?void 0:t.launcher)==null?void 0:Dt.agentIconText)!=null?qt:"\u{1F4AC}"}else if((Mt=t==null?void 0:t.launcher)!=null&&Mt.iconUrl){let p=u("img");p.src=t.launcher.iconUrl,p.alt="",p.className="tvw-rounded-xl tvw-object-cover",p.style.height=s,p.style.width=s,g.replaceChildren(p)}else g.textContent=(at=(ft=t==null?void 0:t.launcher)==null?void 0:ft.agentIconText)!=null?at:"\u{1F4AC}";let F=u("div","tvw-flex tvw-flex-col"),H=u("span","tvw-text-base tvw-font-semibold");H.textContent=(_t=(zt=t==null?void 0:t.launcher)==null?void 0:zt.title)!=null?_t:"Chat Assistant";let B=u("span","tvw-text-xs tvw-text-cw-muted");B.textContent=(wt=(Ot=t==null?void 0:t.launcher)==null?void 0:Ot.subtitle)!=null?wt:"Here to help you get answers fast",F.append(H,B),b?e.append(F):e.append(g,F);let y=(ht=o.clearChat)!=null?ht:{},G=(Oe=y.enabled)!=null?Oe:!0,I=null,x=null;if(G){let p=(Ct=y.size)!=null?Ct:"32px",w=(Wt=y.iconName)!=null?Wt:"refresh-cw",q=(Et=y.iconColor)!=null?Et:"",be=(Lt=y.backgroundColor)!=null?Lt:"",Y=(De=y.borderWidth)!=null?De:"",qe=($e=y.borderColor)!=null?$e:"",Pe=(lt=y.borderRadius)!=null?lt:"",Xe=(Qe=y.paddingX)!=null?Qe:"",ee=(kt=y.paddingY)!=null?kt:"",et=(f=y.tooltipText)!=null?f:"Clear chat",$t=(_=y.showTooltip)!=null?_:!0;x=u("div","tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),I=u("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"),I.style.height=p,I.style.width=p,I.type="button",I.setAttribute("aria-label",et);let Bt=Ee(w,"20px",q||"",2);if(Bt&&I.appendChild(Bt),q&&(I.style.color=q,I.classList.remove("tvw-text-cw-muted")),be&&(I.style.backgroundColor=be,I.classList.remove("hover:tvw-bg-gray-100")),Y||qe){let xe=Y||"0px",pt=qe||"transparent";I.style.border=`${xe} solid ${pt}`,I.classList.remove("tvw-border-none")}if(Pe&&(I.style.borderRadius=Pe,I.classList.remove("tvw-rounded-full")),Xe?(I.style.paddingLeft=Xe,I.style.paddingRight=Xe):(I.style.paddingLeft="",I.style.paddingRight=""),ee?(I.style.paddingTop=ee,I.style.paddingBottom=ee):(I.style.paddingTop="",I.style.paddingBottom=""),x.appendChild(I),$t&&et&&I&&x){let xe=null,pt=()=>{if(xe||!I)return;xe=u("div","tvw-clear-chat-tooltip"),xe.textContent=et;let jt=u("div");jt.className="tvw-clear-chat-tooltip-arrow",xe.appendChild(jt);let Ye=I.getBoundingClientRect();xe.style.position="fixed",xe.style.left=`${Ye.left+Ye.width/2}px`,xe.style.top=`${Ye.top-8}px`,xe.style.transform="translate(-50%, -100%)",document.body.appendChild(xe)},mt=()=>{xe&&xe.parentNode&&(xe.parentNode.removeChild(xe),xe=null)};x.addEventListener("mouseenter",pt),x.addEventListener("mouseleave",mt),I.addEventListener("focus",pt),I.addEventListener("blur",mt),x._cleanupTooltip=()=>{mt(),x&&(x.removeEventListener("mouseenter",pt),x.removeEventListener("mouseleave",mt)),I&&(I.removeEventListener("focus",pt),I.removeEventListener("blur",mt))}}e.appendChild(x)}let M=u("div",c==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":G?"":"tvw-ml-auto"),m=u("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=a,m.style.width=a,m.type="button";let ke=(X=o.closeButtonTooltipText)!=null?X:"Close chat",ne=(ce=o.closeButtonShowTooltip)!=null?ce:!0;m.setAttribute("aria-label",ke),m.style.display=n?"":"none";let Fe=(Ae=o.closeButtonIconName)!=null?Ae:"x",Be=(Le=o.closeButtonIconText)!=null?Le:"\xD7",me=Ee(Fe,"20px",o.closeButtonColor||"",2);if(me?m.appendChild(me):m.textContent=Be,o.closeButtonColor?(m.style.color=o.closeButtonColor,m.classList.remove("tvw-text-cw-muted")):(m.style.color="",m.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(m.style.backgroundColor=o.closeButtonBackgroundColor,m.classList.remove("hover:tvw-bg-gray-100")):(m.style.backgroundColor="",m.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let p=o.closeButtonBorderWidth||"0px",w=o.closeButtonBorderColor||"transparent";m.style.border=`${p} solid ${w}`,m.classList.remove("tvw-border-none")}else m.style.border="",m.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(m.style.borderRadius=o.closeButtonBorderRadius,m.classList.remove("tvw-rounded-full")):(m.style.borderRadius="",m.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(m.style.paddingLeft=o.closeButtonPaddingX,m.style.paddingRight=o.closeButtonPaddingX):(m.style.paddingLeft="",m.style.paddingRight=""),o.closeButtonPaddingY?(m.style.paddingTop=o.closeButtonPaddingY,m.style.paddingBottom=o.closeButtonPaddingY):(m.style.paddingTop="",m.style.paddingBottom=""),M.appendChild(m),ne&&ke){let p=null,w=()=>{if(p)return;p=u("div","tvw-clear-chat-tooltip"),p.textContent=ke;let be=u("div");be.className="tvw-clear-chat-tooltip-arrow",p.appendChild(be);let Y=m.getBoundingClientRect();p.style.position="fixed",p.style.left=`${Y.left+Y.width/2}px`,p.style.top=`${Y.top-8}px`,p.style.transform="translate(-50%, -100%)",document.body.appendChild(p)},q=()=>{p&&p.parentNode&&(p.parentNode.removeChild(p),p=null)};M.addEventListener("mouseenter",w),M.addEventListener("mouseleave",q),m.addEventListener("focus",w),m.addEventListener("blur",q),M._cleanupTooltip=()=>{q(),M.removeEventListener("mouseenter",w),M.removeEventListener("mouseleave",q),m.removeEventListener("focus",w),m.removeEventListener("blur",q)}}c==="top-right"?(r.style.position="relative",r.appendChild(M)):e.appendChild(M);let Z=u("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");Z.id="vanilla-agent-scroll-container";let Se=u("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),fe=u("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");fe.textContent=(v=(D=t==null?void 0:t.copy)==null?void 0:D.welcomeTitle)!=null?v:"Hello \u{1F44B}";let K=u("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");K.textContent=($=(je=t==null?void 0:t.copy)==null?void 0:je.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",Se.append(fe,K);let Q=u("div","tvw-flex tvw-flex-col tvw-gap-3");Z.append(Se,Q);let Ht=u("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),J=u("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),E=((h=t==null?void 0:t.voiceRecognition)==null?void 0:h.enabled)===!0,ot=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),rt=u("form",`tvw-flex tvw-items-end ${E&&ot?"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`);rt.style.outline="none";let oe=u("textarea");oe.placeholder=(P=(d=t==null?void 0:t.copy)==null?void 0:d.inputPlaceholder)!=null?P:"Type your message\u2026",oe.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",oe.rows=1;let L=(le=(ae=t==null?void 0:t.theme)==null?void 0:ae.inputFontFamily)!=null?le:"sans-serif",we=(Re=(ue=t==null?void 0:t.theme)==null?void 0:ue.inputFontWeight)!=null?Re:"400",Pt=p=>{switch(p){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'}};oe.style.fontFamily=Pt(L),oe.style.fontWeight=we,oe.style.border="none",oe.style.outline="none",oe.style.borderWidth="0",oe.style.borderStyle="none",oe.style.borderColor="transparent",oe.addEventListener("focus",()=>{oe.style.border="none",oe.style.outline="none",oe.style.borderWidth="0",oe.style.borderStyle="none",oe.style.borderColor="transparent",oe.style.boxShadow="none"}),oe.addEventListener("blur",()=>{oe.style.border="none",oe.style.outline="none"});let he=(Me=t==null?void 0:t.sendButton)!=null?Me:{},S=(de=he.useIcon)!=null?de:!1,Ne=(j=he.iconText)!=null?j:"\u2191",_e=he.iconName,dt=(se=he.tooltipText)!=null?se:"Send message",st=(pe=he.showTooltip)!=null?pe:!1,R=(ve=he.size)!=null?ve:"40px",ct=he.backgroundColor,Te=he.textColor,Ze=u("div","tvw-send-button-wrapper"),O=u("button",S?"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(O.type="submit",S){if(O.style.width=R,O.style.height=R,O.style.minWidth=R,O.style.minHeight=R,O.style.fontSize="18px",O.style.lineHeight="1",O.innerHTML="",_e){let p=parseFloat(R)||24,w=Te&&typeof Te=="string"&&Te.trim()?Te.trim():"currentColor",q=Ee(_e,p,w,2);q?(O.appendChild(q),O.style.color=w):(O.textContent=Ne,Te?O.style.color=Te:O.classList.add("tvw-text-white"))}else O.textContent=Ne,Te?O.style.color=Te:O.classList.add("tvw-text-white");ct?O.style.backgroundColor=ct:O.classList.add("tvw-bg-cw-primary")}else O.textContent=(gt=(He=t==null?void 0:t.copy)==null?void 0:He.sendButtonLabel)!=null?gt:"Send",Te?O.style.color=Te:O.classList.add("tvw-text-white");if(he.borderWidth&&(O.style.borderWidth=he.borderWidth,O.style.borderStyle="solid"),he.borderColor&&(O.style.borderColor=he.borderColor),he.paddingX?(O.style.paddingLeft=he.paddingX,O.style.paddingRight=he.paddingX):(O.style.paddingLeft="",O.style.paddingRight=""),he.paddingY?(O.style.paddingTop=he.paddingY,O.style.paddingBottom=he.paddingY):(O.style.paddingTop="",O.style.paddingBottom=""),st&&dt){let p=u("div","tvw-send-button-tooltip");p.textContent=dt,Ze.appendChild(p)}Ze.appendChild(O);let ie=(Yt=t==null?void 0:t.voiceRecognition)!=null?Yt:{},ut=ie.enabled===!0,U=null,Ke=null,Vt=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(ut&&Vt){Ke=u("div","tvw-send-button-wrapper"),U=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),U.type="button",U.setAttribute("aria-label","Start voice recognition");let p=(i=ie.iconName)!=null?i:"mic",w=(l=ie.iconSize)!=null?l:R,q=parseFloat(w)||24,be=(C=ie.backgroundColor)!=null?C:ct,Y=(N=ie.iconColor)!=null?N:Te;U.style.width=w,U.style.height=w,U.style.minWidth=w,U.style.minHeight=w,U.style.fontSize="18px",U.style.lineHeight="1";let qe=Y||"currentColor",Pe=Ee(p,q,qe,1.5);Pe?(U.appendChild(Pe),U.style.color=qe):(U.textContent="\u{1F3A4}",U.style.color=qe),be?U.style.backgroundColor=be:U.classList.add("tvw-bg-cw-primary"),Y?U.style.color=Y:!Y&&!Te&&U.classList.add("tvw-text-white"),ie.borderWidth&&(U.style.borderWidth=ie.borderWidth,U.style.borderStyle="solid"),ie.borderColor&&(U.style.borderColor=ie.borderColor),ie.paddingX&&(U.style.paddingLeft=ie.paddingX,U.style.paddingRight=ie.paddingX),ie.paddingY&&(U.style.paddingTop=ie.paddingY,U.style.paddingBottom=ie.paddingY),Ke.appendChild(U);let Xe=(W=ie.tooltipText)!=null?W:"Start voice recognition";if(((k=ie.showTooltip)!=null?k:!1)&&Xe){let et=u("div","tvw-send-button-tooltip");et.textContent=Xe,Ke.appendChild(et)}}rt.addEventListener("click",p=>{p.target!==O&&p.target!==Ze&&p.target!==U&&p.target!==Ke&&oe.focus()}),rt.append(oe),Ke&&rt.append(Ke),rt.append(Ze);let bt=u("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Ft=(T=t==null?void 0:t.statusIndicator)!=null?T:{},Nt=(V=Ft.visible)!=null?V:!0;return bt.style.display=Nt?"":"none",bt.textContent=(ye=Ft.idleText)!=null?ye:"Online",Ht.append(J,rt,bt),r.append(e,Z,Ht),{container:r,body:Z,messagesWrapper:Q,suggestions:J,textarea:oe,sendButton:O,sendButtonWrapper:Ze,micButton:U,micButtonWrapper:Ke,composerForm:rt,statusText:bt,introTitle:fe,introSubtitle:K,closeButton:m,closeButtonWrapper:M,clearChatButton:I,clearChatButtonWrapper:x,iconHolder:g,headerTitle:H,headerSubtitle:B}};var pn=()=>{let t=document.createElement("div");t.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.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 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="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",t.appendChild(n),t.appendChild(r),t.appendChild(e),t.appendChild(o),t},mn=(t,n)=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"];t.role==="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");let e=u("div",r.join(" ")),o=document.createElement("div");if(o.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(o),t.streaming&&t.role==="assistant"&&(!t.content||!t.content.trim())){let s=pn();e.appendChild(s)}return e};var fn=new Set,wn=t=>{let n=t.reasoning,r=u("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(!n)return r;let e=fn.has(t.id),o=u("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",e?"true":"false");let s=u("div","tvw-flex tvw-flex-col tvw-text-left"),a=u("span","tvw-text-xs tvw-text-cw-primary");a.textContent="Thinking...",s.appendChild(a);let c=u("span","tvw-text-xs tvw-text-cw-primary");c.textContent=Bo(n),s.appendChild(c),n.status==="complete"?a.style.display="none":a.style.display="";let b=u("div","tvw-flex tvw-items-center"),g=Ee(e?"chevron-up":"chevron-down",16,"currentColor",2);g?b.appendChild(g):b.textContent=e?"Hide":"Show";let F=u("div","tvw-flex tvw-items-center tvw-ml-auto");F.append(b),o.append(s,F);let H=u("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");H.style.display=e?"":"none";let B=n.chunks.join(""),y=u("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");y.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),H.appendChild(y);let G=()=>{o.setAttribute("aria-expanded",e?"true":"false"),b.innerHTML="";let M=Ee(e?"chevron-up":"chevron-down",16,"currentColor",2);M?b.appendChild(M):b.textContent=e?"Hide":"Show",H.style.display=e?"":"none"},I=()=>{e=!e,e?fn.add(t.id):fn.delete(t.id),G()};return o.addEventListener("pointerdown",x=>{x.preventDefault(),I()}),o.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),I())}),G(),r.append(o,H),r};var hn=new Set,vn=(t,n)=>{var I;let r=t.toolCall,e=(I=n==null?void 0:n.toolCall)!=null?I:{},o=u("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(e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=hn.has(t.id),a=u("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");a.type="button",a.setAttribute("aria-expanded",s?"true":"false"),e.headerBackgroundColor&&(a.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(a.style.paddingLeft=e.headerPaddingX,a.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(a.style.paddingTop=e.headerPaddingY,a.style.paddingBottom=e.headerPaddingY);let c=u("div","tvw-flex tvw-flex-col tvw-text-left"),b=u("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(b.style.color=e.headerTextColor),b.textContent=Ro(r),c.appendChild(b);let z=u("div","tvw-flex tvw-items-center"),g=e.toggleTextColor||e.headerTextColor||"currentColor",F=Ee(s?"chevron-up":"chevron-down",16,g,2);F?z.appendChild(F):z.textContent=s?"Hide":"Show";let H=u("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");H.append(z),a.append(c,H);let B=u("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",e.contentBackgroundColor&&(B.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(B.style.color=e.contentTextColor),e.contentPaddingX&&(B.style.paddingLeft=e.contentPaddingX,B.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(B.style.paddingTop=e.contentPaddingY,B.style.paddingBottom=e.contentPaddingY),r.name){let x=u("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?x.style.color=e.contentTextColor:e.headerTextColor&&(x.style.color=e.headerTextColor),x.textContent=r.name,B.appendChild(x)}if(r.args!==void 0){let x=u("div","tvw-space-y-1"),M=u("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(M.style.color=e.labelTextColor),M.textContent="Arguments";let m=u("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");m.style.fontSize="0.75rem",m.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(m.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(m.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(m.style.color=e.codeBlockTextColor),m.textContent=sn(r.args),x.append(M,m),B.appendChild(x)}if(r.chunks&&r.chunks.length){let x=u("div","tvw-space-y-1"),M=u("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(M.style.color=e.labelTextColor),M.textContent="Activity";let m=u("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");m.style.fontSize="0.75rem",m.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(m.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(m.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(m.style.color=e.codeBlockTextColor),m.textContent=r.chunks.join(`
15
+ `),x.append(M,m),B.appendChild(x)}if(r.status==="complete"&&r.result!==void 0){let x=u("div","tvw-space-y-1"),M=u("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(M.style.color=e.labelTextColor),M.textContent="Result";let m=u("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");m.style.fontSize="0.75rem",m.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(m.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(m.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(m.style.color=e.codeBlockTextColor),m.textContent=sn(r.result),x.append(M,m),B.appendChild(x)}if(r.status==="complete"&&typeof r.duration=="number"){let x=u("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(x.style.color=e.contentTextColor),x.textContent=`Duration: ${r.duration}ms`,B.appendChild(x)}let y=()=>{a.setAttribute("aria-expanded",s?"true":"false"),z.innerHTML="";let x=e.toggleTextColor||e.headerTextColor||"currentColor",M=Ee(s?"chevron-up":"chevron-down",16,x,2);M?z.appendChild(M):z.textContent=s?"Hide":"Show",B.style.display=s?"":"none"},G=()=>{s=!s,s?hn.add(t.id):hn.delete(t.id),y()};return a.addEventListener("pointerdown",x=>{x.preventDefault(),G()}),a.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),G())}),y(),o.append(a,B),o};var Po=t=>{let n=[];return{buttons:n,render:(e,o,s,a,c)=>{if(t.innerHTML="",n.length=0,!e||!e.length||(a!=null?a:o?o.getMessages():[]).some(B=>B.role==="user"))return;let g=document.createDocumentFragment(),F=o?o.isStreaming():!1,H=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'}};e.forEach(B=>{let y=u("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");y.type="button",y.textContent=B,y.disabled=F,c!=null&&c.fontFamily&&(y.style.fontFamily=H(c.fontFamily)),c!=null&&c.fontWeight&&(y.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(y.style.paddingLeft=c.paddingX,y.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(y.style.paddingTop=c.paddingY,y.style.paddingBottom=c.paddingY),y.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(B))}),g.appendChild(y),n.push(y)}),t.appendChild(g)}}};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"}},yn=(t,n,r,e)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,G,I;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let c=(G=Fo[a])!=null?G:Fo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let b=u("div","tvw-space-y-1"),z=u("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(z.textContent=c.title,b.appendChild(z),c.description){let x=u("p","tvw-text-sm tvw-text-cw-muted");x.textContent=c.description,b.appendChild(x)}let g=document.createElement("form");g.className="tvw-form-grid tvw-space-y-3",c.fields.forEach(x=>{var Fe,Be;let M=u("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");M.htmlFor=`${n.id}-${a}-${x.name}`;let m=u("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");m.textContent=x.label,M.appendChild(m);let ke=(Fe=x.type)!=null?Fe:"text",ne;ke==="textarea"?(ne=document.createElement("textarea"),ne.rows=3):(ne=document.createElement("input"),ne.type=ke),ne.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",ne.id=`${n.id}-${a}-${x.name}`,ne.name=x.name,ne.placeholder=(Be=x.placeholder)!=null?Be:"",x.required&&(ne.required=!0),M.appendChild(ne),g.appendChild(M)});let F=u("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),H=u("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),B=u("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=(I=c.submitLabel)!=null?I:"Submit",F.appendChild(H),F.appendChild(B),g.appendChild(F),s.replaceChildren(b,g),g.addEventListener("submit",async x=>{var ne,Fe;x.preventDefault();let M=(ne=r.formEndpoint)!=null?ne:"/form",m=new FormData(g),ke={};m.forEach((Be,me)=>{ke[me]=Be}),ke.type=a,B.disabled=!0,H.textContent="Submitting\u2026";try{let Be=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ke)});if(!Be.ok)throw new Error(`Form submission failed (${Be.status})`);let me=await Be.json();H.textContent=(Fe=me.message)!=null?Fe:"Thanks! We'll be in touch soon.",me.success&&me.nextPrompt&&await e.sendMessage(String(me.nextPrompt))}catch(Be){H.textContent=Be instanceof Error?Be.message:"Something went wrong. Please try again."}finally{B.disabled=!1}})})};var bn=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var e;let r=this.plugins.get(n);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let e=new Set(n.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...n].sort((s,a)=>{var c,b;return((c=a.priority)!=null?c:0)-((b=s.priority)!=null?b:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},en=new bn;var nt={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,iconName:"refresh-cw",size:"29px",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"},debug:!1};function xn(t){var n,r,e;return t?{...nt,...t,theme:{...nt.theme,...t.theme},launcher:{...nt.launcher,...t.launcher,clearChat:{...(n=nt.launcher)==null?void 0:n.clearChat,...(r=t.launcher)==null?void 0:r.clearChat}},copy:{...nt.copy,...t.copy},sendButton:{...nt.sendButton,...t.sendButton},statusIndicator:{...nt.statusIndicator,...t.statusIndicator},voiceRecognition:{...nt.voiceRecognition,...t.voiceRecognition},features:{...nt.features,...t.features},suggestionChips:(e=t.suggestionChips)!=null?e:nt.suggestionChips,suggestionChipsConfig:{...nt.suggestionChipsConfig,...t.suggestionChipsConfig}}:nt}var No=()=>{let t=new Map,n=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:n,off:r,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(c=>{try{c(s)}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",b)}})}}};var tr=t=>{let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:t},nr=t=>{let n=t.trim(),r=n.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return n.slice(r,o+1)}return null},tn=({text:t})=>{if(!t||!t.includes("{"))return null;try{let n=tr(t),r=nr(n);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},Cn=t=>typeof t=="string"?t:t==null?"":String(t),Kt={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Cn(t.payload.text)},messageAndClick:(t,n)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,e=Cn(r.element);if(e&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Cn(r.text)}}},Do=t=>Array.isArray(t)?t.map(n=>String(n)):[],nn=t=>{let n=new Set(Do(t.getMetadata().processedActionMessageIds)),r=()=>{n=new Set(Do(t.getMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(n);t.updateMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&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 c=a?t.parsers.reduce((z,g)=>z||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!c)return null;n.add(s.message.id),e();let b={action:c,message:s.message};t.emit("action:detected",b);for(let z of t.handlers)if(z)try{let g=z(c,{message:s.message,metadata:t.getMetadata(),updateMetadata:t.updateMetadata,document:t.documentRef});if(!g)continue;if(g.handled){let F=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:F}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:r}};var Xt="vanilla-agent-chat-history",or=30*1e3,Sn=t=>!t||typeof t!="object"?{}:{...t},qo=t=>t.map(n=>({...n,streaming:!1})),zo=(t,n)=>r=>{var s,a,c;let e=(s=r.text)!=null?s:"",o=(a=r.message.rawContent)!=null?a:null;if(n){let b=n.process({text:e,raw:o!=null?o:e,message:r.message,streaming:r.streaming});b!==null&&(e=b.text,b.persist||(r.message.__skipPersist=!0))}return t!=null&&t.postprocessMessage?t.postprocessMessage({...r,text:e,raw:(c=o!=null?o:r.text)!=null?c:""}):rn(e)},Tn=(t,n,r)=>{var ae,le,ue,Re,Me,de,j,se,pe,ve,He,gt,Yt;(!t.id||t.id!=="vanilla-agent-root")&&(t.id="vanilla-agent-root");let e=xn(n);un(t,e);let o=en.getForInstance(e.plugins),s=No(),a=e.storageAdapter,c={},b=null;if(a!=null&&a.load)try{let i=a.load();if(i&&typeof i.then=="function")b=i;else if(i){let l=i;l.metadata&&(c=Sn(l.metadata)),(ae=l.messages)!=null&&ae.length&&(e={...e,initialMessages:l.messages})}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",i)}let z=()=>c,g=i=>{var C;c=(C=i({...c}))!=null?C:{},Mt()},F=e.actionParsers&&e.actionParsers.length?e.actionParsers:[tn],H=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Kt.message,Kt.messageAndClick],B=nn({parsers:F,handlers:H,getMetadata:z,updateMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});B.syncFromMetadata();let y=(ue=(le=e.launcher)==null?void 0:le.enabled)!=null?ue:!0,G=(Me=(Re=e.launcher)==null?void 0:Re.autoExpand)!=null?Me:!1,I=G,x=y,M=y?G:!0,m=zo(e,B),ke=(j=(de=e.features)==null?void 0:de.showReasoning)!=null?j:!0,ne=(pe=(se=e.features)==null?void 0:se.showToolCalls)!=null?pe:!0,Fe=(ve=e.statusIndicator)!=null?ve:{},Be=i=>{var l,C,N,W;return i==="idle"?(l=Fe.idleText)!=null?l:Ve.idle:i==="connecting"?(C=Fe.connectingText)!=null?C:Ve.connecting:i==="connected"?(N=Fe.connectedText)!=null?N:Ve.connected:i==="error"?(W=Fe.errorText)!=null?W:Ve.error:Ve[i]},{wrapper:me,panel:Z}=Ho(e),Se=Io(e,y),{container:fe,body:K,messagesWrapper:Q,suggestions:Ht,textarea:J,sendButton:E,sendButtonWrapper:ot,composerForm:yt,statusText:It,introTitle:rt,introSubtitle:oe,closeButton:L,iconHolder:we,headerTitle:Pt,headerSubtitle:he}=Se,S=Se.micButton,Ne=Se.micButtonWrapper;Z.appendChild(fe),t.appendChild(me);let _e=[],dt=Po(Ht),st=null,R,ct=!1,Te=!0,Ze=0,O=0,ie=null,ut=!1,U=0,Ke=!1,Vt=125,bt=2e3,Ft=5,Nt=50,xt=new Map,re={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Tt=(gt=(He=e.voiceRecognition)==null?void 0:He.autoResume)!=null?gt:!1,At=i=>{s.emit("voice:state",{active:re.active,source:i,timestamp:Date.now()})},it=()=>{g(i=>({...i,voiceState:{active:re.active,timestamp:Date.now(),manuallyDeactivated:re.manuallyDeactivated}}))},Dt=()=>{var N,W;if(((N=e.voiceRecognition)==null?void 0:N.enabled)===!1)return;let i=Sn(c.voiceState),l=!!i.active,C=Number((W=i.timestamp)!=null?W:0);re.manuallyDeactivated=!!i.manuallyDeactivated,l&&Date.now()-C<or&&setTimeout(()=>{re.active||(re.manuallyDeactivated=!1,f("restore"))},1e3)},qt=()=>R?qo(R.getMessages()).filter(i=>!i.__skipPersist):[];function Mt(i){if(!(a!=null&&a.save)||!R)return;let l={messages:i?qo(i):qt(),metadata:c};try{let C=a.save(l);C instanceof Promise&&C.catch(N=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",N)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)}}let ft=(i=!1)=>{if(!Te)return;let l=Date.now();ut&&l<U&&!i||(ut&&l>=U&&(ut=!1),!(!i&&!ct)&&(l-O<Vt||(O=l,ie&&cancelAnimationFrame(ie),ie=requestAnimationFrame(()=>{ut||!Te||(Ke=!0,K.scrollTop=K.scrollHeight,Ze=K.scrollTop,requestAnimationFrame(()=>{Ke=!1}),ie=null)}))))},at=null,zt=()=>me.querySelector("#vanilla-agent-scroll-container")||K,_t=(i,l=500)=>{let C=i.scrollTop,N=i.clientHeight,W=i.scrollHeight,k=W-C;if(C+N>=W-2||Math.abs(k)<5)return;at!==null&&(cancelAnimationFrame(at),at=null);let V=performance.now(),ye=w=>1-Math.pow(1-w,3),p=w=>{let q=i.scrollHeight;q!==W&&(W=q,k=W-C);let be=w-V,Y=Math.min(be/l,1),qe=ye(Y),Pe=C+k*qe;i.scrollTop=Pe,Y<1?at=requestAnimationFrame(p):(i.scrollTop=i.scrollHeight,at=null)};at=requestAnimationFrame(p)},Ot=i=>{let l=new Map;i.forEach(C=>{let N=xt.get(C.id);l.set(C.id,{streaming:C.streaming,role:C.role}),!N&&C.role==="assistant"&&s.emit("assistant:message",C),C.role==="assistant"&&(N!=null&&N.streaming)&&C.streaming===!1&&s.emit("assistant:complete",C)}),xt.clear(),l.forEach((C,N)=>{xt.set(N,C)})},wt=(i,l,C)=>{i.innerHTML="";let N=document.createDocumentFragment();l.forEach(k=>{let T=null,V=o.find(p=>!!(k.variant==="reasoning"&&p.renderReasoning||k.variant==="tool"&&p.renderToolCall||!k.variant&&p.renderMessage));if(V)if(k.variant==="reasoning"&&k.reasoning&&V.renderReasoning){if(!ke)return;T=V.renderReasoning({message:k,defaultRenderer:()=>wn(k),config:e})}else if(k.variant==="tool"&&k.toolCall&&V.renderToolCall){if(!ne)return;T=V.renderToolCall({message:k,defaultRenderer:()=>vn(k,e),config:e})}else V.renderMessage&&(T=V.renderMessage({message:k,defaultRenderer:()=>{let p=mn(k,C);return k.role!=="user"&&yn(p,k,e,R),p},config:e}));if(!T)if(k.variant==="reasoning"&&k.reasoning){if(!ke)return;T=wn(k)}else if(k.variant==="tool"&&k.toolCall){if(!ne)return;T=vn(k,e)}else T=mn(k,C),k.role!=="user"&&yn(T,k,e,R);let ye=document.createElement("div");ye.className="tvw-flex",k.role==="user"&&ye.classList.add("tvw-justify-end"),ye.appendChild(T),N.appendChild(ye)});let W=l.some(k=>k.role==="assistant"&&k.streaming);if(ct&&l.some(k=>k.role==="user")&&!W){let k=pn(),T=document.createElement("div");T.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(" "),T.appendChild(k);let V=document.createElement("div");V.className="tvw-flex",V.appendChild(T),N.appendChild(V)}i.appendChild(N),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let k=zt();_t(k)})})},ht=()=>{y&&(M?(me.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Z.classList.remove("tvw-scale-95","tvw-opacity-0"),Z.classList.add("tvw-scale-100","tvw-opacity-100"),D&&(D.element.style.display="none")):(me.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Z.classList.remove("tvw-scale-100","tvw-opacity-100"),Z.classList.add("tvw-scale-95","tvw-opacity-0"),D&&(D.element.style.display="")))},Oe=(i,l="user")=>{if(!y||M===i)return;let C=M;M=i,ht(),M&&(v(),ft(!0));let N={open:M,source:l,timestamp:Date.now()};M&&!C?s.emit("widget:opened",N):!M&&C&&s.emit("widget:closed",N),s.emit("widget:state",{open:M,launcherEnabled:y,voiceActive:re.active,streaming:R.isStreaming()})},Ct=i=>{J.disabled=i,E.disabled=i,S&&(S.disabled=i),dt.buttons.forEach(l=>{l.disabled=i})},Wt=()=>{var W,k,T,V,ye,p,w,q,be,Y,qe,Pe,Xe,ee;rt.textContent=(k=(W=e.copy)==null?void 0:W.welcomeTitle)!=null?k:"Hello \u{1F44B}",oe.textContent=(V=(T=e.copy)==null?void 0:T.welcomeSubtitle)!=null?V:"Ask anything about your account or products.",J.placeholder=(p=(ye=e.copy)==null?void 0:ye.inputPlaceholder)!=null?p:"How can I help...",((q=(w=e.sendButton)==null?void 0:w.useIcon)!=null?q:!1)||(E.textContent=(Y=(be=e.copy)==null?void 0:be.sendButtonLabel)!=null?Y:"Send");let l=(Pe=(qe=e.theme)==null?void 0:qe.inputFontFamily)!=null?Pe:"sans-serif",C=(ee=(Xe=e.theme)==null?void 0:Xe.inputFontWeight)!=null?ee:"400",N=et=>{switch(et){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'}};J.style.fontFamily=N(l),J.style.fontWeight=C};R=new Zt(e,{onMessagesChanged(i){wt(Q,i,m),R&&(i.some(N=>N.role==="user")?dt.render([],R,J,i):dt.render(e.suggestionChips,R,J,i,e.suggestionChipsConfig)),ft(!ct),Ot(i);let l=[...i].reverse().find(C=>C.role==="user");re.lastUserMessageWasVoice=!!(l!=null&&l.viaVoice),Mt(i)},onStatusChanged(i){var N;let l=(N=e.statusIndicator)!=null?N:{},C=W=>{var k,T,V,ye;return W==="idle"?(k=l.idleText)!=null?k:Ve.idle:W==="connecting"?(T=l.connectingText)!=null?T:Ve.connecting:W==="connected"?(V=l.connectedText)!=null?V:Ve.connected:W==="error"?(ye=l.errorText)!=null?ye:Ve.error:Ve[W]};It.textContent=C(i)},onStreamingChanged(i){ct=i,Ct(i),R&&wt(Q,R.getMessages(),m),i||ft(!0)}}),b&&b.then(i=>{var l;i&&(i.metadata&&(c=Sn(i.metadata),B.syncFromMetadata()),(l=i.messages)!=null&&l.length&&R.hydrateMessages(i.messages))}).catch(i=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)});let Et=i=>{i.preventDefault();let l=J.value.trim();l&&(J.value="",R.sendMessage(l))},Lt=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),E.click())},De=null,$e=!1,lt=null,Qe=null,kt=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,f=(i="user")=>{var k,T,V,ye;if($e||R.isStreaming())return;let l=kt();if(!l)return;De=new l;let N=(T=((k=e.voiceRecognition)!=null?k:{}).pauseDuration)!=null?T:2e3;De.continuous=!0,De.interimResults=!0,De.lang="en-US";let W=J.value;De.onresult=p=>{let w="",q="";for(let Y=0;Y<p.results.length;Y++){let qe=p.results[Y],Pe=qe[0].transcript;qe.isFinal?w+=Pe+" ":q=Pe}let be=W+w+q;J.value=be,lt&&clearTimeout(lt),(w||q)&&(lt=window.setTimeout(()=>{let Y=J.value.trim();Y&&De&&$e&&(_(),J.value="",R.sendMessage(Y,{viaVoice:!0}))},N))},De.onerror=p=>{p.error!=="no-speech"&&_()},De.onend=()=>{if($e){let p=J.value.trim();p&&p!==W.trim()&&(J.value="",R.sendMessage(p,{viaVoice:!0})),_()}};try{if(De.start(),$e=!0,re.active=!0,i!=="system"&&(re.manuallyDeactivated=!1),At(i),it(),S){Qe={backgroundColor:S.style.backgroundColor,color:S.style.color,borderColor:S.style.borderColor};let p=(V=e.voiceRecognition)!=null?V:{},w=(ye=p.recordingBackgroundColor)!=null?ye:"#ef4444",q=p.recordingIconColor,be=p.recordingBorderColor;if(S.classList.add("tvw-voice-recording"),S.style.backgroundColor=w,q){S.style.color=q;let Y=S.querySelector("svg");Y&&Y.setAttribute("stroke",q)}be&&(S.style.borderColor=be),S.setAttribute("aria-label","Stop voice recognition")}}catch{_("system")}},_=(i="user")=>{if($e){if($e=!1,lt&&(clearTimeout(lt),lt=null),De){try{De.stop()}catch{}De=null}if(re.active=!1,At(i),it(),S){if(S.classList.remove("tvw-voice-recording"),Qe){S.style.backgroundColor=Qe.backgroundColor,S.style.color=Qe.color,S.style.borderColor=Qe.borderColor;let l=S.querySelector("svg");l&&l.setAttribute("stroke",Qe.color||"currentColor"),Qe=null}S.setAttribute("aria-label","Start voice recognition")}}},X=(i,l)=>{var Pe,Xe,ee,et,$t,Bt,xe;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let N=u("div","tvw-send-button-wrapper"),W=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");W.type="button",W.setAttribute("aria-label","Start voice recognition");let k=(Pe=i==null?void 0:i.iconName)!=null?Pe:"mic",T=(Xe=l==null?void 0:l.size)!=null?Xe:"40px",V=(ee=i==null?void 0:i.iconSize)!=null?ee:T,ye=parseFloat(V)||24,p=(et=i==null?void 0:i.backgroundColor)!=null?et:l==null?void 0:l.backgroundColor,w=($t=i==null?void 0:i.iconColor)!=null?$t:l==null?void 0:l.textColor;W.style.width=V,W.style.height=V,W.style.minWidth=V,W.style.minHeight=V,W.style.fontSize="18px",W.style.lineHeight="1";let q=w||"currentColor",be=Ee(k,ye,q,1.5);be?(W.appendChild(be),W.style.color=q):(W.textContent="\u{1F3A4}",W.style.color=q),p?W.style.backgroundColor=p:W.classList.add("tvw-bg-cw-primary"),w?W.style.color=w:!w&&!(l!=null&&l.textColor)&&W.classList.add("tvw-text-white"),i!=null&&i.borderWidth&&(W.style.borderWidth=i.borderWidth,W.style.borderStyle="solid"),i!=null&&i.borderColor&&(W.style.borderColor=i.borderColor),i!=null&&i.paddingX&&(W.style.paddingLeft=i.paddingX,W.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(W.style.paddingTop=i.paddingY,W.style.paddingBottom=i.paddingY),N.appendChild(W);let Y=(Bt=i==null?void 0:i.tooltipText)!=null?Bt:"Start voice recognition";if(((xe=i==null?void 0:i.showTooltip)!=null?xe:!1)&&Y){let pt=u("div","tvw-send-button-tooltip");pt.textContent=Y,N.appendChild(pt)}return{micButton:W,micButtonWrapper:N}},ce=()=>{if($e){let i=J.value.trim();re.manuallyDeactivated=!0,it(),_("user"),i&&(J.value="",R.sendMessage(i))}else re.manuallyDeactivated=!1,it(),f("user")};S&&(S.addEventListener("click",ce),_e.push(()=>{_("system"),S&&S.removeEventListener("click",ce)}));let Ae=s.on("assistant:complete",()=>{Tt&&(re.active||re.manuallyDeactivated||Tt==="assistant"&&!re.lastUserMessageWasVoice||setTimeout(()=>{!re.active&&!re.manuallyDeactivated&&f("auto")},600))});_e.push(Ae);let Le=()=>{Oe(!M,"user")},D=y?gn(e,Le):null;D&&t.appendChild(D.element),ht(),dt.render(e.suggestionChips,R,J,void 0,e.suggestionChipsConfig),Wt(),Ct(R.isStreaming()),ft(!0),Dt();let v=()=>{var T,V;if(!y){Z.style.height="",Z.style.width="";return}let i=(V=(T=e==null?void 0:e.launcher)==null?void 0:T.width)!=null?V:e==null?void 0:e.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";Z.style.width=l,Z.style.maxWidth=l;let C=window.innerHeight,W=Math.max(200,C-64),k=Math.min(640,W);Z.style.height=`${k}px`};v(),window.addEventListener("resize",v),_e.push(()=>window.removeEventListener("resize",v)),Ze=K.scrollTop;let je=()=>{let i=K.scrollTop,l=K.scrollHeight,C=K.clientHeight,N=l-i-C,W=Math.abs(i-Ze);if(Ze=i,!Ke&&!(W<=Ft)){if(!Te&&N<Nt){ut=!1,Te=!0;return}Te&&N>Nt&&(ut=!0,U=Date.now()+bt,Te=!1)}};K.addEventListener("scroll",je,{passive:!0}),_e.push(()=>K.removeEventListener("scroll",je)),_e.push(()=>{ie&&cancelAnimationFrame(ie)});let $=()=>{L&&(st&&(L.removeEventListener("click",st),st=null),y?(L.style.display="",st=()=>{M=!1,ht()},L.addEventListener("click",st)):L.style.display="none")};$(),(()=>{let{clearChatButton:i}=Se;i&&i.addEventListener("click",()=>{R.clearMessages();try{localStorage.removeItem(Xt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xt}`)}catch(C){console.error("[AgentWidget] Failed to clear default localStorage:",C)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Xt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(C){console.error("[AgentWidget] Failed to clear custom localStorage:",C)}let l=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let C=a.clear();C instanceof Promise&&C.catch(N=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",N)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)}c={},B.syncFromMetadata()})})(),yt.addEventListener("submit",Et),J.addEventListener("keydown",Lt),_e.push(()=>{yt.removeEventListener("submit",Et),J.removeEventListener("keydown",Lt)}),_e.push(()=>{R.cancel()}),D&&_e.push(()=>{D==null||D.destroy()});let d={update(i){var Mn,Wn,En,Ln,kn,Bn,Rn,Hn,In,Pn,Fn,Nn,Dn,qn,zn,_n,On,$n,jn,Vn,Un,Kn,Xn,Yn,Jn,Gn,Zn,Qn,eo,to,no,oo,ro,so,io,ao,lo,co,uo,go,po,mo,fo,wo,ho,vo,yo,bo,xo,Co,So;let l=e.toolCall;e={...e,...i},un(t,e);let C=en.getForInstance(e.plugins);o.length=0,o.push(...C),y=(Wn=(Mn=e.launcher)==null?void 0:Mn.enabled)!=null?Wn:!0,G=(Ln=(En=e.launcher)==null?void 0:En.autoExpand)!=null?Ln:!1,ke=(Bn=(kn=e.features)==null?void 0:kn.showReasoning)!=null?Bn:!0,ne=(Hn=(Rn=e.features)==null?void 0:Rn.showToolCalls)!=null?Hn:!0,((In=e.launcher)==null?void 0:In.enabled)===!1&&D&&(D.destroy(),D=null),((Pn=e.launcher)==null?void 0:Pn.enabled)!==!1&&!D&&(D=gn(e,Le),t.appendChild(D.element)),D&&D.update(e),Pt&&((Fn=e.launcher)==null?void 0:Fn.title)!==void 0&&(Pt.textContent=e.launcher.title),he&&((Nn=e.launcher)==null?void 0:Nn.subtitle)!==void 0&&(he.textContent=e.launcher.subtitle),y!==x?y?Oe(G,"auto"):(M=!0,ht()):G!==I&&Oe(G,"auto"),I=G,x=y,v(),$(),JSON.stringify(i.toolCall)!==JSON.stringify(l)&&R&&wt(Q,R.getMessages(),m);let T=(Dn=e.launcher)!=null?Dn:{},V=(qn=T.headerIconHidden)!=null?qn:!1,ye=T.headerIconName,p=(zn=T.headerIconSize)!=null?zn:"48px";if(we){let A=fe.querySelector(".tvw-border-b-cw-divider"),We=A==null?void 0:A.querySelector(".tvw-flex-col");if(V)we.style.display="none",A&&We&&!A.contains(We)&&A.insertBefore(We,A.firstChild);else{if(we.style.display="",we.style.height=p,we.style.width=p,A&&We&&(A.contains(we)?we.nextSibling!==We&&(we.remove(),A.insertBefore(we,We)):A.insertBefore(we,We)),ye){let ze=parseFloat(p)||24,ge=Ee(ye,ze*.6,"#ffffff",2);ge?we.replaceChildren(ge):we.textContent=(_n=T.agentIconText)!=null?_n:"\u{1F4AC}"}else if(T.iconUrl){let ze=we.querySelector("img");if(ze)ze.src=T.iconUrl,ze.style.height=p,ze.style.width=p;else{let ge=document.createElement("img");ge.src=T.iconUrl,ge.alt="",ge.className="tvw-rounded-xl tvw-object-cover",ge.style.height=p,ge.style.width=p,we.replaceChildren(ge)}}else{let ze=we.querySelector("svg"),ge=we.querySelector("img");(ze||ge)&&we.replaceChildren(),we.textContent=(On=T.agentIconText)!=null?On:"\u{1F4AC}"}let Ie=we.querySelector("img");Ie&&(Ie.style.height=p,Ie.style.width=p)}}if(L){let A=($n=T.closeButtonSize)!=null?$n:"32px",We=(jn=T.closeButtonPlacement)!=null?jn:"inline";L.style.height=A,L.style.width=A;let Ie=We==="top-right",ze=L.classList.contains("tvw-absolute");if(Ie!==ze)if(L.remove(),Ie)L.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50 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",fe.style.position="relative",fe.appendChild(L);else{L.className="tvw-ml-auto 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";let te=fe.querySelector(".tvw-border-b-cw-divider");te&&te.appendChild(L)}if(T.closeButtonColor?(L.style.color=T.closeButtonColor,L.classList.remove("tvw-text-cw-muted")):(L.style.color="",L.classList.add("tvw-text-cw-muted")),T.closeButtonBackgroundColor?(L.style.backgroundColor=T.closeButtonBackgroundColor,L.classList.remove("hover:tvw-bg-gray-100")):(L.style.backgroundColor="",L.classList.add("hover:tvw-bg-gray-100")),T.closeButtonBorderWidth||T.closeButtonBorderColor){let te=T.closeButtonBorderWidth||"0px",vt=T.closeButtonBorderColor||"transparent";L.style.border=`${te} solid ${vt}`,L.classList.remove("tvw-border-none")}else L.style.border="",L.classList.add("tvw-border-none");T.closeButtonBorderRadius?(L.style.borderRadius=T.closeButtonBorderRadius,L.classList.remove("tvw-rounded-full")):(L.style.borderRadius="",L.classList.add("tvw-rounded-full")),T.closeButtonPaddingX?(L.style.paddingLeft=T.closeButtonPaddingX,L.style.paddingRight=T.closeButtonPaddingX):(L.style.paddingLeft="",L.style.paddingRight=""),T.closeButtonPaddingY?(L.style.paddingTop=T.closeButtonPaddingY,L.style.paddingBottom=T.closeButtonPaddingY):(L.style.paddingTop="",L.style.paddingBottom="");let ge=(Vn=T.closeButtonIconName)!=null?Vn:"x",St=(Un=T.closeButtonIconText)!=null?Un:"\xD7";L.innerHTML="";let Je=Ee(ge,"20px",T.closeButtonColor||"",2);Je?L.appendChild(Je):L.textContent=St;let{closeButtonWrapper:Ue}=Se,Ce=(Kn=T.closeButtonTooltipText)!=null?Kn:"Close chat",Ge=(Xn=T.closeButtonShowTooltip)!=null?Xn:!0;if(L.setAttribute("aria-label",Ce),Ue&&(Ue._cleanupTooltip&&(Ue._cleanupTooltip(),delete Ue._cleanupTooltip),Ge&&Ce)){let te=null,vt=()=>{if(te||!L)return;te=u("div","tvw-clear-chat-tooltip"),te.textContent=Ce;let To=u("div");To.className="tvw-clear-chat-tooltip-arrow",te.appendChild(To);let on=L.getBoundingClientRect();te.style.position="fixed",te.style.left=`${on.left+on.width/2}px`,te.style.top=`${on.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},tt=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};Ue.addEventListener("mouseenter",vt),Ue.addEventListener("mouseleave",tt),L.addEventListener("focus",vt),L.addEventListener("blur",tt),Ue._cleanupTooltip=()=>{tt(),Ue&&(Ue.removeEventListener("mouseenter",vt),Ue.removeEventListener("mouseleave",tt)),L&&(L.removeEventListener("focus",vt),L.removeEventListener("blur",tt))}}}let{clearChatButton:w,clearChatButtonWrapper:q}=Se;if(w){let A=(Yn=T.clearChat)!=null?Yn:{},We=(Jn=A.enabled)!=null?Jn:!0;if(q&&(q.style.display=We?"":"none"),We){let Ie=(Gn=A.size)!=null?Gn:"32px";w.style.height=Ie,w.style.width=Ie;let ze=(Zn=A.iconName)!=null?Zn:"refresh-cw",ge=(Qn=A.iconColor)!=null?Qn:"";w.innerHTML="";let St=Ee(ze,"20px",ge||"",2);if(St&&w.appendChild(St),ge?(w.style.color=ge,w.classList.remove("tvw-text-cw-muted")):(w.style.color="",w.classList.add("tvw-text-cw-muted")),A.backgroundColor?(w.style.backgroundColor=A.backgroundColor,w.classList.remove("hover:tvw-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:tvw-bg-gray-100")),A.borderWidth||A.borderColor){let Ce=A.borderWidth||"0px",Ge=A.borderColor||"transparent";w.style.border=`${Ce} solid ${Ge}`,w.classList.remove("tvw-border-none")}else w.style.border="",w.classList.add("tvw-border-none");A.borderRadius?(w.style.borderRadius=A.borderRadius,w.classList.remove("tvw-rounded-full")):(w.style.borderRadius="",w.classList.add("tvw-rounded-full")),A.paddingX?(w.style.paddingLeft=A.paddingX,w.style.paddingRight=A.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),A.paddingY?(w.style.paddingTop=A.paddingY,w.style.paddingBottom=A.paddingY):(w.style.paddingTop="",w.style.paddingBottom="");let Je=(eo=A.tooltipText)!=null?eo:"Clear chat",Ue=(to=A.showTooltip)!=null?to:!0;if(w.setAttribute("aria-label",Je),q&&(q._cleanupTooltip&&(q._cleanupTooltip(),delete q._cleanupTooltip),Ue&&Je)){let Ce=null,Ge=()=>{if(Ce||!w)return;Ce=u("div","tvw-clear-chat-tooltip"),Ce.textContent=Je;let vt=u("div");vt.className="tvw-clear-chat-tooltip-arrow",Ce.appendChild(vt);let tt=w.getBoundingClientRect();Ce.style.position="fixed",Ce.style.left=`${tt.left+tt.width/2}px`,Ce.style.top=`${tt.top-8}px`,Ce.style.transform="translate(-50%, -100%)",document.body.appendChild(Ce)},te=()=>{Ce&&Ce.parentNode&&(Ce.parentNode.removeChild(Ce),Ce=null)};q.addEventListener("mouseenter",Ge),q.addEventListener("mouseleave",te),w.addEventListener("focus",Ge),w.addEventListener("blur",te),q._cleanupTooltip=()=>{te(),q&&(q.removeEventListener("mouseenter",Ge),q.removeEventListener("mouseleave",te)),w&&(w.removeEventListener("focus",Ge),w.removeEventListener("blur",te))}}}}let be=e.actionParsers&&e.actionParsers.length?e.actionParsers:[tn],Y=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Kt.message,Kt.messageAndClick];B=nn({parsers:be,handlers:Y,getMetadata:z,updateMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),m=zo(e,B),R.updateConfig(e),wt(Q,R.getMessages(),m),dt.render(e.suggestionChips,R,J,void 0,e.suggestionChipsConfig),Wt(),Ct(R.isStreaming());let qe=((no=e.voiceRecognition)==null?void 0:no.enabled)===!0,Pe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Xe=qe&&Pe;if(yt.classList.remove("tvw-gap-1","tvw-gap-3"),yt.classList.add(Xe?"tvw-gap-1":"tvw-gap-3"),qe&&Pe)if(!S||!Ne){let A=X(e.voiceRecognition,e.sendButton);A&&(S=A.micButton,Ne=A.micButtonWrapper,yt.insertBefore(Ne,ot),S.addEventListener("click",ce),S.disabled=R.isStreaming())}else{let A=(oo=e.voiceRecognition)!=null?oo:{},We=(ro=e.sendButton)!=null?ro:{},Ie=(so=A.iconName)!=null?so:"mic",ze=(io=We.size)!=null?io:"40px",ge=(ao=A.iconSize)!=null?ao:ze,St=parseFloat(ge)||24;S.style.width=ge,S.style.height=ge,S.style.minWidth=ge,S.style.minHeight=ge;let Je=(co=(lo=A.iconColor)!=null?lo:We.textColor)!=null?co:"currentColor";S.innerHTML="";let Ue=Ee(Ie,St,Je,2);Ue?S.appendChild(Ue):S.textContent="\u{1F3A4}";let Ce=(uo=A.backgroundColor)!=null?uo:We.backgroundColor;Ce?(S.style.backgroundColor=Ce,S.classList.remove("tvw-bg-cw-primary")):(S.style.backgroundColor="",S.classList.add("tvw-bg-cw-primary")),Je?(S.style.color=Je,S.classList.remove("tvw-text-white")):!Je&&!We.textColor&&(S.style.color="",S.classList.add("tvw-text-white")),A.borderWidth?(S.style.borderWidth=A.borderWidth,S.style.borderStyle="solid"):(S.style.borderWidth="",S.style.borderStyle=""),A.borderColor?S.style.borderColor=A.borderColor:S.style.borderColor="",A.paddingX?(S.style.paddingLeft=A.paddingX,S.style.paddingRight=A.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),A.paddingY?(S.style.paddingTop=A.paddingY,S.style.paddingBottom=A.paddingY):(S.style.paddingTop="",S.style.paddingBottom="");let Ge=Ne==null?void 0:Ne.querySelector(".tvw-send-button-tooltip"),te=(go=A.tooltipText)!=null?go:"Start voice recognition";if(((po=A.showTooltip)!=null?po:!1)&&te)if(Ge)Ge.textContent=te,Ge.style.display="";else{let tt=document.createElement("div");tt.className="tvw-send-button-tooltip",tt.textContent=te,Ne==null||Ne.insertBefore(tt,S)}else Ge&&(Ge.style.display="none");Ne.style.display="",S.disabled=R.isStreaming()}else S&&Ne&&(Ne.style.display="none",$e&&_());let ee=(mo=e.sendButton)!=null?mo:{},et=(fo=ee.useIcon)!=null?fo:!1,$t=(wo=ee.iconText)!=null?wo:"\u2191",Bt=ee.iconName,xe=(ho=ee.tooltipText)!=null?ho:"Send message",pt=(vo=ee.showTooltip)!=null?vo:!1,mt=(yo=ee.size)!=null?yo:"40px",jt=ee.backgroundColor,Ye=ee.textColor;if(et){if(E.style.width=mt,E.style.height=mt,E.style.minWidth=mt,E.style.minHeight=mt,E.style.fontSize="18px",E.style.lineHeight="1",E.innerHTML="",Bt){let A=parseFloat(mt)||24,We=Ye&&typeof Ye=="string"&&Ye.trim()?Ye.trim():"currentColor",Ie=Ee(Bt,A,We,2);Ie?(E.appendChild(Ie),E.style.color=We):(E.textContent=$t,Ye?E.style.color=Ye:E.classList.add("tvw-text-white"))}else E.textContent=$t,Ye?E.style.color=Ye:E.classList.add("tvw-text-white");E.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",jt?(E.style.backgroundColor=jt,E.classList.remove("tvw-bg-cw-primary")):E.classList.add("tvw-bg-cw-primary")}else E.textContent=(xo=(bo=e.copy)==null?void 0:bo.sendButtonLabel)!=null?xo:"Send",E.style.width="",E.style.height="",E.style.minWidth="",E.style.minHeight="",E.style.fontSize="",E.style.lineHeight="",E.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",jt?(E.style.backgroundColor=jt,E.classList.remove("tvw-bg-cw-accent")):E.classList.add("tvw-bg-cw-accent"),Ye?E.style.color=Ye:E.classList.add("tvw-text-white");ee.borderWidth?(E.style.borderWidth=ee.borderWidth,E.style.borderStyle="solid"):(E.style.borderWidth="",E.style.borderStyle=""),ee.borderColor?E.style.borderColor=ee.borderColor:E.style.borderColor="",ee.paddingX?(E.style.paddingLeft=ee.paddingX,E.style.paddingRight=ee.paddingX):(E.style.paddingLeft="",E.style.paddingRight=""),ee.paddingY?(E.style.paddingTop=ee.paddingY,E.style.paddingBottom=ee.paddingY):(E.style.paddingTop="",E.style.paddingBottom="");let Jt=ot==null?void 0:ot.querySelector(".tvw-send-button-tooltip");if(pt&&xe)if(Jt)Jt.textContent=xe,Jt.style.display="";else{let A=document.createElement("div");A.className="tvw-send-button-tooltip",A.textContent=xe,ot==null||ot.insertBefore(A,E)}else Jt&&(Jt.style.display="none");let Gt=(Co=e.statusIndicator)!=null?Co:{},$o=(So=Gt.visible)!=null?So:!0;if(It.style.display=$o?"":"none",R){let A=R.getStatus(),We=Ie=>{var ze,ge,St,Je;return Ie==="idle"?(ze=Gt.idleText)!=null?ze:Ve.idle:Ie==="connecting"?(ge=Gt.connectingText)!=null?ge:Ve.connecting:Ie==="connected"?(St=Gt.connectedText)!=null?St:Ve.connected:Ie==="error"?(Je=Gt.errorText)!=null?Je:Ve.error:Ve[Ie]};It.textContent=We(A)}},open(){y&&Oe(!0,"api")},close(){y&&Oe(!1,"api")},toggle(){y&&Oe(!M,"api")},clearChat(){R.clearMessages();try{localStorage.removeItem(Xt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xt}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Xt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let i=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(i),a!=null&&a.clear)try{let l=a.clear();l instanceof Promise&&l.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",l)}c={},B.syncFromMetadata()},setMessage(i){return!J||R.isStreaming()?!1:(!M&&y&&Oe(!0,"system"),J.value=i,J.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(R.isStreaming())return!1;let l=(i==null?void 0:i.trim())||J.value.trim();return l?(!M&&y&&Oe(!0,"system"),J.value="",R.sendMessage(l),!0):!1},startVoiceRecognition(){return $e||R.isStreaming()||!kt()?!1:(!M&&y&&Oe(!0,"system"),re.manuallyDeactivated=!1,it(),f("user"),!0)},stopVoiceRecognition(){return $e?(re.manuallyDeactivated=!0,it(),_("user"),!0):!1},injectTestMessage(i){!M&&y&&Oe(!0,"system"),R.injectTestEvent(i)},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(i){g(i)},on(i,l){return s.on(i,l)},off(i,l){s.off(i,l)},isOpen(){return y&&M},isVoiceActive(){return re.active},getState(){return{open:y&&M,launcherEnabled:y,voiceActive:re.active,streaming:R.isStreaming()}},destroy(){_e.forEach(i=>i()),me.remove(),D==null||D.destroy(),st&&L.removeEventListener("click",st)}};if((((Yt=r==null?void 0:r.debugTools)!=null?Yt:!1)||!!e.debug)&&typeof window!="undefined"){let i=window.AgentWidgetBrowser,l={controller:d,getMessages:d.getMessages,getStatus:d.getStatus,getMetadata:d.getPersistentMetadata,updateMetadata:d.updatePersistentMetadata,clearHistory:()=>d.clearChat(),setVoiceActive:C=>C?d.startVoiceRecognition():d.stopVoiceRecognition()};window.AgentWidgetBrowser=l,_e.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=i)})}return d};var An={},rr=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let n=document.querySelector(t);if(!n)throw new Error(`Chat widget target "${t}" was not found`);return n}return t},sr=()=>{try{if(typeof An!="undefined"&&An.url)return new URL("../widget.css",An.url).href}catch{}return null},_o=t=>{let n=sr(),r=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let o=e.cloneNode(!0);t.insertBefore(o,t.firstChild)};if(t instanceof ShadowRoot)if(n){let e=document.createElement("link");e.rel="stylesheet",e.href=n,e.setAttribute("data-vanilla-agent","true"),t.insertBefore(e,t.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},Oo=t=>{var b;let n=rr(t.target),r=document.createElement("div");r.className="vanilla-agent-host",n.appendChild(r);let e=t.useShadowDom!==!1,o,s;if(e){let z=r.attachShadow({mode:"open"});s=z,o=document.createElement("div"),o.id="vanilla-agent-root",z.appendChild(o),_o(z)}else s=r,o=document.createElement("div"),o.id="vanilla-agent-root",r.appendChild(o),_o(r);let a=Tn(o,t.config,{debugTools:t.debugTools});(b=t.onReady)==null||b.call(t);let c={...a,host:r,destroy(){a.destroy(),r.remove(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}};return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=c),c};var ir=t=>{if(!t)return null;try{return JSON.parse(t)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},ar=t=>t.map(n=>({...n,streaming:!1})),lr=(t="vanilla-agent-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?ir(r.getItem(t)):null},save:r=>{let e=n();if(e)try{let o={...r,messages:r.messages?ar(r.messages):void 0};e.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(t)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var vs=Oo;export{Ut as AgentWidgetClient,Zt as AgentWidgetSession,nt as DEFAULT_WIDGET_CONFIG,nn as createActionManager,Tn as createAgentExperience,Jo as createFlexibleJsonStreamParser,dn as createJsonStreamParser,lr as createLocalStorageAdapter,an as createPlainTextParser,ln as createRegexJsonParser,cn as createXmlParser,vs as default,Kt as defaultActionHandlers,tn as defaultJsonActionParser,Uo as directivePostprocessor,rn as escapeHtml,Oo as initAgentWidget,Wo as markdownPostprocessor,xn as mergeWithDefaults,en as pluginRegistry};
16
16
  //# sourceMappingURL=index.js.map