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