vanilla-agent 1.18.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import{marked as to}from"marked";to.setOptions({breaks:!0});var no=n=>to.parse(n),xn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ao=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),eo=n=>`%%FORM_PLACEHOLDER_${n}%%`,To=(n,e)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=eo(e.length);return e.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=eo(e.length);return e.push({token:s,type:o}),s}),r},Eo=n=>{let e=[],r=To(n,e),t=no(r);return e.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="tvw-form-directive" data-tv-form="${Ao(s)}"></div>`;t=t.replace(i,p)}),t};import{parse as so,STR as oo,OBJ as ro}from"partial-json";var un=n=>n.replace(/\\n/g,`
2
2
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Cn=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},Wo=n=>{var i,l;let e=(i=n.completedAt)!=null?i:Date.now(),r=(l=n.startedAt)!=null?l:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},io=n=>n.status==="complete"?Wo(n):n.status==="pending"?"Waiting":"",Mo=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var ao=n=>n.status==="complete"?Mo(n):"Using tool...",Lo=()=>{let n=null,e=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=t.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},gn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Sn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},An=()=>{var e;let n=Lo();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Tn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=so(r,oo|ro);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?un(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=un(o.text)))}catch{}return e=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Bo=n=>{let e=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?un(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?un(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let l=so(s,oo|ro),p=o(l);p!==null&&(e=p)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},En=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Ho="https://api.travrse.ai/v1/dispatch";function ko(n){switch(n){case"json":return Tn;case"regex-json":return An;case"xml":return En;case"plain":default:return Sn}}var Kt=class{constructor(e={}){this.config=e;var r,t,o;this.apiUrl=(r=e.apiUrl)!=null?r:Ho,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:ko(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}async dispatch(e,r){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(l){let p=l instanceof Error?l:new Error(String(l));throw r({type:"error",error:p}),p}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:l}),l}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(o=>({role:o.role,content:o.rawContent||o.content,createdAt:o.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(e,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let 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(i.text!==void 0){let p=l();p.content+=i.text,o(p)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r){var se,P,_e,Ye,Qe,xt,Ct,D,he,mt,ft,Je,et,M,Me,it,at,Et,wt,ke,tt,qe,F,lt,Ke,We,je,K,Se,Le,Ue,nt,St,Lt,gt,At,de,Nt,Bt,be,yt,Tt,Ht,vt,Wt,ln,dn,cn,vn,Dt,Ft,st,zt,Gt,Zt,Qt;let t=e.getReader(),o=new TextDecoder,s="",i=Date.now(),l=0,p=()=>i+l++,h=y=>{let X=y.reasoning?{...y.reasoning,chunks:[...y.reasoning.chunks]}:void 0,ne=y.toolCall?{...y.toolCall,chunks:y.toolCall.chunks?[...y.toolCall.chunks]:void 0}:void 0,fe=y.tools?y.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...y,reasoning:X,toolCall:ne,tools:fe}},d=y=>{r({type:"message",message:h(y)})},T=null,f={current:null},b=new Map,w=new Map,q={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},m=y=>{if(y==null)return null;try{return String(y)}catch{return null}},C=y=>{var X,ne,fe,Re,Ie;return m((Ie=(Re=(fe=(ne=(X=y.stepId)!=null?X:y.step_id)!=null?ne:y.step)!=null?fe:y.parentId)!=null?Re:y.flowStepId)!=null?Ie:y.flow_step_id)},$=y=>{var X,ne,fe,Re,Ie,ce,L;return m((L=(ce=(Ie=(Re=(fe=(ne=(X=y.callId)!=null?X:y.call_id)!=null?ne:y.requestId)!=null?fe:y.request_id)!=null?Re:y.toolCallId)!=null?Ie:y.tool_call_id)!=null?ce:y.stepId)!=null?L:y.step_id)},A=()=>T||(T={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p()},d(T),T),Y=(y,X)=>{q.lastId=X,y&&q.byStep.set(y,X)},I=(y,X)=>{var Ie;let ne=(Ie=y.reasoningId)!=null?Ie:y.id,fe=C(y);if(ne){let ce=String(ne);return Y(fe,ce),ce}if(fe){let ce=q.byStep.get(fe);if(ce)return q.lastId=ce,ce}if(q.lastId&&!X)return q.lastId;if(!X)return null;let Re=`reason-${p()}`;return Y(fe,Re),Re},V=y=>{let X=b.get(y);if(X)return X;let ne={id:`reason-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:y,status:"streaming",chunks:[]}};return b.set(y,ne),d(ne),ne},G=(y,X)=>{j.lastId=X,y&&j.byCall.set(y,X)},S=(y,X)=>{var Ie;let ne=(Ie=y.toolId)!=null?Ie:y.id,fe=$(y);if(ne){let ce=String(ne);return G(fe,ce),ce}if(fe){let ce=j.byCall.get(fe);if(ce)return j.lastId=ce,ce}if(j.lastId&&!X)return j.lastId;if(!X)return null;let Re=`tool-${p()}`;return G(fe,Re),Re},ie=y=>{let X=w.get(y);if(X)return X;let ne={id:`tool-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:y,status:"pending"}};return w.set(y,ne),d(ne),ne},J=y=>{if(typeof y=="number"&&Number.isFinite(y))return y;if(typeof y=="string"){let X=Number(y);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let ne=Date.parse(y);if(!Number.isNaN(ne))return ne}return Date.now()},U=y=>{if(typeof y=="string")return y;if(y==null)return"";try{return JSON.stringify(y)}catch{return String(y)}},Z=new Map,le=new Map;for(;;){let{done:y,value:X}=await t.read();if(y)break;s+=o.decode(X,{stream:!0});let ne=s.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},gn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Sn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},An=()=>{var e;let n=Lo();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Tn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=so(r,oo|ro);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?un(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=un(o.text)))}catch{}return e=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Bo=n=>{let e=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?un(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?un(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let l=so(s,oo|ro),p=o(l);p!==null&&(e=p)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},En=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Ho="https://api.travrse.ai/v1/dispatch";function ko(n){switch(n){case"json":return Tn;case"regex-json":return An;case"xml":return En;case"plain":default:return Sn}}var Kt=class{constructor(e={}){this.config=e;var r,t,o;this.apiUrl=(r=e.apiUrl)!=null?r:Ho,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:ko(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}async dispatch(e,r){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(l){let p=l instanceof Error?l:new Error(String(l));throw r({type:"error",error:p}),p}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:l}),l}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(o=>({role:o.role,content:o.rawContent||o.content,createdAt:o.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(e,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let 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(i.text!==void 0){let p=l();p.content+=i.text,o(p)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r){var oe,P,_e,Ye,Qe,xt,Ct,j,me,mt,ft,Je,et,M,Le,it,at,Et,wt,Ie,tt,qe,_,lt,Ke,We,je,J,Se,Be,Ue,nt,St,Lt,gt,At,de,Nt,Bt,be,yt,Tt,Ht,vt,Wt,ln,dn,cn,vn,Ft,Dt,st,zt,Gt,Zt,Qt;let t=e.getReader(),o=new TextDecoder,s="",i=Date.now(),l=0,p=()=>i+l++,m=y=>{let K=y.reasoning?{...y.reasoning,chunks:[...y.reasoning.chunks]}:void 0,ne=y.toolCall?{...y.toolCall,chunks:y.toolCall.chunks?[...y.toolCall.chunks]:void 0}:void 0,we=y.tools?y.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{...y,reasoning:K,toolCall:ne,tools:we}},d=y=>{r({type:"message",message:m(y)})},T=null,f={current:null},b=new Map,w=new Map,D={lastId:null,byStep:new Map},N={lastId:null,byCall:new Map},h=y=>{if(y==null)return null;try{return String(y)}catch{return null}},C=y=>{var K,ne,we,$e,Pe;return h((Pe=($e=(we=(ne=(K=y.stepId)!=null?K:y.step_id)!=null?ne:y.step)!=null?we:y.parentId)!=null?$e:y.flowStepId)!=null?Pe:y.flow_step_id)},$=y=>{var K,ne,we,$e,Pe,ce,L;return h((L=(ce=(Pe=($e=(we=(ne=(K=y.callId)!=null?K:y.call_id)!=null?ne:y.requestId)!=null?we:y.request_id)!=null?$e:y.toolCallId)!=null?Pe:y.tool_call_id)!=null?ce:y.stepId)!=null?L:y.step_id)},A=()=>T||(T={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p()},d(T),T),z=(y,K)=>{D.lastId=K,y&&D.byStep.set(y,K)},I=(y,K)=>{var Pe;let ne=(Pe=y.reasoningId)!=null?Pe:y.id,we=C(y);if(ne){let ce=String(ne);return z(we,ce),ce}if(we){let ce=D.byStep.get(we);if(ce)return D.lastId=ce,ce}if(D.lastId&&!K)return D.lastId;if(!K)return null;let $e=`reason-${p()}`;return z(we,$e),$e},V=y=>{let K=b.get(y);if(K)return K;let ne={id:`reason-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:y,status:"streaming",chunks:[]}};return b.set(y,ne),d(ne),ne},G=(y,K)=>{N.lastId=K,y&&N.byCall.set(y,K)},S=(y,K)=>{var Pe;let ne=(Pe=y.toolId)!=null?Pe:y.id,we=$(y);if(ne){let ce=String(ne);return G(we,ce),ce}if(we){let ce=N.byCall.get(we);if(ce)return N.lastId=ce,ce}if(N.lastId&&!K)return N.lastId;if(!K)return null;let $e=`tool-${p()}`;return G(we,$e),$e},ie=y=>{let K=w.get(y);if(K)return K;let ne={id:`tool-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:y,status:"pending"}};return w.set(y,ne),d(ne),ne},Y=y=>{if(typeof y=="number"&&Number.isFinite(y))return y;if(typeof y=="string"){let K=Number(y);if(!Number.isNaN(K)&&Number.isFinite(K))return K;let ne=Date.parse(y);if(!Number.isNaN(ne))return ne}return Date.now()},U=y=>{if(typeof y=="string")return y;if(y==null)return"";try{return JSON.stringify(y)}catch{return String(y)}},Z=new Map,le=new Map;for(;;){let{done:y,value:K}=await t.read();if(y)break;s+=o.decode(K,{stream:!0});let ne=s.split(`
5
5
 
6
- `);s=(se=ne.pop())!=null?se:"";for(let fe of ne){let Re=fe.split(`
7
- `),Ie="message",ce="";for(let Q of Re)Q.startsWith("event:")?Ie=Q.replace("event:","").trim():Q.startsWith("data:")&&(ce+=Q.replace("data:","").trim());if(!ce)continue;let L;try{L=JSON.parse(ce)}catch(Q){r({type:"error",error:Q instanceof Error?Q:new Error("Failed to parse chat stream payload")});continue}let ot=Ie!=="message"?Ie:(P=L.type)!=null?P:"message";if(this.parseSSEEvent){f.current=T;let Q=await this.handleCustomSSEEvent(L,r,f,d,p);if(f.current&&!T&&(T=f.current),Q)continue}if(ot==="reason_start"){let Q=(_e=I(L,!0))!=null?_e:`reason-${p()}`,x=V(Q);x.reasoning=(Ye=x.reasoning)!=null?Ye:{id:Q,status:"streaming",chunks:[]},x.reasoning.startedAt=(xt=x.reasoning.startedAt)!=null?xt:J((Qe=L.startedAt)!=null?Qe:L.timestamp),x.reasoning.completedAt=void 0,x.reasoning.durationMs=void 0,x.streaming=!0,x.reasoning.status="streaming",d(x)}else if(ot==="reason_chunk"){let Q=(D=(Ct=I(L,!1))!=null?Ct:I(L,!0))!=null?D:`reason-${p()}`,x=V(Q);x.reasoning=(he=x.reasoning)!=null?he:{id:Q,status:"streaming",chunks:[]},x.reasoning.startedAt=(ft=x.reasoning.startedAt)!=null?ft:J((mt=L.startedAt)!=null?mt:L.timestamp);let g=(M=(et=(Je=L.reasoningText)!=null?Je:L.text)!=null?et:L.delta)!=null?M:"";if(g&&L.hidden!==!0&&x.reasoning.chunks.push(String(g)),x.reasoning.status=L.done?"complete":"streaming",L.done){x.reasoning.completedAt=J((Me=L.completedAt)!=null?Me:L.timestamp);let B=(it=x.reasoning.startedAt)!=null?it:Date.now();x.reasoning.durationMs=Math.max(0,((at=x.reasoning.completedAt)!=null?at:Date.now())-B)}x.streaming=x.reasoning.status!=="complete",d(x)}else if(ot==="reason_complete"){let Q=(wt=(Et=I(L,!1))!=null?Et:I(L,!0))!=null?wt:`reason-${p()}`,x=b.get(Q);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=J((ke=L.completedAt)!=null?ke:L.timestamp);let B=(tt=x.reasoning.startedAt)!=null?tt:Date.now();x.reasoning.durationMs=Math.max(0,((qe=x.reasoning.completedAt)!=null?qe:Date.now())-B),x.streaming=!1,d(x)}let g=C(L);g&&q.byStep.delete(g)}else if(ot==="tool_start"){let Q=(F=S(L,!0))!=null?F:`tool-${p()}`,x=ie(Q),g=(lt=x.toolCall)!=null?lt:{id:Q,status:"pending"};g.name=(Ke=L.toolName)!=null?Ke:g.name,g.status="running",L.args!==void 0&&(g.args=L.args),g.startedAt=(je=g.startedAt)!=null?je:J((We=L.startedAt)!=null?We:L.timestamp),g.completedAt=void 0,g.durationMs=void 0,x.toolCall=g,x.streaming=!0,d(x)}else if(ot==="tool_chunk"){let Q=(Se=(K=S(L,!1))!=null?K:S(L,!0))!=null?Se:`tool-${p()}`,x=ie(Q),g=(Le=x.toolCall)!=null?Le:{id:Q,status:"running"};g.startedAt=(nt=g.startedAt)!=null?nt:J((Ue=L.startedAt)!=null?Ue:L.timestamp);let B=(gt=(Lt=(St=L.text)!=null?St:L.delta)!=null?Lt:L.message)!=null?gt:"";B&&(g.chunks=(At=g.chunks)!=null?At:[],g.chunks.push(String(B))),g.status="running",x.toolCall=g,x.streaming=!0,d(x)}else if(ot==="tool_complete"){let Q=(Nt=(de=S(L,!1))!=null?de:S(L,!0))!=null?Nt:`tool-${p()}`,x=ie(Q),g=(Bt=x.toolCall)!=null?Bt:{id:Q,status:"running"};if(g.status="complete",L.result!==void 0&&(g.result=L.result),typeof L.duration=="number"&&(g.duration=L.duration),g.completedAt=J((be=L.completedAt)!=null?be:L.timestamp),typeof L.duration=="number")g.durationMs=L.duration;else{let we=(yt=g.startedAt)!=null?yt:Date.now();g.durationMs=Math.max(0,((Tt=g.completedAt)!=null?Tt:Date.now())-we)}x.toolCall=g,x.streaming=!1,d(x);let B=$(L);B&&j.byCall.delete(B)}else if(ot==="step_chunk"){let Q=L.stepType,x=L.executionType;if(Q==="tool"||x==="context")continue;let g=A(),B=(ln=(Wt=(vt=(Ht=L.text)!=null?Ht:L.delta)!=null?vt:L.content)!=null?Wt:L.chunk)!=null?ln:"";if(B){let Ae=((dn=le.get(g.id))!=null?dn:"")+B;g.rawContent=Ae,Z.has(g.id)||Z.set(g.id,this.createStreamParser());let Xe=Z.get(g.id),Be=Ae.trim().startsWith("{")||Ae.trim().startsWith("[");if(Be&&le.set(g.id,Ae),Xe.__isPlainTextParser===!0){g.content+=B,le.delete(g.id),Z.delete(g.id),g.rawContent=void 0,d(g);continue}let De=Xe.processChunk(Ae);if(De instanceof Promise)De.then(ae=>{var He;let pe=typeof ae=="string"?ae:(He=ae==null?void 0:ae.text)!=null?He:null;if(pe!==null&&pe.trim()!==""){let ue=T;ue&&ue.id===g.id&&(ue.content=pe,d(ue))}else if(!Be&&!Ae.trim().startsWith("<")){let ue=T;ue&&ue.id===g.id&&(ue.content+=B,le.delete(ue.id),Z.delete(ue.id),ue.rawContent=void 0,d(ue))}}).catch(()=>{g.content+=B,le.delete(g.id),Z.delete(g.id),g.rawContent=void 0,d(g)});else{let ae=typeof De=="string"?De:(cn=De==null?void 0:De.text)!=null?cn:null;ae!==null&&ae.trim()!==""?(g.content=ae,d(g)):!Be&&!Ae.trim().startsWith("<")&&(g.content+=B,le.delete(g.id),Z.delete(g.id),g.rawContent=void 0,d(g))}}if(L.isComplete){let we=(Dt=(vn=L.result)==null?void 0:vn.response)!=null?Dt:g.content;if(we){let Ae=le.get(g.id),Xe=Ae!=null?Ae:U(we);g.rawContent=Xe;let Be=Z.get(g.id),xe=null,De=!1;if(Be&&(xe=Be.getExtractedText(),xe===null&&(xe=gn(Xe)),xe===null)){let ae=Be.processChunk(Xe);ae instanceof Promise?(De=!0,ae.then(pe=>{var ue;let He=typeof pe=="string"?pe:(ue=pe==null?void 0:pe.text)!=null?ue:null;if(He!==null){let Pe=T;Pe&&Pe.id===g.id&&(Pe.content=He,Pe.streaming=!1,Z.delete(Pe.id),le.delete(Pe.id),d(Pe))}})):xe=typeof ae=="string"?ae:(Ft=ae==null?void 0:ae.text)!=null?Ft:null}if(!De){xe!==null&&xe.trim()!==""?g.content=xe:le.has(g.id)||(g.content=U(we));let ae=Z.get(g.id);if(ae){let pe=(st=ae.close)==null?void 0:st.call(ae);pe instanceof Promise&&pe.catch(()=>{}),Z.delete(g.id)}le.delete(g.id),g.streaming=!1,d(g)}}}}else if(ot==="step_complete"){let Q=L.stepType,x=L.executionType;if(Q==="tool"||x==="context")continue;let g=(zt=L.result)==null?void 0:zt.response,B=A();if(g!=null){let we=Z.get(B.id),Ae=!1,Xe=!1;if(we){let Be=we.getExtractedText(),xe=le.get(B.id),De=xe!=null?xe:U(g);if(B.rawContent=De,Be!==null&&Be.trim()!=="")B.content=Be,Ae=!0;else{let ae=gn(De);if(ae!==null)B.content=ae,Ae=!0;else{let pe=we.processChunk(De);if(pe instanceof Promise)Xe=!0,pe.then(He=>{var Pe;let ue=typeof He=="string"?He:(Pe=He==null?void 0:He.text)!=null?Pe:null;if(ue!==null&&ue.trim()!==""){let rt=T;rt&&rt.id===B.id&&(rt.content=ue,rt.streaming=!1,Z.delete(rt.id),le.delete(rt.id),d(rt))}else{let rt=we.getExtractedText(),ht=T;ht&&ht.id===B.id&&(rt!==null&&rt.trim()!==""?ht.content=rt:le.has(ht.id)||(ht.content=U(g)),ht.streaming=!1,Z.delete(ht.id),le.delete(ht.id),d(ht))}});else{let He=typeof pe=="string"?pe:(Gt=pe==null?void 0:pe.text)!=null?Gt:null;if(He!==null&&He.trim()!=="")B.content=He,Ae=!0;else{let ue=we.getExtractedText();ue!==null&&ue.trim()!==""&&(B.content=ue,Ae=!0)}}}}}if(!Xe){if(!B.rawContent){let Be=le.get(B.id);B.rawContent=Be!=null?Be:U(g)}if(!Ae&&!le.has(B.id)&&(B.content=U(g)),we){let Be=(Zt=we.close)==null?void 0:Zt.call(we);Be instanceof Promise&&Be.catch(()=>{})}Z.delete(B.id),le.delete(B.id),B.streaming=!1,d(B)}}else Z.delete(B.id),le.delete(B.id),B.streaming=!1,d(B)}else if(ot==="flow_complete"){let Q=(Qt=L.result)==null?void 0:Qt.response;if(Q!=null){let x=A(),g=le.get(x.id),B=g!=null?g:U(Q);x.rawContent=B;let we=U(Q),Ae=Z.get(x.id);if(Ae){let xe=gn(B);if(xe!==null)we=xe;else{let De=Ae.processChunk(B);De instanceof Promise&&De.then(pe=>{var ue;let He=typeof pe=="string"?pe:(ue=pe==null?void 0:pe.text)!=null?ue:null;if(He!==null){let Pe=T;Pe&&Pe.id===x.id&&(Pe.content=He,Pe.streaming=!1,d(Pe))}});let ae=Ae.getExtractedText();ae!==null&&(we=ae)}}Z.delete(x.id),le.delete(x.id);let Xe=we!==x.content,Be=x.streaming!==!1;Xe&&(x.content=we),x.streaming=!1,(Xe||Be)&&d(x)}else if(T!==null){let x=T;Z.delete(x.id),le.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}r({type:"status",status:"idle"})}else ot==="error"&&L.error&&r({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};var tn=class{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=e=>{var r,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(r=this.callbacks).onError)==null||t.call(r,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Kt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(e){this.config={...this.config,...e},this.client=new Kt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,r){var l,p,h,d,T;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let o={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1};this.appendMessage(o),this.setStreaming(!0);let s=new AbortController;this.abortController=s;let i=[...this.messages];try{await this.client.dispatch({messages:i,signal:s.signal},this.handleEvent)}catch(f){let b={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f instanceof Error?(h=(p=this.callbacks).onError)==null||h.call(p,f):(T=(d=this.callbacks).onError)==null||T.call(d,new Error(String(f)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,t)=>{var p,h;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(p=r.sequence)!=null?p:0,l=(h=t.sequence)!=null?h:0;return i!==l?i-l:r.id.localeCompare(t.id)})}};var Wn=(n,e)=>{var t;let r=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let i=o.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(s))})};import*as Ro from"lucide";var ve=(n,e=24,r="currentColor",t=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ro[o];return s?Io(s,e,r,t):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function Io(n,e,r,t){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let p=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([h,d])=>{h!=="stroke"&&p.setAttribute(h,String(d))}),o.appendChild(p)}}}),o}var c=(n,e)=>{let r=document.createElement(n);return e&&(r.className=e),r};var ze={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var bt={"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 nn=(n,e)=>{let r=c("button");r.type="button",r.innerHTML=`
6
+ `);s=(oe=ne.pop())!=null?oe:"";for(let we of ne){let $e=we.split(`
7
+ `),Pe="message",ce="";for(let Q of $e)Q.startsWith("event:")?Pe=Q.replace("event:","").trim():Q.startsWith("data:")&&(ce+=Q.replace("data:","").trim());if(!ce)continue;let L;try{L=JSON.parse(ce)}catch(Q){r({type:"error",error:Q instanceof Error?Q:new Error("Failed to parse chat stream payload")});continue}let ot=Pe!=="message"?Pe:(P=L.type)!=null?P:"message";if(this.parseSSEEvent){f.current=T;let Q=await this.handleCustomSSEEvent(L,r,f,d,p);if(f.current&&!T&&(T=f.current),Q)continue}if(ot==="reason_start"){let Q=(_e=I(L,!0))!=null?_e:`reason-${p()}`,x=V(Q);x.reasoning=(Ye=x.reasoning)!=null?Ye:{id:Q,status:"streaming",chunks:[]},x.reasoning.startedAt=(xt=x.reasoning.startedAt)!=null?xt:Y((Qe=L.startedAt)!=null?Qe:L.timestamp),x.reasoning.completedAt=void 0,x.reasoning.durationMs=void 0,x.streaming=!0,x.reasoning.status="streaming",d(x)}else if(ot==="reason_chunk"){let Q=(j=(Ct=I(L,!1))!=null?Ct:I(L,!0))!=null?j:`reason-${p()}`,x=V(Q);x.reasoning=(me=x.reasoning)!=null?me:{id:Q,status:"streaming",chunks:[]},x.reasoning.startedAt=(ft=x.reasoning.startedAt)!=null?ft:Y((mt=L.startedAt)!=null?mt:L.timestamp);let g=(M=(et=(Je=L.reasoningText)!=null?Je:L.text)!=null?et:L.delta)!=null?M:"";if(g&&L.hidden!==!0&&x.reasoning.chunks.push(String(g)),x.reasoning.status=L.done?"complete":"streaming",L.done){x.reasoning.completedAt=Y((Le=L.completedAt)!=null?Le:L.timestamp);let H=(it=x.reasoning.startedAt)!=null?it:Date.now();x.reasoning.durationMs=Math.max(0,((at=x.reasoning.completedAt)!=null?at:Date.now())-H)}x.streaming=x.reasoning.status!=="complete",d(x)}else if(ot==="reason_complete"){let Q=(wt=(Et=I(L,!1))!=null?Et:I(L,!0))!=null?wt:`reason-${p()}`,x=b.get(Q);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=Y((Ie=L.completedAt)!=null?Ie:L.timestamp);let H=(tt=x.reasoning.startedAt)!=null?tt:Date.now();x.reasoning.durationMs=Math.max(0,((qe=x.reasoning.completedAt)!=null?qe:Date.now())-H),x.streaming=!1,d(x)}let g=C(L);g&&D.byStep.delete(g)}else if(ot==="tool_start"){let Q=(_=S(L,!0))!=null?_:`tool-${p()}`,x=ie(Q),g=(lt=x.toolCall)!=null?lt:{id:Q,status:"pending"};g.name=(Ke=L.toolName)!=null?Ke:g.name,g.status="running",L.args!==void 0&&(g.args=L.args),g.startedAt=(je=g.startedAt)!=null?je:Y((We=L.startedAt)!=null?We:L.timestamp),g.completedAt=void 0,g.durationMs=void 0,x.toolCall=g,x.streaming=!0,d(x)}else if(ot==="tool_chunk"){let Q=(Se=(J=S(L,!1))!=null?J:S(L,!0))!=null?Se:`tool-${p()}`,x=ie(Q),g=(Be=x.toolCall)!=null?Be:{id:Q,status:"running"};g.startedAt=(nt=g.startedAt)!=null?nt:Y((Ue=L.startedAt)!=null?Ue:L.timestamp);let H=(gt=(Lt=(St=L.text)!=null?St:L.delta)!=null?Lt:L.message)!=null?gt:"";H&&(g.chunks=(At=g.chunks)!=null?At:[],g.chunks.push(String(H))),g.status="running",x.toolCall=g,x.streaming=!0,d(x)}else if(ot==="tool_complete"){let Q=(Nt=(de=S(L,!1))!=null?de:S(L,!0))!=null?Nt:`tool-${p()}`,x=ie(Q),g=(Bt=x.toolCall)!=null?Bt:{id:Q,status:"running"};if(g.status="complete",L.result!==void 0&&(g.result=L.result),typeof L.duration=="number"&&(g.duration=L.duration),g.completedAt=Y((be=L.completedAt)!=null?be:L.timestamp),typeof L.duration=="number")g.durationMs=L.duration;else{let ye=(yt=g.startedAt)!=null?yt:Date.now();g.durationMs=Math.max(0,((Tt=g.completedAt)!=null?Tt:Date.now())-ye)}x.toolCall=g,x.streaming=!1,d(x);let H=$(L);H&&N.byCall.delete(H)}else if(ot==="step_chunk"){let Q=L.stepType,x=L.executionType;if(Q==="tool"||x==="context")continue;let g=A(),H=(ln=(Wt=(vt=(Ht=L.text)!=null?Ht:L.delta)!=null?vt:L.content)!=null?Wt:L.chunk)!=null?ln:"";if(H){let Ae=((dn=le.get(g.id))!=null?dn:"")+H;g.rawContent=Ae,Z.has(g.id)||Z.set(g.id,this.createStreamParser());let Xe=Z.get(g.id),He=Ae.trim().startsWith("{")||Ae.trim().startsWith("[");if(He&&le.set(g.id,Ae),Xe.__isPlainTextParser===!0){g.content+=H,le.delete(g.id),Z.delete(g.id),g.rawContent=void 0,d(g);continue}let Fe=Xe.processChunk(Ae);if(Fe instanceof Promise)Fe.then(ae=>{var ke;let pe=typeof ae=="string"?ae:(ke=ae==null?void 0:ae.text)!=null?ke:null;if(pe!==null&&pe.trim()!==""){let ue=T;ue&&ue.id===g.id&&(ue.content=pe,d(ue))}else if(!He&&!Ae.trim().startsWith("<")){let ue=T;ue&&ue.id===g.id&&(ue.content+=H,le.delete(ue.id),Z.delete(ue.id),ue.rawContent=void 0,d(ue))}}).catch(()=>{g.content+=H,le.delete(g.id),Z.delete(g.id),g.rawContent=void 0,d(g)});else{let ae=typeof Fe=="string"?Fe:(cn=Fe==null?void 0:Fe.text)!=null?cn:null;ae!==null&&ae.trim()!==""?(g.content=ae,d(g)):!He&&!Ae.trim().startsWith("<")&&(g.content+=H,le.delete(g.id),Z.delete(g.id),g.rawContent=void 0,d(g))}}if(L.isComplete){let ye=(Ft=(vn=L.result)==null?void 0:vn.response)!=null?Ft:g.content;if(ye){let Ae=le.get(g.id),Xe=Ae!=null?Ae:U(ye);g.rawContent=Xe;let He=Z.get(g.id),xe=null,Fe=!1;if(He&&(xe=He.getExtractedText(),xe===null&&(xe=gn(Xe)),xe===null)){let ae=He.processChunk(Xe);ae instanceof Promise?(Fe=!0,ae.then(pe=>{var ue;let ke=typeof pe=="string"?pe:(ue=pe==null?void 0:pe.text)!=null?ue:null;if(ke!==null){let Oe=T;Oe&&Oe.id===g.id&&(Oe.content=ke,Oe.streaming=!1,Z.delete(Oe.id),le.delete(Oe.id),d(Oe))}})):xe=typeof ae=="string"?ae:(Dt=ae==null?void 0:ae.text)!=null?Dt:null}if(!Fe){xe!==null&&xe.trim()!==""?g.content=xe:le.has(g.id)||(g.content=U(ye));let ae=Z.get(g.id);if(ae){let pe=(st=ae.close)==null?void 0:st.call(ae);pe instanceof Promise&&pe.catch(()=>{}),Z.delete(g.id)}le.delete(g.id),g.streaming=!1,d(g)}}}}else if(ot==="step_complete"){let Q=L.stepType,x=L.executionType;if(Q==="tool"||x==="context")continue;let g=(zt=L.result)==null?void 0:zt.response,H=A();if(g!=null){let ye=Z.get(H.id),Ae=!1,Xe=!1;if(ye){let He=ye.getExtractedText(),xe=le.get(H.id),Fe=xe!=null?xe:U(g);if(H.rawContent=Fe,He!==null&&He.trim()!=="")H.content=He,Ae=!0;else{let ae=gn(Fe);if(ae!==null)H.content=ae,Ae=!0;else{let pe=ye.processChunk(Fe);if(pe instanceof Promise)Xe=!0,pe.then(ke=>{var Oe;let ue=typeof ke=="string"?ke:(Oe=ke==null?void 0:ke.text)!=null?Oe:null;if(ue!==null&&ue.trim()!==""){let rt=T;rt&&rt.id===H.id&&(rt.content=ue,rt.streaming=!1,Z.delete(rt.id),le.delete(rt.id),d(rt))}else{let rt=ye.getExtractedText(),ht=T;ht&&ht.id===H.id&&(rt!==null&&rt.trim()!==""?ht.content=rt:le.has(ht.id)||(ht.content=U(g)),ht.streaming=!1,Z.delete(ht.id),le.delete(ht.id),d(ht))}});else{let ke=typeof pe=="string"?pe:(Gt=pe==null?void 0:pe.text)!=null?Gt:null;if(ke!==null&&ke.trim()!=="")H.content=ke,Ae=!0;else{let ue=ye.getExtractedText();ue!==null&&ue.trim()!==""&&(H.content=ue,Ae=!0)}}}}}if(!Xe){if(!H.rawContent){let He=le.get(H.id);H.rawContent=He!=null?He:U(g)}if(!Ae&&!le.has(H.id)&&(H.content=U(g)),ye){let He=(Zt=ye.close)==null?void 0:Zt.call(ye);He instanceof Promise&&He.catch(()=>{})}Z.delete(H.id),le.delete(H.id),H.streaming=!1,d(H)}}else Z.delete(H.id),le.delete(H.id),H.streaming=!1,d(H)}else if(ot==="flow_complete"){let Q=(Qt=L.result)==null?void 0:Qt.response;if(Q!=null){let x=A(),g=le.get(x.id),H=g!=null?g:U(Q);x.rawContent=H;let ye=U(Q),Ae=Z.get(x.id);if(Ae){let xe=gn(H);if(xe!==null)ye=xe;else{let Fe=Ae.processChunk(H);Fe instanceof Promise&&Fe.then(pe=>{var ue;let ke=typeof pe=="string"?pe:(ue=pe==null?void 0:pe.text)!=null?ue:null;if(ke!==null){let Oe=T;Oe&&Oe.id===x.id&&(Oe.content=ke,Oe.streaming=!1,d(Oe))}});let ae=Ae.getExtractedText();ae!==null&&(ye=ae)}}Z.delete(x.id),le.delete(x.id);let Xe=ye!==x.content,He=x.streaming!==!1;Xe&&(x.content=ye),x.streaming=!1,(Xe||He)&&d(x)}else if(T!==null){let x=T;Z.delete(x.id),le.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}r({type:"status",status:"idle"})}else ot==="error"&&L.error&&r({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};var tn=class{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=e=>{var r,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(r=this.callbacks).onError)==null||t.call(r,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Kt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(e){this.config={...this.config,...e},this.client=new Kt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,r){var l,p,m,d,T;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let o={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1};this.appendMessage(o),this.setStreaming(!0);let s=new AbortController;this.abortController=s;let i=[...this.messages];try{await this.client.dispatch({messages:i,signal:s.signal},this.handleEvent)}catch(f){let b={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,f):(T=(d=this.callbacks).onError)==null||T.call(d,new Error(String(f)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,t)=>{var p,m;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(p=r.sequence)!=null?p:0,l=(m=t.sequence)!=null?m:0;return i!==l?i-l:r.id.localeCompare(t.id)})}};var Wn=(n,e)=>{var t;let r=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let i=o.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(s))})};import*as Ro from"lucide";var ve=(n,e=24,r="currentColor",t=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ro[o];return s?Io(s,e,r,t):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function Io(n,e,r,t){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let p=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([m,d])=>{m!=="stroke"&&p.setAttribute(m,String(d))}),o.appendChild(p)}}}),o}var c=(n,e)=>{let r=document.createElement(n);return e&&(r.className=e),r};var ze={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var bt={"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 nn=(n,e)=>{let r=c("button");r.type="button",r.innerHTML=`
8
8
  <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
10
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -12,8 +12,8 @@ import{marked as to}from"marked";to.setOptions({breaks:!0});var no=n=>to.parse(n
12
12
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,r.addEventListener("click",e);let t=s=>{var q,j,m,C,$,A,Y,I,V,G;let i=(q=s.launcher)!=null?q:{},l=r.querySelector("[data-role='launcher-title']");l&&(l.textContent=(j=i.title)!=null?j:"Chat Assistant");let p=r.querySelector("[data-role='launcher-subtitle']");p&&(p.textContent=(m=i.subtitle)!=null?m:"Get answers fast");let h=r.querySelector(".tvw-flex-col");h&&(i.textHidden?h.style.display="none":h.style.display="");let d=r.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let S=(C=i.agentIconSize)!=null?C:"40px";if(d.style.height=S,d.style.width=S,d.innerHTML="",i.agentIconName){let ie=parseFloat(S)||24,J=ve(i.agentIconName,ie*.6,"#ffffff",2);J?(d.appendChild(J),d.style.display=""):(d.textContent=($=i.agentIconText)!=null?$:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(A=i.agentIconText)!=null?A:"\u{1F4AC}",d.style.display="")}let T=r.querySelector("[data-role='launcher-image']");if(T){let S=(Y=i.agentIconSize)!=null?Y:"40px";T.style.height=S,T.style.width=S,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(T.src=i.iconUrl,T.style.display="block"):T.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let S=(I=i.callToActionIconSize)!=null?I:"32px";f.style.height=S,f.style.width=S,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let ie=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,ie=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let J=parseFloat(S)||24,U=Math.max(J-ie,8),Z=ve(i.callToActionIconName,U,"currentColor",2);Z?f.appendChild(Z):f.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}else f.textContent=(G=i.callToActionIconText)!=null?G:"\u2197"}let b=i.position&&bt[i.position]?bt[i.position]:bt["bottom-right"],w="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${w} ${b}`},o=()=>{r.removeEventListener("click",e),r.remove()};return n&&t(n),{element:r,update:t,destroy:o}};var Ut=n=>{var ie,J,U,Z,le,se,P,_e,Ye,Qe,xt,Ct,D,he,mt,ft,Je,et,M,Me,it,at,Et,wt,ke,tt,qe,F,lt,Ke,We,je;let{config:e,showClose:r=!0}=n,t=c("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(ie=e==null?void 0:e.launcher)!=null?ie:{},s=(J=o.headerIconSize)!=null?J:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",l=(Z=o.closeButtonPlacement)!=null?Z:"inline",p=(le=o.headerIconHidden)!=null?le:!1,h=o.headerIconName,d=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(d.style.height=s,d.style.width=s,!p)if(h){let K=parseFloat(s)||24,Se=ve(h,K*.6,"#ffffff",2);Se?d.replaceChildren(Se):d.textContent=(P=(se=e==null?void 0:e.launcher)==null?void 0:se.agentIconText)!=null?P:"\u{1F4AC}"}else if((_e=e==null?void 0:e.launcher)!=null&&_e.iconUrl){let K=c("img");K.src=e.launcher.iconUrl,K.alt="",K.className="tvw-rounded-xl tvw-object-cover",K.style.height=s,K.style.width=s,d.replaceChildren(K)}else d.textContent=(Qe=(Ye=e==null?void 0:e.launcher)==null?void 0:Ye.agentIconText)!=null?Qe:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col"),f=c("span","tvw-text-base tvw-font-semibold");f.textContent=(Ct=(xt=e==null?void 0:e.launcher)==null?void 0:xt.title)!=null?Ct:"Chat Assistant";let b=c("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(he=(D=e==null?void 0:e.launcher)==null?void 0:D.subtitle)!=null?he:"Here to help you get answers fast",T.append(f,b),p?t.append(T):t.append(d,T);let w=(mt=o.clearChat)!=null?mt:{},q=(ft=w.enabled)!=null?ft:!0,j=(Je=w.placement)!=null?Je:"inline",m=null,C=null;if(q){let K=(et=w.size)!=null?et:"32px",Se=(M=w.iconName)!=null?M:"refresh-cw",Le=(Me=w.iconColor)!=null?Me:"",Ue=(it=w.backgroundColor)!=null?it:"",nt=(at=w.borderWidth)!=null?at:"",St=(Et=w.borderColor)!=null?Et:"",Lt=(wt=w.borderRadius)!=null?wt:"",gt=(ke=w.paddingX)!=null?ke:"",At=(tt=w.paddingY)!=null?tt:"",de=(qe=w.tooltipText)!=null?qe:"Clear chat",Nt=(F=w.showTooltip)!=null?F:!0;C=c("div",j==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),j==="top-right"&&(C.style.right="48px"),m=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),m.style.height=K,m.style.width=K,m.type="button",m.setAttribute("aria-label",de);let Bt=ve(Se,"20px",Le||"",2);if(Bt&&m.appendChild(Bt),Le&&(m.style.color=Le,m.classList.remove("tvw-text-cw-muted")),Ue&&(m.style.backgroundColor=Ue,m.classList.remove("hover:tvw-bg-gray-100")),nt||St){let be=nt||"0px",yt=St||"transparent";m.style.border=`${be} solid ${yt}`,m.classList.remove("tvw-border-none")}if(Lt&&(m.style.borderRadius=Lt,m.classList.remove("tvw-rounded-full")),gt?(m.style.paddingLeft=gt,m.style.paddingRight=gt):(m.style.paddingLeft="",m.style.paddingRight=""),At?(m.style.paddingTop=At,m.style.paddingBottom=At):(m.style.paddingTop="",m.style.paddingBottom=""),C.appendChild(m),Nt&&de&&m&&C){let be=null,yt=()=>{if(be||!m)return;be=c("div","tvw-clear-chat-tooltip"),be.textContent=de;let Ht=c("div");Ht.className="tvw-clear-chat-tooltip-arrow",be.appendChild(Ht);let vt=m.getBoundingClientRect();be.style.position="fixed",be.style.left=`${vt.left+vt.width/2}px`,be.style.top=`${vt.top-8}px`,be.style.transform="translate(-50%, -100%)",document.body.appendChild(be)},Tt=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};C.addEventListener("mouseenter",yt),C.addEventListener("mouseleave",Tt),m.addEventListener("focus",yt),m.addEventListener("blur",Tt),C._cleanupTooltip=()=>{Tt(),C&&(C.removeEventListener("mouseenter",yt),C.removeEventListener("mouseleave",Tt)),m&&(m.removeEventListener("focus",yt),m.removeEventListener("blur",Tt))}}j==="inline"&&t.appendChild(C)}let $=c("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":q&&j==="inline"?"":"tvw-ml-auto"),A=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");A.style.height=i,A.style.width=i,A.type="button";let Y=(lt=o.closeButtonTooltipText)!=null?lt:"Close chat",I=(Ke=o.closeButtonShowTooltip)!=null?Ke:!0;A.setAttribute("aria-label",Y),A.style.display=r?"":"none";let V=(We=o.closeButtonIconName)!=null?We:"x",G=(je=o.closeButtonIconText)!=null?je:"\xD7",S=ve(V,"20px",o.closeButtonColor||"",2);if(S?A.appendChild(S):A.textContent=G,o.closeButtonColor?(A.style.color=o.closeButtonColor,A.classList.remove("tvw-text-cw-muted")):(A.style.color="",A.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(A.style.backgroundColor=o.closeButtonBackgroundColor,A.classList.remove("hover:tvw-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let K=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";A.style.border=`${K} solid ${Se}`,A.classList.remove("tvw-border-none")}else A.style.border="",A.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(A.style.borderRadius=o.closeButtonBorderRadius,A.classList.remove("tvw-rounded-full")):(A.style.borderRadius="",A.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(A.style.paddingLeft=o.closeButtonPaddingX,A.style.paddingRight=o.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),o.closeButtonPaddingY?(A.style.paddingTop=o.closeButtonPaddingY,A.style.paddingBottom=o.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom=""),$.appendChild(A),I&&Y){let K=null,Se=()=>{if(K)return;K=c("div","tvw-clear-chat-tooltip"),K.textContent=Y;let Ue=c("div");Ue.className="tvw-clear-chat-tooltip-arrow",K.appendChild(Ue);let nt=A.getBoundingClientRect();K.style.position="fixed",K.style.left=`${nt.left+nt.width/2}px`,K.style.top=`${nt.top-8}px`,K.style.transform="translate(-50%, -100%)",document.body.appendChild(K)},Le=()=>{K&&K.parentNode&&(K.parentNode.removeChild(K),K=null)};$.addEventListener("mouseenter",Se),$.addEventListener("mouseleave",Le),A.addEventListener("focus",Se),A.addEventListener("blur",Le),$._cleanupTooltip=()=>{Le(),$.removeEventListener("mouseenter",Se),$.removeEventListener("mouseleave",Le),A.removeEventListener("focus",Se),A.removeEventListener("blur",Le)}}return l!=="top-right"&&t.appendChild($),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:b,closeButton:A,closeButtonWrapper:$,clearChatButton:m,clearChatButtonWrapper:C}},sn=(n,e,r)=>{var i,l,p,h;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(l=t.closeButtonPlacement)!=null?l:"inline",s=(h=(p=t.clearChat)==null?void 0:p.placement)!=null?h:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var lo=n=>Ut({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),co=n=>{var w,q,j,m;let{config:e,showClose:r=!0,onClose:t}=n,o=(w=e==null?void 0:e.launcher)!=null?w:{},s=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=c("span","tvw-text-base tvw-font-semibold");i.textContent=(q=o.title)!=null?q:"Chat Assistant",s.appendChild(i);let l=(j=o.closeButtonSize)!=null?j:"32px",p=c("div",""),h=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");h.style.height=l,h.style.width=l,h.type="button",h.setAttribute("aria-label","Close chat"),h.style.display=r?"":"none";let d=(m=o.closeButtonIconName)!=null?m:"x",T=ve(d,"20px",o.closeButtonColor||"",2);T?h.appendChild(T):h.textContent="\xD7",t&&h.addEventListener("click",t),p.appendChild(h),s.appendChild(p);let f=c("div");f.style.display="none";let b=c("span");return b.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:b,closeButton:h,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},po=n=>{var A,Y,I,V,G,S,ie,J;let{config:e,showClose:r=!0,onClose:t,onClearChat:o}=n,s=(A=e==null?void 0:e.launcher)!=null?A:{},i=c("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=c("div","tvw-flex tvw-items-center tvw-gap-3"),p=(Y=s.headerIconSize)!=null?Y:"56px",h=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");h.style.height=p,h.style.width=p;let d=s.headerIconName;if(d){let U=parseFloat(p)||24,Z=ve(d,U*.5,"#ffffff",2);Z?h.replaceChildren(Z):h.textContent=(I=s.agentIconText)!=null?I:"\u{1F4AC}"}else if(s.iconUrl){let U=c("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=p,U.style.width=p,h.replaceChildren(U)}else h.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col tvw-flex-1"),f=c("span","tvw-text-lg tvw-font-semibold");f.textContent=(G=s.title)!=null?G:"Chat Assistant";let b=c("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(S=s.subtitle)!=null?S:"Here to help you get answers fast",T.append(f,b),l.append(h,T);let w=(ie=s.closeButtonSize)!=null?ie:"32px",q=c("div",""),j=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");j.style.height=w,j.style.width=w,j.type="button",j.setAttribute("aria-label","Close chat"),j.style.display=r?"":"none";let m=(J=s.closeButtonIconName)!=null?J:"x",C=ve(m,"20px",s.closeButtonColor||"",2);C?j.appendChild(C):j.textContent="\xD7",t&&j.addEventListener("click",t),q.appendChild(j),l.appendChild(q),i.appendChild(l);let $=c("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return $.textContent="Online and ready to help",i.appendChild($),{header:i,iconHolder:h,headerTitle:f,headerSubtitle:b,closeButton:j,closeButtonWrapper:q,clearChatButton:null,clearChatButtonWrapper:null}},Mn={default:lo,minimal:co,expanded:po},uo=n=>{var e;return(e=Mn[n])!=null?e:Mn.default},Ln=(n,e,r)=>{var i,l,p;if(e!=null&&e.render){let h=e.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),d=c("div");d.style.display="none";let T=c("span"),f=c("span"),b=c("button");b.style.display="none";let w=c("div");return w.style.display="none",{header:h,iconHolder:d,headerTitle:T,headerSubtitle:f,closeButton:b,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=uo(t)({config:n,showClose:(p=(l=e==null?void 0:e.showCloseButton)!=null?l:r==null?void 0:r.showClose)!=null?p:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var $o=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},on=n=>{var se,P,_e,Ye,Qe,xt,Ct,D,he,mt,ft,Je,et,M,Me,it,at,Et,wt,ke,tt,qe,F,lt,Ke;let{config:e}=n,r=c("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=((se=e==null?void 0:e.voiceRecognition)==null?void 0:se.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),p=c("form",`tvw-widget-composer tvw-flex tvw-items-end ${o&&s?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);p.style.outline="none";let h=c("textarea");h.placeholder=(_e=(P=e==null?void 0:e.copy)==null?void 0:P.inputPlaceholder)!=null?_e:"Type your message\u2026",h.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",h.rows=1;let d=(Qe=(Ye=e==null?void 0:e.theme)==null?void 0:Ye.inputFontFamily)!=null?Qe:"sans-serif",T=(Ct=(xt=e==null?void 0:e.theme)==null?void 0:xt.inputFontWeight)!=null?Ct:"400";h.style.fontFamily=$o(d),h.style.fontWeight=T,h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.addEventListener("focus",()=>{h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.style.boxShadow="none"}),h.addEventListener("blur",()=>{h.style.border="none",h.style.outline="none"});let f=(D=e==null?void 0:e.sendButton)!=null?D:{},b=(he=f.useIcon)!=null?he:!1,w=(mt=f.iconText)!=null?mt:"\u2191",q=f.iconName,j=(ft=f.tooltipText)!=null?ft:"Send message",m=(Je=f.showTooltip)!=null?Je:!1,C=(et=f.size)!=null?et:"40px",$=f.backgroundColor,A=f.textColor,Y=c("div","tvw-send-button-wrapper"),I=c("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(I.type="submit",b){if(I.style.width=C,I.style.height=C,I.style.minWidth=C,I.style.minHeight=C,I.style.fontSize="18px",I.style.lineHeight="1",I.innerHTML="",q){let We=parseFloat(C)||24,je=A&&typeof A=="string"&&A.trim()?A.trim():"currentColor",K=ve(q,We,je,2);K?(I.appendChild(K),I.style.color=je):(I.textContent=w,A?I.style.color=A:I.classList.add("tvw-text-white"))}else I.textContent=w,A?I.style.color=A:I.classList.add("tvw-text-white");$?I.style.backgroundColor=$:I.classList.add("tvw-bg-cw-primary")}else I.textContent=(Me=(M=e==null?void 0:e.copy)==null?void 0:M.sendButtonLabel)!=null?Me:"Send",A?I.style.color=A:I.classList.add("tvw-text-white");if(f.borderWidth&&(I.style.borderWidth=f.borderWidth,I.style.borderStyle="solid"),f.borderColor&&(I.style.borderColor=f.borderColor),f.paddingX?(I.style.paddingLeft=f.paddingX,I.style.paddingRight=f.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),f.paddingY?(I.style.paddingTop=f.paddingY,I.style.paddingBottom=f.paddingY):(I.style.paddingTop="",I.style.paddingBottom=""),m&&j){let We=c("div","tvw-send-button-tooltip");We.textContent=j,Y.appendChild(We)}Y.appendChild(I);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},G=V.enabled===!0,S=null,ie=null,J=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(G&&J){ie=c("div","tvw-send-button-wrapper"),S=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),S.type="button",S.setAttribute("aria-label","Start voice recognition");let We=(at=V.iconName)!=null?at:"mic",je=(Et=V.iconSize)!=null?Et:C,K=parseFloat(je)||24,Se=(wt=V.backgroundColor)!=null?wt:$,Le=(ke=V.iconColor)!=null?ke:A;S.style.width=je,S.style.height=je,S.style.minWidth=je,S.style.minHeight=je,S.style.fontSize="18px",S.style.lineHeight="1";let Ue=Le||"currentColor",nt=ve(We,K,Ue,1.5);nt?(S.appendChild(nt),S.style.color=Ue):(S.textContent="\u{1F3A4}",S.style.color=Ue),Se?S.style.backgroundColor=Se:S.classList.add("tvw-bg-cw-primary"),Le?S.style.color=Le:!Le&&!A&&S.classList.add("tvw-text-white"),V.borderWidth&&(S.style.borderWidth=V.borderWidth,S.style.borderStyle="solid"),V.borderColor&&(S.style.borderColor=V.borderColor),V.paddingX&&(S.style.paddingLeft=V.paddingX,S.style.paddingRight=V.paddingX),V.paddingY&&(S.style.paddingTop=V.paddingY,S.style.paddingBottom=V.paddingY),ie.appendChild(S);let St=(tt=V.tooltipText)!=null?tt:"Start voice recognition";if(((qe=V.showTooltip)!=null?qe:!1)&&St){let gt=c("div","tvw-send-button-tooltip");gt.textContent=St,ie.appendChild(gt)}}p.addEventListener("click",We=>{We.target!==I&&We.target!==Y&&We.target!==S&&We.target!==ie&&h.focus()}),p.append(h),ie&&p.append(ie),p.append(Y);let U=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Z=(F=e==null?void 0:e.statusIndicator)!=null?F:{},le=(lt=Z.visible)!=null?lt:!0;return U.style.display=le?"":"none",U.textContent=(Ke=Z.idleText)!=null?Ke:"Online",r.append(t,p,U),{footer:r,suggestions:t,composerForm:p,textarea:h,sendButton:I,sendButtonWrapper:Y,micButton:S,micButtonWrapper:ie,statusText:U}};var go=n=>{var p,h,d,T,f;if(!((h=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)!=null?h:!0)){let b=c("div","tvw-relative tvw-w-full tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),w=c("div","tvw-relative tvw-w-full tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0");return b.appendChild(w),{wrapper:b,panel:w}}let r=(d=n==null?void 0:n.launcher)!=null?d:{},t=r.position&&bt[r.position]?bt[r.position]:bt["bottom-right"],o=c("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=c("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(f=(T=n==null?void 0:n.launcher)==null?void 0:T.width)!=null?f:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,o.appendChild(s),{wrapper:o,panel:s}},ho=(n,e=!0)=>{var T,f,b,w,q;let r=c("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(T=n==null?void 0:n.layout)==null?void 0:T.header,o=t?Ln(n,t,{showClose:e}):Ut({config:n,showClose:e}),s=c("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");s.id="vanilla-agent-scroll-container";let i=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}";let p=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");p.textContent=(q=(w=n==null?void 0:n.copy)==null?void 0:w.welcomeSubtitle)!=null?q:"Ask anything about your account or products.",i.append(l,p);let h=c("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,h);let d=on({config:n});return sn(r,o,n),r.append(s,d.footer),{container:r,body:s,messagesWrapper:h,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:l,introSubtitle:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:d.footer}};var hn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(r),n.appendChild(t),n.appendChild(o),n},Po=(n,e)=>{let r=c("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=c("img");o.src=t,o.alt=e==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},mo=(n,e)=>{let r=c("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?r.textContent=e.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Oo=(n,e="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},rn=(n,e,r)=>{var j,m,C,$,A;let t=r!=null?r:{},o=(j=t.layout)!=null?j:"bubble",s=t.avatar,i=t.timestamp,l=(m=s==null?void 0:s.show)!=null?m:!1,p=(C=i==null?void 0:i.show)!=null?C:!1,h=($=s==null?void 0:s.position)!=null?$:"left",d=(A=i==null?void 0:i.position)!=null?A:"below",T=Oo(n.role,o),f=c("div",T.join(" ")),b=document.createElement("div");if(b.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),p&&d==="inline"&&n.createdAt){let Y=mo(n,i);Y.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(Y)}if(f.appendChild(b),p&&d==="below"&&n.createdAt){let Y=mo(n,i);Y.classList.add("tvw-mt-1"),f.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=hn();f.appendChild(Y)}if(!l||n.role==="system")return f;let w=c("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),q=Po(s,n.role);return h==="right"||h==="left"&&n.role==="user"?w.append(f,q):w.append(q,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),w},No=(n,e,r)=>{let t=r!=null?r:{};return n.role==="user"&&t.renderUserMessage?t.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&t.renderAssistantMessage?t.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):rn(n,e,r)};var Bn=new Set,Hn=n=>{let e=n.reasoning,r=c("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return r;let t=Bn.has(n.id),o=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false");let s=c("div","tvw-flex tvw-flex-col tvw-text-left"),i=c("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=c("span","tvw-text-xs tvw-text-cw-primary");l.textContent=io(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let p=c("div","tvw-flex tvw-items-center"),d=ve(t?"chevron-up":"chevron-down",16,"currentColor",2);d?p.appendChild(d):p.textContent=t?"Hide":"Show";let T=c("div","tvw-flex tvw-items-center tvw-ml-auto");T.append(p),o.append(s,T);let f=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let b=e.chunks.join(""),w=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");w.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(w);let q=()=>{o.setAttribute("aria-expanded",t?"true":"false"),p.innerHTML="";let C=ve(t?"chevron-up":"chevron-down",16,"currentColor",2);C?p.appendChild(C):p.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},j=()=>{t=!t,t?Bn.add(n.id):Bn.delete(n.id),q()};return o.addEventListener("pointerdown",m=>{m.preventDefault(),j()}),o.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),j())}),q(),r.append(o,f),r};var kn=new Set,Rn=(n,e)=>{var j;let r=n.toolCall,t=(j=e==null?void 0:e.toolCall)!=null?j:{},o=c("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=kn.has(n.id),i=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=c("div","tvw-flex tvw-flex-col tvw-text-left"),p=c("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(p.style.color=t.headerTextColor),p.textContent=ao(r),l.appendChild(p);let h=c("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",T=ve(s?"chevron-up":"chevron-down",16,d,2);T?h.appendChild(T):h.textContent=s?"Hide":"Show";let f=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(h),i.append(l,f);let b=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=s?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),r.name){let m=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?m.style.color=t.contentTextColor:t.headerTextColor&&(m.style.color=t.headerTextColor),m.textContent=r.name,b.appendChild(m)}if(r.args!==void 0){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Arguments";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=Cn(r.args),m.append(C,$),b.appendChild(m)}if(r.chunks&&r.chunks.length){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Activity";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=r.chunks.join(`
16
- `),m.append(C,$),b.appendChild(m)}if(r.status==="complete"&&r.result!==void 0){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Result";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=Cn(r.result),m.append(C,$),b.appendChild(m)}if(r.status==="complete"&&typeof r.duration=="number"){let m=c("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${r.duration}ms`,b.appendChild(m)}let w=()=>{i.setAttribute("aria-expanded",s?"true":"false"),h.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",C=ve(s?"chevron-up":"chevron-down",16,m,2);C?h.appendChild(C):h.textContent=s?"Hide":"Show",b.style.display=s?"":"none"},q=()=>{s=!s,s?kn.add(n.id):kn.delete(n.id),w()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),q()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),q())}),w(),o.append(i,b),o};var fo=n=>{let e=[];return{buttons:e,render:(t,o,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(b=>b.role==="user"))return;let d=document.createDocumentFragment(),T=o?o.isStreaming():!1,f=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let w=c("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");w.type="button",w.textContent=b,w.disabled=T,l!=null&&l.fontFamily&&(w.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(w.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(w.style.paddingLeft=l.paddingX,w.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(w.style.paddingTop=l.paddingY,w.style.paddingBottom=l.paddingY),w.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(b))}),d.appendChild(w),e.push(w)}),n.appendChild(d)}}};var wo={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"}},In=(n,e,r,t)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,q,j;if(s.dataset.enhanced==="true")return;let i=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let l=(q=wo[i])!=null?q:wo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let p=c("div","tvw-space-y-1"),h=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(h.textContent=l.title,p.appendChild(h),l.description){let m=c("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,p.appendChild(m)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var I,V;let C=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");C.htmlFor=`${e.id}-${i}-${m.name}`;let $=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");$.textContent=m.label,C.appendChild($);let A=(I=m.type)!=null?I:"text",Y;A==="textarea"?(Y=document.createElement("textarea"),Y.rows=3):(Y=document.createElement("input"),Y.type=A),Y.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",Y.id=`${e.id}-${i}-${m.name}`,Y.name=m.name,Y.placeholder=(V=m.placeholder)!=null?V:"",m.required&&(Y.required=!0),C.appendChild(Y),d.appendChild(C)});let T=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=c("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(j=l.submitLabel)!=null?j:"Submit",T.appendChild(f),T.appendChild(b),d.appendChild(T),s.replaceChildren(p,d),d.addEventListener("submit",async m=>{var Y,I;m.preventDefault();let C=(Y=r.formEndpoint)!=null?Y:"/form",$=new FormData(d),A={};$.forEach((V,G)=>{A[G]=V}),A.type=i,b.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let G=await V.json();f.textContent=(I=G.message)!=null?I:"Thanks! We'll be in touch soon.",G.success&&G.nextPrompt&&await t.sendMessage(String(G.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var $n=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var t;let r=this.plugins.get(e);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let t=new Set(e.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,p;return((l=i.priority)!=null?l:0)-((p=s.priority)!=null?p:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},mn=new $n;var Ne={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},debug:!1};function Pn(n){var e,r,t,o,s,i,l,p,h,d,T,f,b,w,q,j,m;return n?{...Ne,...n,theme:{...Ne.theme,...n.theme},launcher:{...Ne.launcher,...n.launcher,clearChat:{...(e=Ne.launcher)==null?void 0:e.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...Ne.copy,...n.copy},sendButton:{...Ne.sendButton,...n.sendButton},statusIndicator:{...Ne.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ne.voiceRecognition,...n.voiceRecognition},features:{...Ne.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Ne.suggestionChips,suggestionChipsConfig:{...Ne.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ne.layout,...n.layout,header:{...(o=Ne.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Ne.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(h=(p=Ne.layout)==null?void 0:p.messages)==null?void 0:h.avatar,...(T=(d=n.layout)==null?void 0:d.messages)==null?void 0:T.avatar},timestamp:{...(b=(f=Ne.layout)==null?void 0:f.messages)==null?void 0:b.timestamp,...(q=(w=n.layout)==null?void 0:w.messages)==null?void 0:q.timestamp}},slots:{...(j=Ne.layout)==null?void 0:j.slots,...(m=n.layout)==null?void 0:m.slots}}}:Ne}var yo=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:e,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(l=>{try{l(s)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var Do=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Fo=n=>{let e=n.trim(),r=e.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(r,o+1)}return null},fn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Do(n),r=Fo(e);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},On=n=>typeof n=="string"?n:n==null?"":String(n),Xt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:On(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,t=On(r.element);if(t&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:On(r.text)}}},vo=n=>Array.isArray(n)?n.map(e=>String(e)):[],wn=n=>{let e=new Set(vo(n.getMetadata().processedActionMessageIds)),r=()=>{e=new Set(vo(n.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((h,d)=>h||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let p={action:l,message:s.message};n.emit("action:detected",p);for(let h of n.handlers)if(h)try{let d=h(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let T=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:T}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:r}};var jo=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},_o=n=>n.map(e=>({...e,streaming:!1})),Nn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?jo(r.getItem(n)):null},save:r=>{let t=e();if(t)try{let o={...r,messages:r.messages?_o(r.messages):void 0};t.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Dn=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,t])=>{this.register(r,t)})}},an=new Dn;import{parse as qo,STR as Uo,OBJ as zo}from"partial-json";function Yo(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function Jo(n,e){if(!Yo(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:e}}function Fn(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n;try{let o=qo(r,Uo|zo),s=Jo(o,r);s&&(n=s)}catch{}return e=r.length,n},reset:()=>{n=null,e=0}}}function Ko(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function jn(n,e){let{config:r,message:t,onPropsUpdate:o}=e,s=an.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:l=>{o&&o(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Xo(){let n=Fn();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function _n(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function qn(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var Vt="vanilla-agent-chat-history",Vo=30*1e3,Un=n=>!n||typeof n!="object"?{}:{...n},bo=n=>n.map(e=>({...e,streaming:!1})),xo=(n,e)=>r=>{var s,i,l;let t=(s=r.text)!=null?s:"",o=(i=r.message.rawContent)!=null?i:null;if(e){let p=e.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 n!=null&&n.postprocessMessage?n.postprocessMessage({...r,text:t,raw:(l=o!=null?o:r.text)!=null?l:""}):xn(t)},zn=(n,e,r)=>{var ae,pe,He,ue,Pe,rt,ht,Jn,Kn,Xn,Vn,Gn,Zn,Qn;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Pn(e),o=mn.getForInstance(t.plugins);t.components&&an.registerAll(t.components);let s=yo(),i=(ae=t.storageAdapter)!=null?ae:Nn(),l={},p=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")p=a;else if(a){let u=a;u.metadata&&(l=Un(u.metadata)),(pe=u.messages)!=null&&pe.length&&(t={...t,initialMessages:u.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let h=()=>l,d=a=>{var E;l=(E=a({...l}))!=null?E:{},Ht()},T=t.actionParsers&&t.actionParsers.length?t.actionParsers:[fn],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Xt.message,Xt.messageAndClick],b=wn({parsers:T,handlers:f,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let w=(ue=(He=t.launcher)==null?void 0:He.enabled)!=null?ue:!0,q=(rt=(Pe=t.launcher)==null?void 0:Pe.autoExpand)!=null?rt:!1,j=q,m=w,C=w?q:!0,$=xo(t,b),A=(Jn=(ht=t.features)==null?void 0:ht.showReasoning)!=null?Jn:!0,Y=(Xn=(Kn=t.features)==null?void 0:Kn.showToolCalls)!=null?Xn:!0,I=(Vn=t.statusIndicator)!=null?Vn:{},V=a=>{var u,E,O,k;return a==="idle"?(u=I.idleText)!=null?u:ze.idle:a==="connecting"?(E=I.connectingText)!=null?E:ze.connecting:a==="connected"?(O=I.connectedText)!=null?O:ze.connected:a==="error"?(k=I.errorText)!=null?k:ze.error:ze[a]},{wrapper:G,panel:S}=go(t),ie=ho(t,w),{container:J,body:U,messagesWrapper:Z,suggestions:le,textarea:se,sendButton:P,sendButtonWrapper:_e,composerForm:Ye,statusText:Qe,introTitle:xt,introSubtitle:Ct,closeButton:D,iconHolder:he,headerTitle:mt,headerSubtitle:ft,header:Je,footer:et}=ie,M=ie.micButton,Me=ie.micButtonWrapper,it=o.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let u=Ut({config:t,showClose:w});return sn(J,u,t),u.header},onClose:()=>st(!1,"user")});if(a){let u=J.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(a),Je=a)}}let at=o.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>on({config:t}).footer,onSubmit:u=>{F&&!F.isStreaming()&&F.sendMessage(u)},disabled:!1});a&&(et.replaceWith(a),et=a)}(()=>{var O,k;let a=(k=(O=t.layout)==null?void 0:O.slots)!=null?k:{},u=te=>{switch(te){case"body-top":return J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Z;case"footer-top":return le;case"composer":return Ye;case"footer-bottom":return Qe;default:return null}},E=(te,H)=>{var v;switch(te){case"header-left":case"header-center":case"header-right":if(te==="header-left")Je.insertBefore(H,Je.firstChild);else if(te==="header-right")Je.appendChild(H);else{let N=Je.querySelector(".tvw-flex-col");N?(v=N.parentNode)==null||v.insertBefore(H,N.nextSibling):Je.appendChild(H)}break;case"body-top":let z=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");z?z.replaceWith(H):U.insertBefore(H,U.firstChild);break;case"body-bottom":U.appendChild(H);break;case"footer-top":le.replaceWith(H);break;case"footer-bottom":Qe.replaceWith(H);break;default:break}};for(let[te,H]of Object.entries(a))if(H)try{let v=H({config:t,defaultContent:()=>u(te)});v&&E(te,v)}catch(v){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${te}":`,v)}})(),S.appendChild(J),n.appendChild(G);let wt=()=>{var re,Oe,dt,oe,ct,kt,Rt,Mt,jt,It,_t,pt,$t,Pt,pn,en;let a=(Oe=(re=t.launcher)==null?void 0:re.sidebarMode)!=null?Oe:!1,u=a||((oe=(dt=t.launcher)==null?void 0:dt.fullHeight)!=null?oe:!1),E=(ct=t.theme)!=null?ct:{},O=(Rt=(kt=t.launcher)==null?void 0:kt.position)!=null?Rt:"bottom-left",k=O==="bottom-left"||O==="top-left",te=a?"none":"1px solid var(--tvw-cw-border)",H=a?k?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",v=a?"0":"16px",z=(Mt=E.panelBorder)!=null?Mt:te,N=(jt=E.panelShadow)!=null?jt:H,R=(It=E.panelBorderRadius)!=null?It:v;n.style.cssText="",G.style.cssText="",S.style.cssText="",J.style.cssText="",U.style.cssText="",et.style.cssText="";let _=(pt=(_t=t==null?void 0:t.launcher)==null?void 0:_t.width)!=null?pt:t==null?void 0:t.launcherWidth,$e=_!=null?_:"min(400px, calc(100vw - 24px))";a||(S.style.width=$e,S.style.maxWidth=$e),S.style.boxShadow=N,S.style.borderRadius=R,J.style.border=z,J.style.borderRadius=R;let ye=(($t=t.launcher)==null?void 0:$t.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.height="100%",ye&&(G.style.overflow="hidden"),S.style.display="flex",S.style.flexDirection="column",S.style.flex="1 1 0%",S.style.minHeight="0",S.style.maxHeight="100%",S.style.height="100%",S.style.overflow="hidden",J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",et.style.flexShrink="0"),G.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!a&&!ye&&((Pt=bt[O])!=null?Pt:bt["bottom-right"]).split(" ").forEach(Yt=>G.classList.add(Yt)),a){let qt=(en=(pn=t.launcher)==null?void 0:pn.sidebarWidth)!=null?en:"420px";G.style.cssText=`
15
+ `,r.addEventListener("click",e);let t=s=>{var D,N,h,C,$,A,z,I,V,G;let i=(D=s.launcher)!=null?D:{},l=r.querySelector("[data-role='launcher-title']");l&&(l.textContent=(N=i.title)!=null?N:"Chat Assistant");let p=r.querySelector("[data-role='launcher-subtitle']");p&&(p.textContent=(h=i.subtitle)!=null?h:"Get answers fast");let m=r.querySelector(".tvw-flex-col");m&&(i.textHidden?m.style.display="none":m.style.display="");let d=r.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let S=(C=i.agentIconSize)!=null?C:"40px";if(d.style.height=S,d.style.width=S,d.innerHTML="",i.agentIconName){let ie=parseFloat(S)||24,Y=ve(i.agentIconName,ie*.6,"#ffffff",2);Y?(d.appendChild(Y),d.style.display=""):(d.textContent=($=i.agentIconText)!=null?$:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(A=i.agentIconText)!=null?A:"\u{1F4AC}",d.style.display="")}let T=r.querySelector("[data-role='launcher-image']");if(T){let S=(z=i.agentIconSize)!=null?z:"40px";T.style.height=S,T.style.width=S,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(T.src=i.iconUrl,T.style.display="block"):T.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let S=(I=i.callToActionIconSize)!=null?I:"32px";f.style.height=S,f.style.width=S,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let ie=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,ie=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let Y=parseFloat(S)||24,U=Math.max(Y-ie,8),Z=ve(i.callToActionIconName,U,"currentColor",2);Z?f.appendChild(Z):f.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}else f.textContent=(G=i.callToActionIconText)!=null?G:"\u2197"}let b=i.position&&bt[i.position]?bt[i.position]:bt["bottom-right"],w="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${w} ${b}`},o=()=>{r.removeEventListener("click",e),r.remove()};return n&&t(n),{element:r,update:t,destroy:o}};var Ut=n=>{var ie,Y,U,Z,le,oe,P,_e,Ye,Qe,xt,Ct,j,me,mt,ft,Je,et,M,Le,it,at,Et,wt,Ie,tt,qe,_,lt,Ke,We,je;let{config:e,showClose:r=!0}=n,t=c("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(ie=e==null?void 0:e.launcher)!=null?ie:{},s=(Y=o.headerIconSize)!=null?Y:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",l=(Z=o.closeButtonPlacement)!=null?Z:"inline",p=(le=o.headerIconHidden)!=null?le:!1,m=o.headerIconName,d=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(d.style.height=s,d.style.width=s,!p)if(m){let J=parseFloat(s)||24,Se=ve(m,J*.6,"#ffffff",2);Se?d.replaceChildren(Se):d.textContent=(P=(oe=e==null?void 0:e.launcher)==null?void 0:oe.agentIconText)!=null?P:"\u{1F4AC}"}else if((_e=e==null?void 0:e.launcher)!=null&&_e.iconUrl){let J=c("img");J.src=e.launcher.iconUrl,J.alt="",J.className="tvw-rounded-xl tvw-object-cover",J.style.height=s,J.style.width=s,d.replaceChildren(J)}else d.textContent=(Qe=(Ye=e==null?void 0:e.launcher)==null?void 0:Ye.agentIconText)!=null?Qe:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col"),f=c("span","tvw-text-base tvw-font-semibold");f.textContent=(Ct=(xt=e==null?void 0:e.launcher)==null?void 0:xt.title)!=null?Ct:"Chat Assistant";let b=c("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(me=(j=e==null?void 0:e.launcher)==null?void 0:j.subtitle)!=null?me:"Here to help you get answers fast",T.append(f,b),p?t.append(T):t.append(d,T);let w=(mt=o.clearChat)!=null?mt:{},D=(ft=w.enabled)!=null?ft:!0,N=(Je=w.placement)!=null?Je:"inline",h=null,C=null;if(D){let J=(et=w.size)!=null?et:"32px",Se=(M=w.iconName)!=null?M:"refresh-cw",Be=(Le=w.iconColor)!=null?Le:"",Ue=(it=w.backgroundColor)!=null?it:"",nt=(at=w.borderWidth)!=null?at:"",St=(Et=w.borderColor)!=null?Et:"",Lt=(wt=w.borderRadius)!=null?wt:"",gt=(Ie=w.paddingX)!=null?Ie:"",At=(tt=w.paddingY)!=null?tt:"",de=(qe=w.tooltipText)!=null?qe:"Clear chat",Nt=(_=w.showTooltip)!=null?_:!0;C=c("div",N==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),N==="top-right"&&(C.style.right="48px"),h=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),h.style.height=J,h.style.width=J,h.type="button",h.setAttribute("aria-label",de);let Bt=ve(Se,"20px",Be||"",2);if(Bt&&h.appendChild(Bt),Be&&(h.style.color=Be,h.classList.remove("tvw-text-cw-muted")),Ue&&(h.style.backgroundColor=Ue,h.classList.remove("hover:tvw-bg-gray-100")),nt||St){let be=nt||"0px",yt=St||"transparent";h.style.border=`${be} solid ${yt}`,h.classList.remove("tvw-border-none")}if(Lt&&(h.style.borderRadius=Lt,h.classList.remove("tvw-rounded-full")),gt?(h.style.paddingLeft=gt,h.style.paddingRight=gt):(h.style.paddingLeft="",h.style.paddingRight=""),At?(h.style.paddingTop=At,h.style.paddingBottom=At):(h.style.paddingTop="",h.style.paddingBottom=""),C.appendChild(h),Nt&&de&&h&&C){let be=null,yt=()=>{if(be||!h)return;be=c("div","tvw-clear-chat-tooltip"),be.textContent=de;let Ht=c("div");Ht.className="tvw-clear-chat-tooltip-arrow",be.appendChild(Ht);let vt=h.getBoundingClientRect();be.style.position="fixed",be.style.left=`${vt.left+vt.width/2}px`,be.style.top=`${vt.top-8}px`,be.style.transform="translate(-50%, -100%)",document.body.appendChild(be)},Tt=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};C.addEventListener("mouseenter",yt),C.addEventListener("mouseleave",Tt),h.addEventListener("focus",yt),h.addEventListener("blur",Tt),C._cleanupTooltip=()=>{Tt(),C&&(C.removeEventListener("mouseenter",yt),C.removeEventListener("mouseleave",Tt)),h&&(h.removeEventListener("focus",yt),h.removeEventListener("blur",Tt))}}N==="inline"&&t.appendChild(C)}let $=c("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":D&&N==="inline"?"":"tvw-ml-auto"),A=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");A.style.height=i,A.style.width=i,A.type="button";let z=(lt=o.closeButtonTooltipText)!=null?lt:"Close chat",I=(Ke=o.closeButtonShowTooltip)!=null?Ke:!0;A.setAttribute("aria-label",z),A.style.display=r?"":"none";let V=(We=o.closeButtonIconName)!=null?We:"x",G=(je=o.closeButtonIconText)!=null?je:"\xD7",S=ve(V,"20px",o.closeButtonColor||"",2);if(S?A.appendChild(S):A.textContent=G,o.closeButtonColor?(A.style.color=o.closeButtonColor,A.classList.remove("tvw-text-cw-muted")):(A.style.color="",A.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(A.style.backgroundColor=o.closeButtonBackgroundColor,A.classList.remove("hover:tvw-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let J=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";A.style.border=`${J} solid ${Se}`,A.classList.remove("tvw-border-none")}else A.style.border="",A.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(A.style.borderRadius=o.closeButtonBorderRadius,A.classList.remove("tvw-rounded-full")):(A.style.borderRadius="",A.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(A.style.paddingLeft=o.closeButtonPaddingX,A.style.paddingRight=o.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),o.closeButtonPaddingY?(A.style.paddingTop=o.closeButtonPaddingY,A.style.paddingBottom=o.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom=""),$.appendChild(A),I&&z){let J=null,Se=()=>{if(J)return;J=c("div","tvw-clear-chat-tooltip"),J.textContent=z;let Ue=c("div");Ue.className="tvw-clear-chat-tooltip-arrow",J.appendChild(Ue);let nt=A.getBoundingClientRect();J.style.position="fixed",J.style.left=`${nt.left+nt.width/2}px`,J.style.top=`${nt.top-8}px`,J.style.transform="translate(-50%, -100%)",document.body.appendChild(J)},Be=()=>{J&&J.parentNode&&(J.parentNode.removeChild(J),J=null)};$.addEventListener("mouseenter",Se),$.addEventListener("mouseleave",Be),A.addEventListener("focus",Se),A.addEventListener("blur",Be),$._cleanupTooltip=()=>{Be(),$.removeEventListener("mouseenter",Se),$.removeEventListener("mouseleave",Be),A.removeEventListener("focus",Se),A.removeEventListener("blur",Be)}}return l!=="top-right"&&t.appendChild($),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:b,closeButton:A,closeButtonWrapper:$,clearChatButton:h,clearChatButtonWrapper:C}},sn=(n,e,r)=>{var i,l,p,m;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(l=t.closeButtonPlacement)!=null?l:"inline",s=(m=(p=t.clearChat)==null?void 0:p.placement)!=null?m:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var lo=n=>Ut({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),co=n=>{var w,D,N,h;let{config:e,showClose:r=!0,onClose:t}=n,o=(w=e==null?void 0:e.launcher)!=null?w:{},s=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=c("span","tvw-text-base tvw-font-semibold");i.textContent=(D=o.title)!=null?D:"Chat Assistant",s.appendChild(i);let l=(N=o.closeButtonSize)!=null?N:"32px",p=c("div",""),m=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");m.style.height=l,m.style.width=l,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none";let d=(h=o.closeButtonIconName)!=null?h:"x",T=ve(d,"20px",o.closeButtonColor||"",2);T?m.appendChild(T):m.textContent="\xD7",t&&m.addEventListener("click",t),p.appendChild(m),s.appendChild(p);let f=c("div");f.style.display="none";let b=c("span");return b.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:b,closeButton:m,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},po=n=>{var A,z,I,V,G,S,ie,Y;let{config:e,showClose:r=!0,onClose:t,onClearChat:o}=n,s=(A=e==null?void 0:e.launcher)!=null?A:{},i=c("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=c("div","tvw-flex tvw-items-center tvw-gap-3"),p=(z=s.headerIconSize)!=null?z:"56px",m=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");m.style.height=p,m.style.width=p;let d=s.headerIconName;if(d){let U=parseFloat(p)||24,Z=ve(d,U*.5,"#ffffff",2);Z?m.replaceChildren(Z):m.textContent=(I=s.agentIconText)!=null?I:"\u{1F4AC}"}else if(s.iconUrl){let U=c("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=p,U.style.width=p,m.replaceChildren(U)}else m.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col tvw-flex-1"),f=c("span","tvw-text-lg tvw-font-semibold");f.textContent=(G=s.title)!=null?G:"Chat Assistant";let b=c("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(S=s.subtitle)!=null?S:"Here to help you get answers fast",T.append(f,b),l.append(m,T);let w=(ie=s.closeButtonSize)!=null?ie:"32px",D=c("div",""),N=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");N.style.height=w,N.style.width=w,N.type="button",N.setAttribute("aria-label","Close chat"),N.style.display=r?"":"none";let h=(Y=s.closeButtonIconName)!=null?Y:"x",C=ve(h,"20px",s.closeButtonColor||"",2);C?N.appendChild(C):N.textContent="\xD7",t&&N.addEventListener("click",t),D.appendChild(N),l.appendChild(D),i.appendChild(l);let $=c("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return $.textContent="Online and ready to help",i.appendChild($),{header:i,iconHolder:m,headerTitle:f,headerSubtitle:b,closeButton:N,closeButtonWrapper:D,clearChatButton:null,clearChatButtonWrapper:null}},Mn={default:lo,minimal:co,expanded:po},uo=n=>{var e;return(e=Mn[n])!=null?e:Mn.default},Ln=(n,e,r)=>{var i,l,p;if(e!=null&&e.render){let m=e.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),d=c("div");d.style.display="none";let T=c("span"),f=c("span"),b=c("button");b.style.display="none";let w=c("div");return w.style.display="none",{header:m,iconHolder:d,headerTitle:T,headerSubtitle:f,closeButton:b,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=uo(t)({config:n,showClose:(p=(l=e==null?void 0:e.showCloseButton)!=null?l:r==null?void 0:r.showClose)!=null?p:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var $o=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},on=n=>{var oe,P,_e,Ye,Qe,xt,Ct,j,me,mt,ft,Je,et,M,Le,it,at,Et,wt,Ie,tt,qe,_,lt,Ke;let{config:e}=n,r=c("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=((oe=e==null?void 0:e.voiceRecognition)==null?void 0:oe.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),p=c("form",`tvw-widget-composer tvw-flex tvw-items-end ${o&&s?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);p.style.outline="none";let m=c("textarea");m.placeholder=(_e=(P=e==null?void 0:e.copy)==null?void 0:P.inputPlaceholder)!=null?_e:"Type your message\u2026",m.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",m.rows=1;let d=(Qe=(Ye=e==null?void 0:e.theme)==null?void 0:Ye.inputFontFamily)!=null?Qe:"sans-serif",T=(Ct=(xt=e==null?void 0:e.theme)==null?void 0:xt.inputFontWeight)!=null?Ct:"400";m.style.fontFamily=$o(d),m.style.fontWeight=T,m.style.border="none",m.style.outline="none",m.style.borderWidth="0",m.style.borderStyle="none",m.style.borderColor="transparent",m.addEventListener("focus",()=>{m.style.border="none",m.style.outline="none",m.style.borderWidth="0",m.style.borderStyle="none",m.style.borderColor="transparent",m.style.boxShadow="none"}),m.addEventListener("blur",()=>{m.style.border="none",m.style.outline="none"});let f=(j=e==null?void 0:e.sendButton)!=null?j:{},b=(me=f.useIcon)!=null?me:!1,w=(mt=f.iconText)!=null?mt:"\u2191",D=f.iconName,N=(ft=f.tooltipText)!=null?ft:"Send message",h=(Je=f.showTooltip)!=null?Je:!1,C=(et=f.size)!=null?et:"40px",$=f.backgroundColor,A=f.textColor,z=c("div","tvw-send-button-wrapper"),I=c("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(I.type="submit",b){if(I.style.width=C,I.style.height=C,I.style.minWidth=C,I.style.minHeight=C,I.style.fontSize="18px",I.style.lineHeight="1",I.innerHTML="",D){let We=parseFloat(C)||24,je=A&&typeof A=="string"&&A.trim()?A.trim():"currentColor",J=ve(D,We,je,2);J?(I.appendChild(J),I.style.color=je):(I.textContent=w,A?I.style.color=A:I.classList.add("tvw-text-white"))}else I.textContent=w,A?I.style.color=A:I.classList.add("tvw-text-white");$?I.style.backgroundColor=$:I.classList.add("tvw-bg-cw-primary")}else I.textContent=(Le=(M=e==null?void 0:e.copy)==null?void 0:M.sendButtonLabel)!=null?Le:"Send",A?I.style.color=A:I.classList.add("tvw-text-white");if(f.borderWidth&&(I.style.borderWidth=f.borderWidth,I.style.borderStyle="solid"),f.borderColor&&(I.style.borderColor=f.borderColor),f.paddingX?(I.style.paddingLeft=f.paddingX,I.style.paddingRight=f.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),f.paddingY?(I.style.paddingTop=f.paddingY,I.style.paddingBottom=f.paddingY):(I.style.paddingTop="",I.style.paddingBottom=""),h&&N){let We=c("div","tvw-send-button-tooltip");We.textContent=N,z.appendChild(We)}z.appendChild(I);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},G=V.enabled===!0,S=null,ie=null,Y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(G&&Y){ie=c("div","tvw-send-button-wrapper"),S=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),S.type="button",S.setAttribute("aria-label","Start voice recognition");let We=(at=V.iconName)!=null?at:"mic",je=(Et=V.iconSize)!=null?Et:C,J=parseFloat(je)||24,Se=(wt=V.backgroundColor)!=null?wt:$,Be=(Ie=V.iconColor)!=null?Ie:A;S.style.width=je,S.style.height=je,S.style.minWidth=je,S.style.minHeight=je,S.style.fontSize="18px",S.style.lineHeight="1";let Ue=Be||"currentColor",nt=ve(We,J,Ue,1.5);nt?(S.appendChild(nt),S.style.color=Ue):(S.textContent="\u{1F3A4}",S.style.color=Ue),Se?S.style.backgroundColor=Se:S.classList.add("tvw-bg-cw-primary"),Be?S.style.color=Be:!Be&&!A&&S.classList.add("tvw-text-white"),V.borderWidth&&(S.style.borderWidth=V.borderWidth,S.style.borderStyle="solid"),V.borderColor&&(S.style.borderColor=V.borderColor),V.paddingX&&(S.style.paddingLeft=V.paddingX,S.style.paddingRight=V.paddingX),V.paddingY&&(S.style.paddingTop=V.paddingY,S.style.paddingBottom=V.paddingY),ie.appendChild(S);let St=(tt=V.tooltipText)!=null?tt:"Start voice recognition";if(((qe=V.showTooltip)!=null?qe:!1)&&St){let gt=c("div","tvw-send-button-tooltip");gt.textContent=St,ie.appendChild(gt)}}p.addEventListener("click",We=>{We.target!==I&&We.target!==z&&We.target!==S&&We.target!==ie&&m.focus()}),p.append(m),ie&&p.append(ie),p.append(z);let U=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Z=(_=e==null?void 0:e.statusIndicator)!=null?_:{},le=(lt=Z.visible)!=null?lt:!0;return U.style.display=le?"":"none",U.textContent=(Ke=Z.idleText)!=null?Ke:"Online",r.append(t,p,U),{footer:r,suggestions:t,composerForm:p,textarea:m,sendButton:I,sendButtonWrapper:z,micButton:S,micButtonWrapper:ie,statusText:U}};var go=n=>{var p,m,d,T,f,b,w;if(!((m=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)!=null?m:!0)){let D=c("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),N=c("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),h=(T=(d=n==null?void 0:n.launcher)==null?void 0:d.width)!=null?T:"100%";return D.style.width=h,N.style.width="100%",D.appendChild(N),{wrapper:D,panel:N}}let r=(f=n==null?void 0:n.launcher)!=null?f:{},t=r.position&&bt[r.position]?bt[r.position]:bt["bottom-right"],o=c("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=c("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(w=(b=n==null?void 0:n.launcher)==null?void 0:b.width)!=null?w:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,o.appendChild(s),{wrapper:o,panel:s}},ho=(n,e=!0)=>{var T,f,b,w,D;let r=c("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(T=n==null?void 0:n.layout)==null?void 0:T.header,o=t?Ln(n,t,{showClose:e}):Ut({config:n,showClose:e}),s=c("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");s.id="vanilla-agent-scroll-container";let i=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}";let p=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");p.textContent=(D=(w=n==null?void 0:n.copy)==null?void 0:w.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",i.append(l,p);let m=c("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,m);let d=on({config:n});return sn(r,o,n),r.append(s,d.footer),{container:r,body:s,messagesWrapper:m,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:l,introSubtitle:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:d.footer}};var hn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(r),n.appendChild(t),n.appendChild(o),n},Po=(n,e)=>{let r=c("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=c("img");o.src=t,o.alt=e==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},mo=(n,e)=>{let r=c("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?r.textContent=e.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Oo=(n,e="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},rn=(n,e,r)=>{var N,h,C,$,A;let t=r!=null?r:{},o=(N=t.layout)!=null?N:"bubble",s=t.avatar,i=t.timestamp,l=(h=s==null?void 0:s.show)!=null?h:!1,p=(C=i==null?void 0:i.show)!=null?C:!1,m=($=s==null?void 0:s.position)!=null?$:"left",d=(A=i==null?void 0:i.position)!=null?A:"below",T=Oo(n.role,o),f=c("div",T.join(" ")),b=document.createElement("div");if(b.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),p&&d==="inline"&&n.createdAt){let z=mo(n,i);z.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(z)}if(f.appendChild(b),p&&d==="below"&&n.createdAt){let z=mo(n,i);z.classList.add("tvw-mt-1"),f.appendChild(z)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let z=hn();f.appendChild(z)}if(!l||n.role==="system")return f;let w=c("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),D=Po(s,n.role);return m==="right"||m==="left"&&n.role==="user"?w.append(f,D):w.append(D,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),w},No=(n,e,r)=>{let t=r!=null?r:{};return n.role==="user"&&t.renderUserMessage?t.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&t.renderAssistantMessage?t.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):rn(n,e,r)};var Bn=new Set,Hn=n=>{let e=n.reasoning,r=c("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return r;let t=Bn.has(n.id),o=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false");let s=c("div","tvw-flex tvw-flex-col tvw-text-left"),i=c("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=c("span","tvw-text-xs tvw-text-cw-primary");l.textContent=io(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let p=c("div","tvw-flex tvw-items-center"),d=ve(t?"chevron-up":"chevron-down",16,"currentColor",2);d?p.appendChild(d):p.textContent=t?"Hide":"Show";let T=c("div","tvw-flex tvw-items-center tvw-ml-auto");T.append(p),o.append(s,T);let f=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let b=e.chunks.join(""),w=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");w.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(w);let D=()=>{o.setAttribute("aria-expanded",t?"true":"false"),p.innerHTML="";let C=ve(t?"chevron-up":"chevron-down",16,"currentColor",2);C?p.appendChild(C):p.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},N=()=>{t=!t,t?Bn.add(n.id):Bn.delete(n.id),D()};return o.addEventListener("pointerdown",h=>{h.preventDefault(),N()}),o.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),N())}),D(),r.append(o,f),r};var kn=new Set,Rn=(n,e)=>{var N;let r=n.toolCall,t=(N=e==null?void 0:e.toolCall)!=null?N:{},o=c("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=kn.has(n.id),i=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=c("div","tvw-flex tvw-flex-col tvw-text-left"),p=c("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(p.style.color=t.headerTextColor),p.textContent=ao(r),l.appendChild(p);let m=c("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",T=ve(s?"chevron-up":"chevron-down",16,d,2);T?m.appendChild(T):m.textContent=s?"Hide":"Show";let f=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(m),i.append(l,f);let b=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=s?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),r.name){let h=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?h.style.color=t.contentTextColor:t.headerTextColor&&(h.style.color=t.headerTextColor),h.textContent=r.name,b.appendChild(h)}if(r.args!==void 0){let h=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Arguments";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=Cn(r.args),h.append(C,$),b.appendChild(h)}if(r.chunks&&r.chunks.length){let h=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Activity";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=r.chunks.join(`
16
+ `),h.append(C,$),b.appendChild(h)}if(r.status==="complete"&&r.result!==void 0){let h=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Result";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=Cn(r.result),h.append(C,$),b.appendChild(h)}if(r.status==="complete"&&typeof r.duration=="number"){let h=c("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(h.style.color=t.contentTextColor),h.textContent=`Duration: ${r.duration}ms`,b.appendChild(h)}let w=()=>{i.setAttribute("aria-expanded",s?"true":"false"),m.innerHTML="";let h=t.toggleTextColor||t.headerTextColor||"currentColor",C=ve(s?"chevron-up":"chevron-down",16,h,2);C?m.appendChild(C):m.textContent=s?"Hide":"Show",b.style.display=s?"":"none"},D=()=>{s=!s,s?kn.add(n.id):kn.delete(n.id),w()};return i.addEventListener("pointerdown",h=>{h.preventDefault(),D()}),i.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),D())}),w(),o.append(i,b),o};var fo=n=>{let e=[];return{buttons:e,render:(t,o,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(b=>b.role==="user"))return;let d=document.createDocumentFragment(),T=o?o.isStreaming():!1,f=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let w=c("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");w.type="button",w.textContent=b,w.disabled=T,l!=null&&l.fontFamily&&(w.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(w.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(w.style.paddingLeft=l.paddingX,w.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(w.style.paddingTop=l.paddingY,w.style.paddingBottom=l.paddingY),w.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(b))}),d.appendChild(w),e.push(w)}),n.appendChild(d)}}};var wo={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"}},In=(n,e,r,t)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,D,N;if(s.dataset.enhanced==="true")return;let i=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let l=(D=wo[i])!=null?D:wo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let p=c("div","tvw-space-y-1"),m=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(m.textContent=l.title,p.appendChild(m),l.description){let h=c("p","tvw-text-sm tvw-text-cw-muted");h.textContent=l.description,p.appendChild(h)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(h=>{var I,V;let C=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");C.htmlFor=`${e.id}-${i}-${h.name}`;let $=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");$.textContent=h.label,C.appendChild($);let A=(I=h.type)!=null?I:"text",z;A==="textarea"?(z=document.createElement("textarea"),z.rows=3):(z=document.createElement("input"),z.type=A),z.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",z.id=`${e.id}-${i}-${h.name}`,z.name=h.name,z.placeholder=(V=h.placeholder)!=null?V:"",h.required&&(z.required=!0),C.appendChild(z),d.appendChild(C)});let T=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=c("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(N=l.submitLabel)!=null?N:"Submit",T.appendChild(f),T.appendChild(b),d.appendChild(T),s.replaceChildren(p,d),d.addEventListener("submit",async h=>{var z,I;h.preventDefault();let C=(z=r.formEndpoint)!=null?z:"/form",$=new FormData(d),A={};$.forEach((V,G)=>{A[G]=V}),A.type=i,b.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let G=await V.json();f.textContent=(I=G.message)!=null?I:"Thanks! We'll be in touch soon.",G.success&&G.nextPrompt&&await t.sendMessage(String(G.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var $n=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var t;let r=this.plugins.get(e);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let t=new Set(e.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,p;return((l=i.priority)!=null?l:0)-((p=s.priority)!=null?p:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},mn=new $n;var Ne={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},debug:!1};function Pn(n){var e,r,t,o,s,i,l,p,m,d,T,f,b,w,D,N,h;return n?{...Ne,...n,theme:{...Ne.theme,...n.theme},launcher:{...Ne.launcher,...n.launcher,clearChat:{...(e=Ne.launcher)==null?void 0:e.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...Ne.copy,...n.copy},sendButton:{...Ne.sendButton,...n.sendButton},statusIndicator:{...Ne.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ne.voiceRecognition,...n.voiceRecognition},features:{...Ne.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Ne.suggestionChips,suggestionChipsConfig:{...Ne.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ne.layout,...n.layout,header:{...(o=Ne.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Ne.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(m=(p=Ne.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(T=(d=n.layout)==null?void 0:d.messages)==null?void 0:T.avatar},timestamp:{...(b=(f=Ne.layout)==null?void 0:f.messages)==null?void 0:b.timestamp,...(D=(w=n.layout)==null?void 0:w.messages)==null?void 0:D.timestamp}},slots:{...(N=Ne.layout)==null?void 0:N.slots,...(h=n.layout)==null?void 0:h.slots}}}:Ne}var yo=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:e,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(l=>{try{l(s)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var Fo=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Do=n=>{let e=n.trim(),r=e.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(r,o+1)}return null},fn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Fo(n),r=Do(e);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},On=n=>typeof n=="string"?n:n==null?"":String(n),Xt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:On(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,t=On(r.element);if(t&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:On(r.text)}}},vo=n=>Array.isArray(n)?n.map(e=>String(e)):[],wn=n=>{let e=new Set(vo(n.getMetadata().processedActionMessageIds)),r=()=>{e=new Set(vo(n.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((m,d)=>m||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let p={action:l,message:s.message};n.emit("action:detected",p);for(let m of n.handlers)if(m)try{let d=m(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let T=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:T}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:r}};var jo=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},_o=n=>n.map(e=>({...e,streaming:!1})),Nn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?jo(r.getItem(n)):null},save:r=>{let t=e();if(t)try{let o={...r,messages:r.messages?_o(r.messages):void 0};t.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Fn=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,t])=>{this.register(r,t)})}},an=new Fn;import{parse as qo,STR as Uo,OBJ as zo}from"partial-json";function Yo(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function Jo(n,e){if(!Yo(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:e}}function Dn(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n;try{let o=qo(r,Uo|zo),s=Jo(o,r);s&&(n=s)}catch{}return e=r.length,n},reset:()=>{n=null,e=0}}}function Ko(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function jn(n,e){let{config:r,message:t,onPropsUpdate:o}=e,s=an.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:l=>{o&&o(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Xo(){let n=Dn();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function _n(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function qn(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var Vt="vanilla-agent-chat-history",Vo=30*1e3,Un=n=>!n||typeof n!="object"?{}:{...n},bo=n=>n.map(e=>({...e,streaming:!1})),xo=(n,e)=>r=>{var s,i,l;let t=(s=r.text)!=null?s:"",o=(i=r.message.rawContent)!=null?i:null;if(e){let p=e.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 n!=null&&n.postprocessMessage?n.postprocessMessage({...r,text:t,raw:(l=o!=null?o:r.text)!=null?l:""}):xn(t)},zn=(n,e,r)=>{var ae,pe,ke,ue,Oe,rt,ht,Jn,Kn,Xn,Vn,Gn,Zn,Qn;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Pn(e),o=mn.getForInstance(t.plugins);t.components&&an.registerAll(t.components);let s=yo(),i=(ae=t.storageAdapter)!=null?ae:Nn(),l={},p=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")p=a;else if(a){let u=a;u.metadata&&(l=Un(u.metadata)),(pe=u.messages)!=null&&pe.length&&(t={...t,initialMessages:u.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let m=()=>l,d=a=>{var E;l=(E=a({...l}))!=null?E:{},Ht()},T=t.actionParsers&&t.actionParsers.length?t.actionParsers:[fn],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Xt.message,Xt.messageAndClick],b=wn({parsers:T,handlers:f,getMetadata:m,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let w=(ue=(ke=t.launcher)==null?void 0:ke.enabled)!=null?ue:!0,D=(rt=(Oe=t.launcher)==null?void 0:Oe.autoExpand)!=null?rt:!1,N=D,h=w,C=w?D:!0,$=xo(t,b),A=(Jn=(ht=t.features)==null?void 0:ht.showReasoning)!=null?Jn:!0,z=(Xn=(Kn=t.features)==null?void 0:Kn.showToolCalls)!=null?Xn:!0,I=(Vn=t.statusIndicator)!=null?Vn:{},V=a=>{var u,E,O,R;return a==="idle"?(u=I.idleText)!=null?u:ze.idle:a==="connecting"?(E=I.connectingText)!=null?E:ze.connecting:a==="connected"?(O=I.connectedText)!=null?O:ze.connected:a==="error"?(R=I.errorText)!=null?R:ze.error:ze[a]},{wrapper:G,panel:S}=go(t),ie=ho(t,w),{container:Y,body:U,messagesWrapper:Z,suggestions:le,textarea:oe,sendButton:P,sendButtonWrapper:_e,composerForm:Ye,statusText:Qe,introTitle:xt,introSubtitle:Ct,closeButton:j,iconHolder:me,headerTitle:mt,headerSubtitle:ft,header:Je,footer:et}=ie,M=ie.micButton,Le=ie.micButtonWrapper,it=o.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let u=Ut({config:t,showClose:w});return sn(Y,u,t),u.header},onClose:()=>st(!1,"user")});if(a){let u=Y.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(a),Je=a)}}let at=o.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>on({config:t}).footer,onSubmit:u=>{_&&!_.isStreaming()&&_.sendMessage(u)},disabled:!1});a&&(et.replaceWith(a),et=a)}(()=>{var O,R;let a=(R=(O=t.layout)==null?void 0:O.slots)!=null?R:{},u=te=>{switch(te){case"body-top":return Y.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Z;case"footer-top":return le;case"composer":return Ye;case"footer-bottom":return Qe;default:return null}},E=(te,k)=>{var v;switch(te){case"header-left":case"header-center":case"header-right":if(te==="header-left")Je.insertBefore(k,Je.firstChild);else if(te==="header-right")Je.appendChild(k);else{let F=Je.querySelector(".tvw-flex-col");F?(v=F.parentNode)==null||v.insertBefore(k,F.nextSibling):Je.appendChild(k)}break;case"body-top":let X=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");X?X.replaceWith(k):U.insertBefore(k,U.firstChild);break;case"body-bottom":U.appendChild(k);break;case"footer-top":le.replaceWith(k);break;case"footer-bottom":Qe.replaceWith(k);break;default:break}};for(let[te,k]of Object.entries(a))if(k)try{let v=k({config:t,defaultContent:()=>u(te)});v&&E(te,v)}catch(v){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${te}":`,v)}})(),S.appendChild(Y),n.appendChild(G);let wt=()=>{var se,Re,dt,re,ct,kt,Rt,Mt,jt,It,_t,pt,$t,Pt,pn,en;let a=(Re=(se=t.launcher)==null?void 0:se.sidebarMode)!=null?Re:!1,u=a||((re=(dt=t.launcher)==null?void 0:dt.fullHeight)!=null?re:!1),E=(ct=t.theme)!=null?ct:{},O=(Rt=(kt=t.launcher)==null?void 0:kt.position)!=null?Rt:"bottom-left",R=O==="bottom-left"||O==="top-left",te=a?"none":"1px solid var(--tvw-cw-border)",k=a?R?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",v=a?"0":"16px",X=(Mt=E.panelBorder)!=null?Mt:te,F=(jt=E.panelShadow)!=null?jt:k,B=(It=E.panelBorderRadius)!=null?It:v;n.style.cssText="",G.style.cssText="",S.style.cssText="",Y.style.cssText="",U.style.cssText="",et.style.cssText="";let q=(pt=(_t=t==null?void 0:t.launcher)==null?void 0:_t.width)!=null?pt:t==null?void 0:t.launcherWidth,Me=q!=null?q:"min(400px, calc(100vw - 24px))";a||(S.style.width=Me,S.style.maxWidth=Me),S.style.boxShadow=F,S.style.borderRadius=B,Y.style.border=X,Y.style.borderRadius=B;let ge=(($t=t.launcher)==null?void 0:$t.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.height="100%",ge&&(G.style.overflow="hidden"),S.style.display="flex",S.style.flexDirection="column",S.style.flex="1 1 0%",S.style.minHeight="0",S.style.maxHeight="100%",S.style.height="100%",S.style.overflow="hidden",Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",et.style.flexShrink="0"),G.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!a&&!ge&&((Pt=bt[O])!=null?Pt:bt["bottom-right"]).split(" ").forEach(Yt=>G.classList.add(Yt)),a){let qt=(en=(pn=t.launcher)==null?void 0:pn.sidebarWidth)!=null?en:"420px";G.style.cssText=`
17
17
  position: fixed !important;
18
18
  top: 0 !important;
19
19
  bottom: 0 !important;
@@ -24,7 +24,7 @@ import{marked as to}from"marked";to.setOptions({breaks:!0});var no=n=>to.parse(n
24
24
  padding: 0 !important;
25
25
  display: flex !important;
26
26
  flex-direction: column !important;
27
- ${k?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
27
+ ${R?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
28
28
  `,S.style.cssText=`
29
29
  position: relative !important;
30
30
  display: flex !important;
@@ -36,9 +36,9 @@ import{marked as to}from"marked";to.setOptions({breaks:!0});var no=n=>to.parse(n
36
36
  min-height: 0 !important;
37
37
  margin: 0 !important;
38
38
  padding: 0 !important;
39
- box-shadow: ${N} !important;
40
- border-radius: ${R} !important;
41
- `,S.style.setProperty("width","100%","important"),S.style.setProperty("max-width","100%","important"),J.style.cssText=`
39
+ box-shadow: ${F} !important;
40
+ border-radius: ${B} !important;
41
+ `,S.style.setProperty("width","100%","important"),S.style.setProperty("max-width","100%","important"),Y.style.cssText=`
42
42
  display: flex !important;
43
43
  flex-direction: column !important;
44
44
  flex: 1 1 0% !important;
@@ -47,17 +47,17 @@ import{marked as to}from"marked";to.setOptions({breaks:!0});var no=n=>to.parse(n
47
47
  min-height: 0 !important;
48
48
  max-height: 100% !important;
49
49
  overflow: hidden !important;
50
- border-radius: ${R} !important;
51
- border: ${z} !important;
50
+ border-radius: ${B} !important;
51
+ border: ${X} !important;
52
52
  `,et.style.cssText=`
53
53
  flex-shrink: 0 !important;
54
54
  border-top: none !important;
55
55
  padding: 8px 16px 12px 16px !important;
56
- `}if(!ye){let qt="max-height: -moz-available !important; max-height: stretch !important;",Yt=a?"":"padding-top: 1.25em !important;";G.style.cssText+=qt+Yt}};wt(),Wn(n,t);let ke=[],tt=fo(le),qe=null,F,lt=!1,Ke=!0,We=0,je=0,K=null,Se=!1,Le=0,Ue=!1,nt=125,St=2e3,Lt=5,gt=50,At=new Map,de={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Nt=(Zn=(Gn=t.voiceRecognition)==null?void 0:Gn.autoResume)!=null?Zn:!1,Bt=a=>{s.emit("voice:state",{active:de.active,source:a,timestamp:Date.now()})},be=()=>{d(a=>({...a,voiceState:{active:de.active,timestamp:Date.now(),manuallyDeactivated:de.manuallyDeactivated}}))},yt=()=>{var O,k;if(((O=t.voiceRecognition)==null?void 0:O.enabled)===!1)return;let a=Un(l.voiceState),u=!!a.active,E=Number((k=a.timestamp)!=null?k:0);de.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-E<Vo&&setTimeout(()=>{de.active||(de.manuallyDeactivated=!1,Ie("restore"))},1e3)},Tt=()=>F?bo(F.getMessages()).filter(a=>!a.__skipPersist):[];function Ht(a){if(!(i!=null&&i.save))return;let E={messages:a?bo(a):F?Tt():[],metadata:l};try{let O=i.save(E);O instanceof Promise&&O.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(O){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",O)}}let vt=(a=!1)=>{if(!Ke)return;let u=Date.now();Se&&u<Le&&!a||(Se&&u>=Le&&(Se=!1),!(!a&&!lt)&&(u-je<nt||(je=u,K&&cancelAnimationFrame(K),K=requestAnimationFrame(()=>{Se||!Ke||(Ue=!0,U.scrollTop=U.scrollHeight,We=U.scrollTop,requestAnimationFrame(()=>{Ue=!1}),K=null)}))))},Wt=null,ln=()=>G.querySelector("#vanilla-agent-scroll-container")||U,dn=(a,u=500)=>{let E=a.scrollTop,O=a.clientHeight,k=a.scrollHeight,te=k-E;if(E+O>=k-2||Math.abs(te)<5)return;Wt!==null&&(cancelAnimationFrame(Wt),Wt=null);let v=performance.now(),z=R=>1-Math.pow(1-R,3),N=R=>{let _=a.scrollHeight;_!==k&&(k=_,te=k-E);let $e=R-v,ye=Math.min($e/u,1),re=z(ye),Oe=E+te*re;a.scrollTop=Oe,ye<1?Wt=requestAnimationFrame(N):(a.scrollTop=a.scrollHeight,Wt=null)};Wt=requestAnimationFrame(N)},cn=a=>{let u=new Map;a.forEach(E=>{let O=At.get(E.id);u.set(E.id,{streaming:E.streaming,role:E.role}),!O&&E.role==="assistant"&&s.emit("assistant:message",E),E.role==="assistant"&&(O!=null&&O.streaming)&&E.streaming===!1&&s.emit("assistant:complete",E)}),At.clear(),u.forEach((E,O)=>{At.set(O,E)})},Dt=(a,u,E)=>{a.innerHTML="";let O=document.createDocumentFragment();u.forEach(v=>{var $e,ye;let z=null,N=o.find(re=>!!(v.variant==="reasoning"&&re.renderReasoning||v.variant==="tool"&&re.renderToolCall||!v.variant&&re.renderMessage)),R=($e=t.layout)==null?void 0:$e.messages;if(N)if(v.variant==="reasoning"&&v.reasoning&&N.renderReasoning){if(!A)return;z=N.renderReasoning({message:v,defaultRenderer:()=>Hn(v),config:t})}else if(v.variant==="tool"&&v.toolCall&&N.renderToolCall){if(!Y)return;z=N.renderToolCall({message:v,defaultRenderer:()=>Rn(v,t),config:t})}else N.renderMessage&&(z=N.renderMessage({message:v,defaultRenderer:()=>{let re=rn(v,E,R);return v.role!=="user"&&In(re,v,t,F),re},config:t}));if(!z&&v.role==="assistant"&&!v.variant&&t.enableComponentStreaming!==!1&&_n(v)){let Oe=qn(v);if(Oe){let dt=jn(Oe,{config:t,message:v,transform:E});if(dt){let oe=document.createElement("div");if(oe.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),oe.setAttribute("data-message-id",v.id),v.content&&v.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=E({text:v.content,message:v,streaming:!!v.streaming,raw:v.rawContent}),oe.appendChild(ct)}oe.appendChild(dt),z=oe}}}if(!z)if(v.variant==="reasoning"&&v.reasoning){if(!A)return;z=Hn(v)}else if(v.variant==="tool"&&v.toolCall){if(!Y)return;z=Rn(v,t)}else{let re=(ye=t.layout)==null?void 0:ye.messages;re!=null&&re.renderUserMessage&&v.role==="user"?z=re.renderUserMessage({message:v,config:t,streaming:!!v.streaming}):re!=null&&re.renderAssistantMessage&&v.role==="assistant"?z=re.renderAssistantMessage({message:v,config:t,streaming:!!v.streaming}):z=rn(v,E,re),v.role!=="user"&&z&&In(z,v,t,F)}let _=document.createElement("div");_.className="tvw-flex",v.role==="user"&&_.classList.add("tvw-justify-end"),_.appendChild(z),O.appendChild(_)});let k=u.some(v=>v.role==="assistant"&&v.streaming),te=u[u.length-1],H=(te==null?void 0:te.role)==="assistant"&&!te.streaming;if(lt&&u.some(v=>v.role==="user")&&!k&&!H){let v=hn(),z=document.createElement("div");z.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(" "),z.appendChild(v);let N=document.createElement("div");N.className="tvw-flex",N.appendChild(z),O.appendChild(N)}a.appendChild(O),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let v=ln();dn(v)})})},Ft=()=>{w&&(C?(G.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),S.classList.remove("tvw-scale-95","tvw-opacity-0"),S.classList.add("tvw-scale-100","tvw-opacity-100"),g?g.element.style.display="none":B&&(B.style.display="none")):(G.classList.add("tvw-pointer-events-none","tvw-opacity-0"),S.classList.remove("tvw-scale-100","tvw-opacity-100"),S.classList.add("tvw-scale-95","tvw-opacity-0"),g?g.element.style.display="":B&&(B.style.display="")))},st=(a,u="user")=>{if(!w||C===a)return;let E=C;C=a,Ft(),C&&(we(),vt(!0));let O={open:C,source:u,timestamp:Date.now()};C&&!E?s.emit("widget:opened",O):!C&&E&&s.emit("widget:closed",O),s.emit("widget:state",{open:C,launcherEnabled:w,voiceActive:de.active,streaming:F.isStreaming()})},zt=a=>{P.disabled=a,M&&(M.disabled=a),tt.buttons.forEach(u=>{u.disabled=a})},Gt=()=>{var k,te,H,v,z,N,R,_,$e,ye,re,Oe,dt,oe;xt.textContent=(te=(k=t.copy)==null?void 0:k.welcomeTitle)!=null?te:"Hello \u{1F44B}",Ct.textContent=(v=(H=t.copy)==null?void 0:H.welcomeSubtitle)!=null?v:"Ask anything about your account or products.",se.placeholder=(N=(z=t.copy)==null?void 0:z.inputPlaceholder)!=null?N:"How can I help...",((_=(R=t.sendButton)==null?void 0:R.useIcon)!=null?_:!1)||(P.textContent=(ye=($e=t.copy)==null?void 0:$e.sendButtonLabel)!=null?ye:"Send");let u=(Oe=(re=t.theme)==null?void 0:re.inputFontFamily)!=null?Oe:"sans-serif",E=(oe=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?oe:"400",O=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=O(u),se.style.fontWeight=E};F=new tn(t,{onMessagesChanged(a){Dt(Z,a,$),F&&(a.some(O=>O.role==="user")?tt.render([],F,se,a):tt.render(t.suggestionChips,F,se,a,t.suggestionChipsConfig)),vt(!lt),cn(a);let u=[...a].reverse().find(E=>E.role==="user");de.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Ht(a)},onStatusChanged(a){var O;let u=(O=t.statusIndicator)!=null?O:{},E=k=>{var te,H,v,z;return k==="idle"?(te=u.idleText)!=null?te:ze.idle:k==="connecting"?(H=u.connectingText)!=null?H:ze.connecting:k==="connected"?(v=u.connectedText)!=null?v:ze.connected:k==="error"?(z=u.errorText)!=null?z:ze.error:ze[k]};Qe.textContent=E(a)},onStreamingChanged(a){lt=a,zt(a),F&&Dt(Z,F.getMessages(),$),a||vt(!0)}}),p&&p.then(a=>{var u;a&&(a.metadata&&(l=Un(a.metadata),b.syncFromMetadata()),(u=a.messages)!=null&&u.length&&F.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let Zt=a=>{a.preventDefault();let u=se.value.trim();u&&(se.value="",F.sendMessage(u))},Qt=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),P.click())},y=null,X=!1,ne=null,fe=null,Re=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ie=(a="user")=>{var te,H,v,z;if(X||F.isStreaming())return;let u=Re();if(!u)return;y=new u;let O=(H=((te=t.voiceRecognition)!=null?te:{}).pauseDuration)!=null?H:2e3;y.continuous=!0,y.interimResults=!0,y.lang="en-US";let k=se.value;y.onresult=N=>{let R="",_="";for(let ye=0;ye<N.results.length;ye++){let re=N.results[ye],Oe=re[0].transcript;re.isFinal?R+=Oe+" ":_=Oe}let $e=k+R+_;se.value=$e,ne&&clearTimeout(ne),(R||_)&&(ne=window.setTimeout(()=>{let ye=se.value.trim();ye&&y&&X&&(ce(),se.value="",F.sendMessage(ye,{viaVoice:!0}))},O))},y.onerror=N=>{N.error!=="no-speech"&&ce()},y.onend=()=>{if(X){let N=se.value.trim();N&&N!==k.trim()&&(se.value="",F.sendMessage(N,{viaVoice:!0})),ce()}};try{if(y.start(),X=!0,de.active=!0,a!=="system"&&(de.manuallyDeactivated=!1),Bt(a),be(),M){fe={backgroundColor:M.style.backgroundColor,color:M.style.color,borderColor:M.style.borderColor};let N=(v=t.voiceRecognition)!=null?v:{},R=(z=N.recordingBackgroundColor)!=null?z:"#ef4444",_=N.recordingIconColor,$e=N.recordingBorderColor;if(M.classList.add("tvw-voice-recording"),M.style.backgroundColor=R,_){M.style.color=_;let ye=M.querySelector("svg");ye&&ye.setAttribute("stroke",_)}$e&&(M.style.borderColor=$e),M.setAttribute("aria-label","Stop voice recognition")}}catch{ce("system")}},ce=(a="user")=>{if(X){if(X=!1,ne&&(clearTimeout(ne),ne=null),y){try{y.stop()}catch{}y=null}if(de.active=!1,Bt(a),be(),M){if(M.classList.remove("tvw-voice-recording"),fe){M.style.backgroundColor=fe.backgroundColor,M.style.color=fe.color,M.style.borderColor=fe.borderColor;let u=M.querySelector("svg");u&&u.setAttribute("stroke",fe.color||"currentColor"),fe=null}M.setAttribute("aria-label","Start voice recognition")}}},L=(a,u)=>{var Oe,dt,oe,ct,kt,Rt,Mt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let O=c("div","tvw-send-button-wrapper"),k=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");k.type="button",k.setAttribute("aria-label","Start voice recognition");let te=(Oe=a==null?void 0:a.iconName)!=null?Oe:"mic",H=(dt=u==null?void 0:u.size)!=null?dt:"40px",v=(oe=a==null?void 0:a.iconSize)!=null?oe:H,z=parseFloat(v)||24,N=(ct=a==null?void 0:a.backgroundColor)!=null?ct:u==null?void 0:u.backgroundColor,R=(kt=a==null?void 0:a.iconColor)!=null?kt:u==null?void 0:u.textColor;k.style.width=v,k.style.height=v,k.style.minWidth=v,k.style.minHeight=v,k.style.fontSize="18px",k.style.lineHeight="1";let _=R||"currentColor",$e=ve(te,z,_,1.5);$e?(k.appendChild($e),k.style.color=_):(k.textContent="\u{1F3A4}",k.style.color=_),N?k.style.backgroundColor=N:k.classList.add("tvw-bg-cw-primary"),R?k.style.color=R:!R&&!(u!=null&&u.textColor)&&k.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(k.style.borderWidth=a.borderWidth,k.style.borderStyle="solid"),a!=null&&a.borderColor&&(k.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(k.style.paddingLeft=a.paddingX,k.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(k.style.paddingTop=a.paddingY,k.style.paddingBottom=a.paddingY),O.appendChild(k);let ye=(Rt=a==null?void 0:a.tooltipText)!=null?Rt:"Start voice recognition";if(((Mt=a==null?void 0:a.showTooltip)!=null?Mt:!1)&&ye){let jt=c("div","tvw-send-button-tooltip");jt.textContent=ye,O.appendChild(jt)}return{micButton:k,micButtonWrapper:O}},ot=()=>{if(X){let a=se.value.trim();de.manuallyDeactivated=!0,be(),ce("user"),a&&(se.value="",F.sendMessage(a))}else de.manuallyDeactivated=!1,be(),Ie("user")};M&&(M.addEventListener("click",ot),ke.push(()=>{ce("system"),M&&M.removeEventListener("click",ot)}));let Q=s.on("assistant:complete",()=>{Nt&&(de.active||de.manuallyDeactivated||Nt==="assistant"&&!de.lastUserMessageWasVoice||setTimeout(()=>{!de.active&&!de.manuallyDeactivated&&Ie("auto")},600))});ke.push(Q);let x=()=>{st(!C,"user")},g=null,B=null;if(w){let a=o.find(u=>u.renderLauncher);if(a!=null&&a.renderLauncher){let u=a.renderLauncher({config:t,defaultRenderer:()=>nn(t,x).element,onToggle:x});u&&(B=u)}B||(g=nn(t,x))}g?n.appendChild(g.element):B&&n.appendChild(B),Ft(),tt.render(t.suggestionChips,F,se,void 0,t.suggestionChipsConfig),Gt(),zt(F.isStreaming()),vt(!0),yt();let we=()=>{var E,O,k,te,H,v;let a=(O=(E=t.launcher)==null?void 0:E.sidebarMode)!=null?O:!1,u=a||((te=(k=t.launcher)==null?void 0:k.fullHeight)!=null?te:!1);if(!w){S.style.height="",S.style.width="";return}if(!a){let z=(v=(H=t==null?void 0:t.launcher)==null?void 0:H.width)!=null?v:t==null?void 0:t.launcherWidth,N=z!=null?z:"min(400px, calc(100vw - 24px))";S.style.width=N,S.style.maxWidth=N}if(!u){let z=window.innerHeight,R=Math.max(200,z-64),_=Math.min(640,R);S.style.height=`${_}px`}};we(),window.addEventListener("resize",we),ke.push(()=>window.removeEventListener("resize",we)),We=U.scrollTop;let Ae=()=>{let a=U.scrollTop,u=U.scrollHeight,E=U.clientHeight,O=u-a-E,k=Math.abs(a-We);if(We=a,!Ue&&!(k<=Lt)){if(!Ke&&O<gt){Se=!1,Ke=!0;return}Ke&&O>gt&&(Se=!0,Le=Date.now()+St,Ke=!1)}};U.addEventListener("scroll",Ae,{passive:!0}),ke.push(()=>U.removeEventListener("scroll",Ae)),ke.push(()=>{K&&cancelAnimationFrame(K)});let Xe=()=>{D&&(qe&&(D.removeEventListener("click",qe),qe=null),w?(D.style.display="",qe=()=>{C=!1,Ft()},D.addEventListener("click",qe)):D.style.display="none")};Xe(),(()=>{let{clearChatButton:a}=ie;a&&a.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(Vt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vt}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Vt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let u=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let E=i.clear();E instanceof Promise&&E.catch(O=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",O)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},b.syncFromMetadata()})})(),Ye.addEventListener("submit",Zt),se.addEventListener("keydown",Qt),ke.push(()=>{Ye.removeEventListener("submit",Zt),se.removeEventListener("keydown",Qt)}),ke.push(()=>{F.cancel()}),g?ke.push(()=>{g==null||g.destroy()}):B&&ke.push(()=>{B==null||B.remove()});let xe={update(a){var en,qt,Yt,es,ts,ns,ss,os,rs,is,as,ls,ds,cs,ps,us,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,Hs,ks,Rs,Is,$s,Ps,Os,Ns,Ds,Fs,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs,Qs;let u=t.toolCall;t={...t,...a},wt(),Wn(n,t);let E=mn.getForInstance(t.plugins);if(o.length=0,o.push(...E),w=(qt=(en=t.launcher)==null?void 0:en.enabled)!=null?qt:!0,q=(es=(Yt=t.launcher)==null?void 0:Yt.autoExpand)!=null?es:!1,A=(ns=(ts=t.features)==null?void 0:ts.showReasoning)!=null?ns:!0,Y=(os=(ss=t.features)==null?void 0:ss.showToolCalls)!=null?os:!0,((rs=t.launcher)==null?void 0:rs.enabled)===!1&&g&&(g.destroy(),g=null),((is=t.launcher)==null?void 0:is.enabled)===!1&&B&&(B.remove(),B=null),((as=t.launcher)==null?void 0:as.enabled)!==!1&&!g&&!B){let W=o.find(me=>me.renderLauncher);if(W!=null&&W.renderLauncher){let me=W.renderLauncher({config:t,defaultRenderer:()=>nn(t,x).element,onToggle:x});me&&(B=me,n.appendChild(B))}B||(g=nn(t,x),n.appendChild(g.element))}g&&g.update(t),mt&&((ls=t.launcher)==null?void 0:ls.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((ds=t.launcher)==null?void 0:ds.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),w!==m?w?st(q,"auto"):(C=!0,Ft()):q!==j&&st(q,"auto"),j=q,m=w,we(),Xe(),JSON.stringify(a.toolCall)!==JSON.stringify(u)&&F&&Dt(Z,F.getMessages(),$);let H=(cs=t.launcher)!=null?cs:{},v=(ps=H.headerIconHidden)!=null?ps:!1,z=H.headerIconName,N=(us=H.headerIconSize)!=null?us:"48px";if(he){let W=J.querySelector(".tvw-border-b-cw-divider"),me=W==null?void 0:W.querySelector(".tvw-flex-col");if(v)he.style.display="none",W&&me&&!W.contains(me)&&W.insertBefore(me,W.firstChild);else{if(he.style.display="",he.style.height=N,he.style.width=N,W&&me&&(W.contains(he)?he.nextSibling!==me&&(he.remove(),W.insertBefore(he,me)):W.insertBefore(he,me)),z){let Ee=parseFloat(N)||24,Ce=ve(z,Ee*.6,"#ffffff",2);Ce?he.replaceChildren(Ce):he.textContent=(gs=H.agentIconText)!=null?gs:"\u{1F4AC}"}else if(H.iconUrl){let Ee=he.querySelector("img");if(Ee)Ee.src=H.iconUrl,Ee.style.height=N,Ee.style.width=N;else{let Ce=document.createElement("img");Ce.src=H.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=N,Ce.style.width=N,he.replaceChildren(Ce)}}else{let Ee=he.querySelector("svg"),Ce=he.querySelector("img");(Ee||Ce)&&he.replaceChildren(),he.textContent=(hs=H.agentIconText)!=null?hs:"\u{1F4AC}"}let ee=he.querySelector("img");ee&&(ee.style.height=N,ee.style.width=N)}}if(D){let W=(ms=H.closeButtonSize)!=null?ms:"32px",me=(fs=H.closeButtonPlacement)!=null?fs:"inline";D.style.height=W,D.style.width=W;let{closeButtonWrapper:ee}=ie,Ee=me==="top-right",Ce=ee==null?void 0:ee.classList.contains("tvw-absolute");if(ee&&Ee!==Ce)if(ee.remove(),Ee)ee.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",J.style.position="relative",J.appendChild(ee);else{let ge=(ys=(ws=H.clearChat)==null?void 0:ws.placement)!=null?ys:"inline",Ge=(bs=(vs=H.clearChat)==null?void 0:vs.enabled)!=null?bs:!0;ee.className=Ge&&ge==="inline"?"":"tvw-ml-auto";let Ze=J.querySelector(".tvw-border-b-cw-divider");Ze&&Ze.appendChild(ee)}if(H.closeButtonColor?(D.style.color=H.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),H.closeButtonBackgroundColor?(D.style.backgroundColor=H.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),H.closeButtonBorderWidth||H.closeButtonBorderColor){let ge=H.closeButtonBorderWidth||"0px",Ge=H.closeButtonBorderColor||"transparent";D.style.border=`${ge} solid ${Ge}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");H.closeButtonBorderRadius?(D.style.borderRadius=H.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),H.closeButtonPaddingX?(D.style.paddingLeft=H.closeButtonPaddingX,D.style.paddingRight=H.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),H.closeButtonPaddingY?(D.style.paddingTop=H.closeButtonPaddingY,D.style.paddingBottom=H.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Ve=(xs=H.closeButtonIconName)!=null?xs:"x",Fe=(Cs=H.closeButtonIconText)!=null?Cs:"\xD7";D.innerHTML="";let ut=ve(Ve,"20px",H.closeButtonColor||"",2);ut?D.appendChild(ut):D.textContent=Fe;let Ot=(Ss=H.closeButtonTooltipText)!=null?Ss:"Close chat",Te=(As=H.closeButtonShowTooltip)!=null?As:!0;if(D.setAttribute("aria-label",Ot),ee&&(ee._cleanupTooltip&&(ee._cleanupTooltip(),delete ee._cleanupTooltip),Te&&Ot)){let ge=null,Ge=()=>{if(ge||!D)return;ge=c("div","tvw-clear-chat-tooltip"),ge.textContent=Ot;let Jt=c("div");Jt.className="tvw-clear-chat-tooltip-arrow",ge.appendChild(Jt);let bn=D.getBoundingClientRect();ge.style.position="fixed",ge.style.left=`${bn.left+bn.width/2}px`,ge.style.top=`${bn.top-8}px`,ge.style.transform="translate(-50%, -100%)",document.body.appendChild(ge)},Ze=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};ee.addEventListener("mouseenter",Ge),ee.addEventListener("mouseleave",Ze),D.addEventListener("focus",Ge),D.addEventListener("blur",Ze),ee._cleanupTooltip=()=>{Ze(),ee&&(ee.removeEventListener("mouseenter",Ge),ee.removeEventListener("mouseleave",Ze)),D&&(D.removeEventListener("focus",Ge),D.removeEventListener("blur",Ze))}}}let{clearChatButton:R,clearChatButtonWrapper:_}=ie;if(R){let W=(Ts=H.clearChat)!=null?Ts:{},me=(Es=W.enabled)!=null?Es:!0,ee=(Ws=W.placement)!=null?Ws:"inline";if(_){_.style.display=me?"":"none";let Ee=ee==="top-right",Ce=_.classList.contains("tvw-absolute");if(Ee!==Ce&&me){if(_.remove(),Ee)_.className="tvw-absolute tvw-top-4 tvw-z-50",_.style.right="48px",J.style.position="relative",J.appendChild(_);else{_.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",_.style.right="";let Fe=J.querySelector(".tvw-border-b-cw-divider"),ut=ie.closeButtonWrapper;Fe&&ut&&ut.parentElement===Fe?Fe.insertBefore(_,ut):Fe&&Fe.appendChild(_)}let Ve=ie.closeButtonWrapper;Ve&&!Ve.classList.contains("tvw-absolute")&&(Ee?Ve.classList.add("tvw-ml-auto"):Ve.classList.remove("tvw-ml-auto"))}}if(me){let Ee=(Ms=W.size)!=null?Ms:"32px";R.style.height=Ee,R.style.width=Ee;let Ce=(Ls=W.iconName)!=null?Ls:"refresh-cw",Ve=(Bs=W.iconColor)!=null?Bs:"";R.innerHTML="";let Fe=ve(Ce,"20px",Ve||"",2);if(Fe&&R.appendChild(Fe),Ve?(R.style.color=Ve,R.classList.remove("tvw-text-cw-muted")):(R.style.color="",R.classList.add("tvw-text-cw-muted")),W.backgroundColor?(R.style.backgroundColor=W.backgroundColor,R.classList.remove("hover:tvw-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let Te=W.borderWidth||"0px",ge=W.borderColor||"transparent";R.style.border=`${Te} solid ${ge}`,R.classList.remove("tvw-border-none")}else R.style.border="",R.classList.add("tvw-border-none");W.borderRadius?(R.style.borderRadius=W.borderRadius,R.classList.remove("tvw-rounded-full")):(R.style.borderRadius="",R.classList.add("tvw-rounded-full")),W.paddingX?(R.style.paddingLeft=W.paddingX,R.style.paddingRight=W.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),W.paddingY?(R.style.paddingTop=W.paddingY,R.style.paddingBottom=W.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let ut=(Hs=W.tooltipText)!=null?Hs:"Clear chat",Ot=(ks=W.showTooltip)!=null?ks:!0;if(R.setAttribute("aria-label",ut),_&&(_._cleanupTooltip&&(_._cleanupTooltip(),delete _._cleanupTooltip),Ot&&ut)){let Te=null,ge=()=>{if(Te||!R)return;Te=c("div","tvw-clear-chat-tooltip"),Te.textContent=ut;let Ze=c("div");Ze.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(Ze);let Jt=R.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${Jt.left+Jt.width/2}px`,Te.style.top=`${Jt.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},Ge=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};_.addEventListener("mouseenter",ge),_.addEventListener("mouseleave",Ge),R.addEventListener("focus",ge),R.addEventListener("blur",Ge),_._cleanupTooltip=()=>{Ge(),_&&(_.removeEventListener("mouseenter",ge),_.removeEventListener("mouseleave",Ge)),R&&(R.removeEventListener("focus",ge),R.removeEventListener("blur",Ge))}}}}let $e=t.actionParsers&&t.actionParsers.length?t.actionParsers:[fn],ye=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Xt.message,Xt.messageAndClick];b=wn({parsers:$e,handlers:ye,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),$=xo(t,b),F.updateConfig(t),Dt(Z,F.getMessages(),$),tt.render(t.suggestionChips,F,se,void 0,t.suggestionChipsConfig),Gt(),zt(F.isStreaming());let re=((Rs=t.voiceRecognition)==null?void 0:Rs.enabled)===!0,Oe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=re&&Oe;if(Ye.classList.remove("tvw-gap-1","tvw-gap-3"),Ye.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),re&&Oe)if(!M||!Me){let W=L(t.voiceRecognition,t.sendButton);W&&(M=W.micButton,Me=W.micButtonWrapper,Ye.insertBefore(Me,_e),M.addEventListener("click",ot),M.disabled=F.isStreaming())}else{let W=(Is=t.voiceRecognition)!=null?Is:{},me=($s=t.sendButton)!=null?$s:{},ee=(Ps=W.iconName)!=null?Ps:"mic",Ee=(Os=me.size)!=null?Os:"40px",Ce=(Ns=W.iconSize)!=null?Ns:Ee,Ve=parseFloat(Ce)||24;M.style.width=Ce,M.style.height=Ce,M.style.minWidth=Ce,M.style.minHeight=Ce;let Fe=(Fs=(Ds=W.iconColor)!=null?Ds:me.textColor)!=null?Fs:"currentColor";M.innerHTML="";let ut=ve(ee,Ve,Fe,2);ut?M.appendChild(ut):M.textContent="\u{1F3A4}";let Ot=(js=W.backgroundColor)!=null?js:me.backgroundColor;Ot?(M.style.backgroundColor=Ot,M.classList.remove("tvw-bg-cw-primary")):(M.style.backgroundColor="",M.classList.add("tvw-bg-cw-primary")),Fe?(M.style.color=Fe,M.classList.remove("tvw-text-white")):!Fe&&!me.textColor&&(M.style.color="",M.classList.add("tvw-text-white")),W.borderWidth?(M.style.borderWidth=W.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),W.borderColor?M.style.borderColor=W.borderColor:M.style.borderColor="",W.paddingX?(M.style.paddingLeft=W.paddingX,M.style.paddingRight=W.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),W.paddingY?(M.style.paddingTop=W.paddingY,M.style.paddingBottom=W.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Te=Me==null?void 0:Me.querySelector(".tvw-send-button-tooltip"),ge=(_s=W.tooltipText)!=null?_s:"Start voice recognition";if(((qs=W.showTooltip)!=null?qs:!1)&&ge)if(Te)Te.textContent=ge,Te.style.display="";else{let Ze=document.createElement("div");Ze.className="tvw-send-button-tooltip",Ze.textContent=ge,Me==null||Me.insertBefore(Ze,M)}else Te&&(Te.style.display="none");Me.style.display="",M.disabled=F.isStreaming()}else M&&Me&&(Me.style.display="none",X&&ce());let oe=(Us=t.sendButton)!=null?Us:{},ct=(zs=oe.useIcon)!=null?zs:!1,kt=(Ys=oe.iconText)!=null?Ys:"\u2191",Rt=oe.iconName,Mt=(Js=oe.tooltipText)!=null?Js:"Send message",jt=(Ks=oe.showTooltip)!=null?Ks:!1,It=(Xs=oe.size)!=null?Xs:"40px",_t=oe.backgroundColor,pt=oe.textColor;if(ct){if(P.style.width=It,P.style.height=It,P.style.minWidth=It,P.style.minHeight=It,P.style.fontSize="18px",P.style.lineHeight="1",P.innerHTML="",Rt){let W=parseFloat(It)||24,me=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",ee=ve(Rt,W,me,2);ee?(P.appendChild(ee),P.style.color=me):(P.textContent=kt,pt?P.style.color=pt:P.classList.add("tvw-text-white"))}else P.textContent=kt,pt?P.style.color=pt:P.classList.add("tvw-text-white");P.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",_t?(P.style.backgroundColor=_t,P.classList.remove("tvw-bg-cw-primary")):P.classList.add("tvw-bg-cw-primary")}else P.textContent=(Gs=(Vs=t.copy)==null?void 0:Vs.sendButtonLabel)!=null?Gs:"Send",P.style.width="",P.style.height="",P.style.minWidth="",P.style.minHeight="",P.style.fontSize="",P.style.lineHeight="",P.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",_t?(P.style.backgroundColor=_t,P.classList.remove("tvw-bg-cw-accent")):P.classList.add("tvw-bg-cw-accent"),pt?P.style.color=pt:P.classList.add("tvw-text-white");oe.borderWidth?(P.style.borderWidth=oe.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),oe.borderColor?P.style.borderColor=oe.borderColor:P.style.borderColor="",oe.paddingX?(P.style.paddingLeft=oe.paddingX,P.style.paddingRight=oe.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),oe.paddingY?(P.style.paddingTop=oe.paddingY,P.style.paddingBottom=oe.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let $t=_e==null?void 0:_e.querySelector(".tvw-send-button-tooltip");if(jt&&Mt)if($t)$t.textContent=Mt,$t.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=Mt,_e==null||_e.insertBefore(W,P)}else $t&&($t.style.display="none");let Pt=(Zs=t.statusIndicator)!=null?Zs:{},pn=(Qs=Pt.visible)!=null?Qs:!0;if(Qe.style.display=pn?"":"none",F){let W=F.getStatus(),me=ee=>{var Ee,Ce,Ve,Fe;return ee==="idle"?(Ee=Pt.idleText)!=null?Ee:ze.idle:ee==="connecting"?(Ce=Pt.connectingText)!=null?Ce:ze.connecting:ee==="connected"?(Ve=Pt.connectedText)!=null?Ve:ze.connected:ee==="error"?(Fe=Pt.errorText)!=null?Fe:ze.error:ze[ee]};Qe.textContent=me(W)}},open(){w&&st(!0,"api")},close(){w&&st(!1,"api")},toggle(){w&&st(!C,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(Vt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vt}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Vt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}l={},b.syncFromMetadata()},setMessage(a){return!se||F.isStreaming()?!1:(!C&&w&&st(!0,"system"),se.value=a,se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(F.isStreaming())return!1;let u=(a==null?void 0:a.trim())||se.value.trim();return u?(!C&&w&&st(!0,"system"),se.value="",F.sendMessage(u),!0):!1},startVoiceRecognition(){return X||F.isStreaming()||!Re()?!1:(!C&&w&&st(!0,"system"),de.manuallyDeactivated=!1,be(),Ie("user"),!0)},stopVoiceRecognition(){return X?(de.manuallyDeactivated=!0,be(),ce("user"),!0):!1},injectTestMessage(a){!C&&w&&st(!0,"system"),F.injectTestEvent(a)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,u){return s.on(a,u)},off(a,u){s.off(a,u)},isOpen(){return w&&C},isVoiceActive(){return de.active},getState(){return{open:w&&C,launcherEnabled:w,voiceActive:de.active,streaming:F.isStreaming()}},destroy(){ke.forEach(a=>a()),G.remove(),g==null||g.destroy(),B==null||B.remove(),qe&&D.removeEventListener("click",qe)}};if((((Qn=r==null?void 0:r.debugTools)!=null?Qn:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,u={controller:xe,getMessages:xe.getMessages,getStatus:xe.getStatus,getMetadata:xe.getPersistentMetadata,updateMetadata:xe.updatePersistentMetadata,clearHistory:()=>xe.clearChat(),setVoiceActive:E=>E?xe.startVoiceRecognition():xe.stopVoiceRecognition()};window.AgentWidgetBrowser=u,ke.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}return xe};var Yn={},Go=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},Zo=()=>{try{if(typeof Yn!="undefined"&&Yn.url)return new URL("../widget.css",Yn.url).href}catch{}return null},Co=n=>{let e=Zo(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let o=t.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},So=n=>{var h,d,T,f;let e=Go(n.target),r=document.createElement("div");r.className="vanilla-agent-host";let t=(T=(d=(h=n.config)==null?void 0:h.launcher)==null?void 0:d.enabled)!=null?T:!0;t||(r.style.height="100%",r.style.display="flex",r.style.flexDirection="column"),e.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let b=r.attachShadow({mode:"open"});i=b,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),b.appendChild(s),Co(b)}else i=r,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),Co(r);let l=zn(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let p={...l,host:r,destroy(){l.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=p),p};function Qo(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function yn(n){var e,r;return(r=(e=n.parserType)!=null?e:Qo(n.streamParser))!=null?r:"plain"}function er(n,e="esm"){let r={...n};return delete r.postprocessMessage,delete r.initialMessages,e==="esm"?tr(r):e==="script-installer"?or(r):e==="script-advanced"?ir(r):e==="react-component"?nr(r):e==="react-advanced"?sr(r):rr(r)}function tr(n){let e=yn(n),r=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
56
+ `}if(!ge){let qt="max-height: -moz-available !important; max-height: stretch !important;",Yt=a?"":"padding-top: 1.25em !important;";G.style.cssText+=qt+Yt}};wt(),Wn(n,t);let Ie=[],tt=fo(le),qe=null,_,lt=!1,Ke=!0,We=0,je=0,J=null,Se=!1,Be=0,Ue=!1,nt=125,St=2e3,Lt=5,gt=50,At=new Map,de={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Nt=(Zn=(Gn=t.voiceRecognition)==null?void 0:Gn.autoResume)!=null?Zn:!1,Bt=a=>{s.emit("voice:state",{active:de.active,source:a,timestamp:Date.now()})},be=()=>{d(a=>({...a,voiceState:{active:de.active,timestamp:Date.now(),manuallyDeactivated:de.manuallyDeactivated}}))},yt=()=>{var O,R;if(((O=t.voiceRecognition)==null?void 0:O.enabled)===!1)return;let a=Un(l.voiceState),u=!!a.active,E=Number((R=a.timestamp)!=null?R:0);de.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-E<Vo&&setTimeout(()=>{de.active||(de.manuallyDeactivated=!1,Pe("restore"))},1e3)},Tt=()=>_?bo(_.getMessages()).filter(a=>!a.__skipPersist):[];function Ht(a){if(!(i!=null&&i.save))return;let E={messages:a?bo(a):_?Tt():[],metadata:l};try{let O=i.save(E);O instanceof Promise&&O.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(O){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",O)}}let vt=(a=!1)=>{if(!Ke)return;let u=Date.now();Se&&u<Be&&!a||(Se&&u>=Be&&(Se=!1),!(!a&&!lt)&&(u-je<nt||(je=u,J&&cancelAnimationFrame(J),J=requestAnimationFrame(()=>{Se||!Ke||(Ue=!0,U.scrollTop=U.scrollHeight,We=U.scrollTop,requestAnimationFrame(()=>{Ue=!1}),J=null)}))))},Wt=null,ln=()=>G.querySelector("#vanilla-agent-scroll-container")||U,dn=(a,u=500)=>{let E=a.scrollTop,O=a.clientHeight,R=a.scrollHeight,te=R-E;if(E+O>=R-2||Math.abs(te)<5)return;Wt!==null&&(cancelAnimationFrame(Wt),Wt=null);let v=performance.now(),X=B=>1-Math.pow(1-B,3),F=B=>{let q=a.scrollHeight;q!==R&&(R=q,te=R-E);let Me=B-v,ge=Math.min(Me/u,1),se=X(ge),Re=E+te*se;a.scrollTop=Re,ge<1?Wt=requestAnimationFrame(F):(a.scrollTop=a.scrollHeight,Wt=null)};Wt=requestAnimationFrame(F)},cn=a=>{let u=new Map;a.forEach(E=>{let O=At.get(E.id);u.set(E.id,{streaming:E.streaming,role:E.role}),!O&&E.role==="assistant"&&s.emit("assistant:message",E),E.role==="assistant"&&(O!=null&&O.streaming)&&E.streaming===!1&&s.emit("assistant:complete",E)}),At.clear(),u.forEach((E,O)=>{At.set(O,E)})},Ft=(a,u,E)=>{a.innerHTML="";let O=document.createDocumentFragment();u.forEach(v=>{var Me,ge;let X=null,F=o.find(se=>!!(v.variant==="reasoning"&&se.renderReasoning||v.variant==="tool"&&se.renderToolCall||!v.variant&&se.renderMessage)),B=(Me=t.layout)==null?void 0:Me.messages;if(F)if(v.variant==="reasoning"&&v.reasoning&&F.renderReasoning){if(!A)return;X=F.renderReasoning({message:v,defaultRenderer:()=>Hn(v),config:t})}else if(v.variant==="tool"&&v.toolCall&&F.renderToolCall){if(!z)return;X=F.renderToolCall({message:v,defaultRenderer:()=>Rn(v,t),config:t})}else F.renderMessage&&(X=F.renderMessage({message:v,defaultRenderer:()=>{let se=rn(v,E,B);return v.role!=="user"&&In(se,v,t,_),se},config:t}));if(!X&&v.role==="assistant"&&!v.variant&&t.enableComponentStreaming!==!1&&_n(v)){let Re=qn(v);if(Re){let dt=jn(Re,{config:t,message:v,transform:E});if(dt){let re=document.createElement("div");if(re.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(" "),re.setAttribute("data-message-id",v.id),v.content&&v.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=E({text:v.content,message:v,streaming:!!v.streaming,raw:v.rawContent}),re.appendChild(ct)}re.appendChild(dt),X=re}}}if(!X)if(v.variant==="reasoning"&&v.reasoning){if(!A)return;X=Hn(v)}else if(v.variant==="tool"&&v.toolCall){if(!z)return;X=Rn(v,t)}else{let se=(ge=t.layout)==null?void 0:ge.messages;se!=null&&se.renderUserMessage&&v.role==="user"?X=se.renderUserMessage({message:v,config:t,streaming:!!v.streaming}):se!=null&&se.renderAssistantMessage&&v.role==="assistant"?X=se.renderAssistantMessage({message:v,config:t,streaming:!!v.streaming}):X=rn(v,E,se),v.role!=="user"&&X&&In(X,v,t,_)}let q=document.createElement("div");q.className="tvw-flex",v.role==="user"&&q.classList.add("tvw-justify-end"),q.appendChild(X),O.appendChild(q)});let R=u.some(v=>v.role==="assistant"&&v.streaming),te=u[u.length-1],k=(te==null?void 0:te.role)==="assistant"&&!te.streaming;if(lt&&u.some(v=>v.role==="user")&&!R&&!k){let v=hn(),X=document.createElement("div");X.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(" "),X.appendChild(v);let F=document.createElement("div");F.className="tvw-flex",F.appendChild(X),O.appendChild(F)}a.appendChild(O),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let v=ln();dn(v)})})},Dt=()=>{w&&(C?(G.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),S.classList.remove("tvw-scale-95","tvw-opacity-0"),S.classList.add("tvw-scale-100","tvw-opacity-100"),g?g.element.style.display="none":H&&(H.style.display="none")):(G.classList.add("tvw-pointer-events-none","tvw-opacity-0"),S.classList.remove("tvw-scale-100","tvw-opacity-100"),S.classList.add("tvw-scale-95","tvw-opacity-0"),g?g.element.style.display="":H&&(H.style.display="")))},st=(a,u="user")=>{if(!w||C===a)return;let E=C;C=a,Dt(),C&&(ye(),vt(!0));let O={open:C,source:u,timestamp:Date.now()};C&&!E?s.emit("widget:opened",O):!C&&E&&s.emit("widget:closed",O),s.emit("widget:state",{open:C,launcherEnabled:w,voiceActive:de.active,streaming:_.isStreaming()})},zt=a=>{P.disabled=a,M&&(M.disabled=a),tt.buttons.forEach(u=>{u.disabled=a})},Gt=()=>{var R,te,k,v,X,F,B,q,Me,ge,se,Re,dt,re;xt.textContent=(te=(R=t.copy)==null?void 0:R.welcomeTitle)!=null?te:"Hello \u{1F44B}",Ct.textContent=(v=(k=t.copy)==null?void 0:k.welcomeSubtitle)!=null?v:"Ask anything about your account or products.",oe.placeholder=(F=(X=t.copy)==null?void 0:X.inputPlaceholder)!=null?F:"How can I help...",((q=(B=t.sendButton)==null?void 0:B.useIcon)!=null?q:!1)||(P.textContent=(ge=(Me=t.copy)==null?void 0:Me.sendButtonLabel)!=null?ge:"Send");let u=(Re=(se=t.theme)==null?void 0:se.inputFontFamily)!=null?Re:"sans-serif",E=(re=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?re:"400",O=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};oe.style.fontFamily=O(u),oe.style.fontWeight=E};_=new tn(t,{onMessagesChanged(a){Ft(Z,a,$),_&&(a.some(O=>O.role==="user")?tt.render([],_,oe,a):tt.render(t.suggestionChips,_,oe,a,t.suggestionChipsConfig)),vt(!lt),cn(a);let u=[...a].reverse().find(E=>E.role==="user");de.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Ht(a)},onStatusChanged(a){var O;let u=(O=t.statusIndicator)!=null?O:{},E=R=>{var te,k,v,X;return R==="idle"?(te=u.idleText)!=null?te:ze.idle:R==="connecting"?(k=u.connectingText)!=null?k:ze.connecting:R==="connected"?(v=u.connectedText)!=null?v:ze.connected:R==="error"?(X=u.errorText)!=null?X:ze.error:ze[R]};Qe.textContent=E(a)},onStreamingChanged(a){lt=a,zt(a),_&&Ft(Z,_.getMessages(),$),a||vt(!0)}}),p&&p.then(a=>{var u;a&&(a.metadata&&(l=Un(a.metadata),b.syncFromMetadata()),(u=a.messages)!=null&&u.length&&_.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let Zt=a=>{a.preventDefault();let u=oe.value.trim();u&&(oe.value="",_.sendMessage(u))},Qt=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),P.click())},y=null,K=!1,ne=null,we=null,$e=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Pe=(a="user")=>{var te,k,v,X;if(K||_.isStreaming())return;let u=$e();if(!u)return;y=new u;let O=(k=((te=t.voiceRecognition)!=null?te:{}).pauseDuration)!=null?k:2e3;y.continuous=!0,y.interimResults=!0,y.lang="en-US";let R=oe.value;y.onresult=F=>{let B="",q="";for(let ge=0;ge<F.results.length;ge++){let se=F.results[ge],Re=se[0].transcript;se.isFinal?B+=Re+" ":q=Re}let Me=R+B+q;oe.value=Me,ne&&clearTimeout(ne),(B||q)&&(ne=window.setTimeout(()=>{let ge=oe.value.trim();ge&&y&&K&&(ce(),oe.value="",_.sendMessage(ge,{viaVoice:!0}))},O))},y.onerror=F=>{F.error!=="no-speech"&&ce()},y.onend=()=>{if(K){let F=oe.value.trim();F&&F!==R.trim()&&(oe.value="",_.sendMessage(F,{viaVoice:!0})),ce()}};try{if(y.start(),K=!0,de.active=!0,a!=="system"&&(de.manuallyDeactivated=!1),Bt(a),be(),M){we={backgroundColor:M.style.backgroundColor,color:M.style.color,borderColor:M.style.borderColor};let F=(v=t.voiceRecognition)!=null?v:{},B=(X=F.recordingBackgroundColor)!=null?X:"#ef4444",q=F.recordingIconColor,Me=F.recordingBorderColor;if(M.classList.add("tvw-voice-recording"),M.style.backgroundColor=B,q){M.style.color=q;let ge=M.querySelector("svg");ge&&ge.setAttribute("stroke",q)}Me&&(M.style.borderColor=Me),M.setAttribute("aria-label","Stop voice recognition")}}catch{ce("system")}},ce=(a="user")=>{if(K){if(K=!1,ne&&(clearTimeout(ne),ne=null),y){try{y.stop()}catch{}y=null}if(de.active=!1,Bt(a),be(),M){if(M.classList.remove("tvw-voice-recording"),we){M.style.backgroundColor=we.backgroundColor,M.style.color=we.color,M.style.borderColor=we.borderColor;let u=M.querySelector("svg");u&&u.setAttribute("stroke",we.color||"currentColor"),we=null}M.setAttribute("aria-label","Start voice recognition")}}},L=(a,u)=>{var Re,dt,re,ct,kt,Rt,Mt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let O=c("div","tvw-send-button-wrapper"),R=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");R.type="button",R.setAttribute("aria-label","Start voice recognition");let te=(Re=a==null?void 0:a.iconName)!=null?Re:"mic",k=(dt=u==null?void 0:u.size)!=null?dt:"40px",v=(re=a==null?void 0:a.iconSize)!=null?re:k,X=parseFloat(v)||24,F=(ct=a==null?void 0:a.backgroundColor)!=null?ct:u==null?void 0:u.backgroundColor,B=(kt=a==null?void 0:a.iconColor)!=null?kt:u==null?void 0:u.textColor;R.style.width=v,R.style.height=v,R.style.minWidth=v,R.style.minHeight=v,R.style.fontSize="18px",R.style.lineHeight="1";let q=B||"currentColor",Me=ve(te,X,q,1.5);Me?(R.appendChild(Me),R.style.color=q):(R.textContent="\u{1F3A4}",R.style.color=q),F?R.style.backgroundColor=F:R.classList.add("tvw-bg-cw-primary"),B?R.style.color=B:!B&&!(u!=null&&u.textColor)&&R.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(R.style.borderWidth=a.borderWidth,R.style.borderStyle="solid"),a!=null&&a.borderColor&&(R.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(R.style.paddingLeft=a.paddingX,R.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(R.style.paddingTop=a.paddingY,R.style.paddingBottom=a.paddingY),O.appendChild(R);let ge=(Rt=a==null?void 0:a.tooltipText)!=null?Rt:"Start voice recognition";if(((Mt=a==null?void 0:a.showTooltip)!=null?Mt:!1)&&ge){let jt=c("div","tvw-send-button-tooltip");jt.textContent=ge,O.appendChild(jt)}return{micButton:R,micButtonWrapper:O}},ot=()=>{if(K){let a=oe.value.trim();de.manuallyDeactivated=!0,be(),ce("user"),a&&(oe.value="",_.sendMessage(a))}else de.manuallyDeactivated=!1,be(),Pe("user")};M&&(M.addEventListener("click",ot),Ie.push(()=>{ce("system"),M&&M.removeEventListener("click",ot)}));let Q=s.on("assistant:complete",()=>{Nt&&(de.active||de.manuallyDeactivated||Nt==="assistant"&&!de.lastUserMessageWasVoice||setTimeout(()=>{!de.active&&!de.manuallyDeactivated&&Pe("auto")},600))});Ie.push(Q);let x=()=>{st(!C,"user")},g=null,H=null;if(w){let a=o.find(u=>u.renderLauncher);if(a!=null&&a.renderLauncher){let u=a.renderLauncher({config:t,defaultRenderer:()=>nn(t,x).element,onToggle:x});u&&(H=u)}H||(g=nn(t,x))}g?n.appendChild(g.element):H&&n.appendChild(H),Dt(),tt.render(t.suggestionChips,_,oe,void 0,t.suggestionChipsConfig),Gt(),zt(_.isStreaming()),vt(!0),yt();let ye=()=>{var E,O,R,te,k,v,X,F;let a=(O=(E=t.launcher)==null?void 0:E.sidebarMode)!=null?O:!1,u=a||((te=(R=t.launcher)==null?void 0:R.fullHeight)!=null?te:!1);if(!w){S.style.height="",S.style.width="";return}if(!a){let B=(v=(k=t==null?void 0:t.launcher)==null?void 0:k.width)!=null?v:t==null?void 0:t.launcherWidth,q=B!=null?B:"min(400px, calc(100vw - 24px))";S.style.width=q,S.style.maxWidth=q}if(!u){let B=window.innerHeight,q=64,Me=(F=(X=t.launcher)==null?void 0:X.heightOffset)!=null?F:0,ge=Math.max(200,B-q),se=Math.min(640,ge),Re=Math.max(200,se-Me);S.style.height=`${Re}px`}};ye(),window.addEventListener("resize",ye),Ie.push(()=>window.removeEventListener("resize",ye)),We=U.scrollTop;let Ae=()=>{let a=U.scrollTop,u=U.scrollHeight,E=U.clientHeight,O=u-a-E,R=Math.abs(a-We);if(We=a,!Ue&&!(R<=Lt)){if(!Ke&&O<gt){Se=!1,Ke=!0;return}Ke&&O>gt&&(Se=!0,Be=Date.now()+St,Ke=!1)}};U.addEventListener("scroll",Ae,{passive:!0}),Ie.push(()=>U.removeEventListener("scroll",Ae)),Ie.push(()=>{J&&cancelAnimationFrame(J)});let Xe=()=>{j&&(qe&&(j.removeEventListener("click",qe),qe=null),w?(j.style.display="",qe=()=>{C=!1,Dt()},j.addEventListener("click",qe)):j.style.display="none")};Xe(),(()=>{let{clearChatButton:a}=ie;a&&a.addEventListener("click",()=>{_.clearMessages();try{localStorage.removeItem(Vt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vt}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Vt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let u=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let E=i.clear();E instanceof Promise&&E.catch(O=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",O)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},b.syncFromMetadata()})})(),Ye.addEventListener("submit",Zt),oe.addEventListener("keydown",Qt),Ie.push(()=>{Ye.removeEventListener("submit",Zt),oe.removeEventListener("keydown",Qt)}),Ie.push(()=>{_.cancel()}),g?Ie.push(()=>{g==null||g.destroy()}):H&&Ie.push(()=>{H==null||H.remove()});let xe={update(a){var en,qt,Yt,es,ts,ns,ss,os,rs,is,as,ls,ds,cs,ps,us,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,Hs,ks,Rs,Is,$s,Ps,Os,Ns,Fs,Ds,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs,Qs;let u=t.toolCall;t={...t,...a},wt(),Wn(n,t);let E=mn.getForInstance(t.plugins);if(o.length=0,o.push(...E),w=(qt=(en=t.launcher)==null?void 0:en.enabled)!=null?qt:!0,D=(es=(Yt=t.launcher)==null?void 0:Yt.autoExpand)!=null?es:!1,A=(ns=(ts=t.features)==null?void 0:ts.showReasoning)!=null?ns:!0,z=(os=(ss=t.features)==null?void 0:ss.showToolCalls)!=null?os:!0,((rs=t.launcher)==null?void 0:rs.enabled)===!1&&g&&(g.destroy(),g=null),((is=t.launcher)==null?void 0:is.enabled)===!1&&H&&(H.remove(),H=null),((as=t.launcher)==null?void 0:as.enabled)!==!1&&!g&&!H){let W=o.find(fe=>fe.renderLauncher);if(W!=null&&W.renderLauncher){let fe=W.renderLauncher({config:t,defaultRenderer:()=>nn(t,x).element,onToggle:x});fe&&(H=fe,n.appendChild(H))}H||(g=nn(t,x),n.appendChild(g.element))}g&&g.update(t),mt&&((ls=t.launcher)==null?void 0:ls.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((ds=t.launcher)==null?void 0:ds.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),w!==h?w?st(D,"auto"):(C=!0,Dt()):D!==N&&st(D,"auto"),N=D,h=w,ye(),Xe(),JSON.stringify(a.toolCall)!==JSON.stringify(u)&&_&&Ft(Z,_.getMessages(),$);let k=(cs=t.launcher)!=null?cs:{},v=(ps=k.headerIconHidden)!=null?ps:!1,X=k.headerIconName,F=(us=k.headerIconSize)!=null?us:"48px";if(me){let W=Y.querySelector(".tvw-border-b-cw-divider"),fe=W==null?void 0:W.querySelector(".tvw-flex-col");if(v)me.style.display="none",W&&fe&&!W.contains(fe)&&W.insertBefore(fe,W.firstChild);else{if(me.style.display="",me.style.height=F,me.style.width=F,W&&fe&&(W.contains(me)?me.nextSibling!==fe&&(me.remove(),W.insertBefore(me,fe)):W.insertBefore(me,fe)),X){let Ee=parseFloat(F)||24,Ce=ve(X,Ee*.6,"#ffffff",2);Ce?me.replaceChildren(Ce):me.textContent=(gs=k.agentIconText)!=null?gs:"\u{1F4AC}"}else if(k.iconUrl){let Ee=me.querySelector("img");if(Ee)Ee.src=k.iconUrl,Ee.style.height=F,Ee.style.width=F;else{let Ce=document.createElement("img");Ce.src=k.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=F,Ce.style.width=F,me.replaceChildren(Ce)}}else{let Ee=me.querySelector("svg"),Ce=me.querySelector("img");(Ee||Ce)&&me.replaceChildren(),me.textContent=(hs=k.agentIconText)!=null?hs:"\u{1F4AC}"}let ee=me.querySelector("img");ee&&(ee.style.height=F,ee.style.width=F)}}if(j){let W=(ms=k.closeButtonSize)!=null?ms:"32px",fe=(fs=k.closeButtonPlacement)!=null?fs:"inline";j.style.height=W,j.style.width=W;let{closeButtonWrapper:ee}=ie,Ee=fe==="top-right",Ce=ee==null?void 0:ee.classList.contains("tvw-absolute");if(ee&&Ee!==Ce)if(ee.remove(),Ee)ee.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(ee);else{let he=(ys=(ws=k.clearChat)==null?void 0:ws.placement)!=null?ys:"inline",Ge=(bs=(vs=k.clearChat)==null?void 0:vs.enabled)!=null?bs:!0;ee.className=Ge&&he==="inline"?"":"tvw-ml-auto";let Ze=Y.querySelector(".tvw-border-b-cw-divider");Ze&&Ze.appendChild(ee)}if(k.closeButtonColor?(j.style.color=k.closeButtonColor,j.classList.remove("tvw-text-cw-muted")):(j.style.color="",j.classList.add("tvw-text-cw-muted")),k.closeButtonBackgroundColor?(j.style.backgroundColor=k.closeButtonBackgroundColor,j.classList.remove("hover:tvw-bg-gray-100")):(j.style.backgroundColor="",j.classList.add("hover:tvw-bg-gray-100")),k.closeButtonBorderWidth||k.closeButtonBorderColor){let he=k.closeButtonBorderWidth||"0px",Ge=k.closeButtonBorderColor||"transparent";j.style.border=`${he} solid ${Ge}`,j.classList.remove("tvw-border-none")}else j.style.border="",j.classList.add("tvw-border-none");k.closeButtonBorderRadius?(j.style.borderRadius=k.closeButtonBorderRadius,j.classList.remove("tvw-rounded-full")):(j.style.borderRadius="",j.classList.add("tvw-rounded-full")),k.closeButtonPaddingX?(j.style.paddingLeft=k.closeButtonPaddingX,j.style.paddingRight=k.closeButtonPaddingX):(j.style.paddingLeft="",j.style.paddingRight=""),k.closeButtonPaddingY?(j.style.paddingTop=k.closeButtonPaddingY,j.style.paddingBottom=k.closeButtonPaddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Ve=(xs=k.closeButtonIconName)!=null?xs:"x",De=(Cs=k.closeButtonIconText)!=null?Cs:"\xD7";j.innerHTML="";let ut=ve(Ve,"20px",k.closeButtonColor||"",2);ut?j.appendChild(ut):j.textContent=De;let Ot=(Ss=k.closeButtonTooltipText)!=null?Ss:"Close chat",Te=(As=k.closeButtonShowTooltip)!=null?As:!0;if(j.setAttribute("aria-label",Ot),ee&&(ee._cleanupTooltip&&(ee._cleanupTooltip(),delete ee._cleanupTooltip),Te&&Ot)){let he=null,Ge=()=>{if(he||!j)return;he=c("div","tvw-clear-chat-tooltip"),he.textContent=Ot;let Jt=c("div");Jt.className="tvw-clear-chat-tooltip-arrow",he.appendChild(Jt);let bn=j.getBoundingClientRect();he.style.position="fixed",he.style.left=`${bn.left+bn.width/2}px`,he.style.top=`${bn.top-8}px`,he.style.transform="translate(-50%, -100%)",document.body.appendChild(he)},Ze=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};ee.addEventListener("mouseenter",Ge),ee.addEventListener("mouseleave",Ze),j.addEventListener("focus",Ge),j.addEventListener("blur",Ze),ee._cleanupTooltip=()=>{Ze(),ee&&(ee.removeEventListener("mouseenter",Ge),ee.removeEventListener("mouseleave",Ze)),j&&(j.removeEventListener("focus",Ge),j.removeEventListener("blur",Ze))}}}let{clearChatButton:B,clearChatButtonWrapper:q}=ie;if(B){let W=(Ts=k.clearChat)!=null?Ts:{},fe=(Es=W.enabled)!=null?Es:!0,ee=(Ws=W.placement)!=null?Ws:"inline";if(q){q.style.display=fe?"":"none";let Ee=ee==="top-right",Ce=q.classList.contains("tvw-absolute");if(Ee!==Ce&&fe){if(q.remove(),Ee)q.className="tvw-absolute tvw-top-4 tvw-z-50",q.style.right="48px",Y.style.position="relative",Y.appendChild(q);else{q.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",q.style.right="";let De=Y.querySelector(".tvw-border-b-cw-divider"),ut=ie.closeButtonWrapper;De&&ut&&ut.parentElement===De?De.insertBefore(q,ut):De&&De.appendChild(q)}let Ve=ie.closeButtonWrapper;Ve&&!Ve.classList.contains("tvw-absolute")&&(Ee?Ve.classList.add("tvw-ml-auto"):Ve.classList.remove("tvw-ml-auto"))}}if(fe){let Ee=(Ms=W.size)!=null?Ms:"32px";B.style.height=Ee,B.style.width=Ee;let Ce=(Ls=W.iconName)!=null?Ls:"refresh-cw",Ve=(Bs=W.iconColor)!=null?Bs:"";B.innerHTML="";let De=ve(Ce,"20px",Ve||"",2);if(De&&B.appendChild(De),Ve?(B.style.color=Ve,B.classList.remove("tvw-text-cw-muted")):(B.style.color="",B.classList.add("tvw-text-cw-muted")),W.backgroundColor?(B.style.backgroundColor=W.backgroundColor,B.classList.remove("hover:tvw-bg-gray-100")):(B.style.backgroundColor="",B.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let Te=W.borderWidth||"0px",he=W.borderColor||"transparent";B.style.border=`${Te} solid ${he}`,B.classList.remove("tvw-border-none")}else B.style.border="",B.classList.add("tvw-border-none");W.borderRadius?(B.style.borderRadius=W.borderRadius,B.classList.remove("tvw-rounded-full")):(B.style.borderRadius="",B.classList.add("tvw-rounded-full")),W.paddingX?(B.style.paddingLeft=W.paddingX,B.style.paddingRight=W.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),W.paddingY?(B.style.paddingTop=W.paddingY,B.style.paddingBottom=W.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let ut=(Hs=W.tooltipText)!=null?Hs:"Clear chat",Ot=(ks=W.showTooltip)!=null?ks:!0;if(B.setAttribute("aria-label",ut),q&&(q._cleanupTooltip&&(q._cleanupTooltip(),delete q._cleanupTooltip),Ot&&ut)){let Te=null,he=()=>{if(Te||!B)return;Te=c("div","tvw-clear-chat-tooltip"),Te.textContent=ut;let Ze=c("div");Ze.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(Ze);let Jt=B.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${Jt.left+Jt.width/2}px`,Te.style.top=`${Jt.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},Ge=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};q.addEventListener("mouseenter",he),q.addEventListener("mouseleave",Ge),B.addEventListener("focus",he),B.addEventListener("blur",Ge),q._cleanupTooltip=()=>{Ge(),q&&(q.removeEventListener("mouseenter",he),q.removeEventListener("mouseleave",Ge)),B&&(B.removeEventListener("focus",he),B.removeEventListener("blur",Ge))}}}}let Me=t.actionParsers&&t.actionParsers.length?t.actionParsers:[fn],ge=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Xt.message,Xt.messageAndClick];b=wn({parsers:Me,handlers:ge,getMetadata:m,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),$=xo(t,b),_.updateConfig(t),Ft(Z,_.getMessages(),$),tt.render(t.suggestionChips,_,oe,void 0,t.suggestionChipsConfig),Gt(),zt(_.isStreaming());let se=((Rs=t.voiceRecognition)==null?void 0:Rs.enabled)===!0,Re=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=se&&Re;if(Ye.classList.remove("tvw-gap-1","tvw-gap-3"),Ye.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),se&&Re)if(!M||!Le){let W=L(t.voiceRecognition,t.sendButton);W&&(M=W.micButton,Le=W.micButtonWrapper,Ye.insertBefore(Le,_e),M.addEventListener("click",ot),M.disabled=_.isStreaming())}else{let W=(Is=t.voiceRecognition)!=null?Is:{},fe=($s=t.sendButton)!=null?$s:{},ee=(Ps=W.iconName)!=null?Ps:"mic",Ee=(Os=fe.size)!=null?Os:"40px",Ce=(Ns=W.iconSize)!=null?Ns:Ee,Ve=parseFloat(Ce)||24;M.style.width=Ce,M.style.height=Ce,M.style.minWidth=Ce,M.style.minHeight=Ce;let De=(Ds=(Fs=W.iconColor)!=null?Fs:fe.textColor)!=null?Ds:"currentColor";M.innerHTML="";let ut=ve(ee,Ve,De,2);ut?M.appendChild(ut):M.textContent="\u{1F3A4}";let Ot=(js=W.backgroundColor)!=null?js:fe.backgroundColor;Ot?(M.style.backgroundColor=Ot,M.classList.remove("tvw-bg-cw-primary")):(M.style.backgroundColor="",M.classList.add("tvw-bg-cw-primary")),De?(M.style.color=De,M.classList.remove("tvw-text-white")):!De&&!fe.textColor&&(M.style.color="",M.classList.add("tvw-text-white")),W.borderWidth?(M.style.borderWidth=W.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),W.borderColor?M.style.borderColor=W.borderColor:M.style.borderColor="",W.paddingX?(M.style.paddingLeft=W.paddingX,M.style.paddingRight=W.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),W.paddingY?(M.style.paddingTop=W.paddingY,M.style.paddingBottom=W.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Te=Le==null?void 0:Le.querySelector(".tvw-send-button-tooltip"),he=(_s=W.tooltipText)!=null?_s:"Start voice recognition";if(((qs=W.showTooltip)!=null?qs:!1)&&he)if(Te)Te.textContent=he,Te.style.display="";else{let Ze=document.createElement("div");Ze.className="tvw-send-button-tooltip",Ze.textContent=he,Le==null||Le.insertBefore(Ze,M)}else Te&&(Te.style.display="none");Le.style.display="",M.disabled=_.isStreaming()}else M&&Le&&(Le.style.display="none",K&&ce());let re=(Us=t.sendButton)!=null?Us:{},ct=(zs=re.useIcon)!=null?zs:!1,kt=(Ys=re.iconText)!=null?Ys:"\u2191",Rt=re.iconName,Mt=(Js=re.tooltipText)!=null?Js:"Send message",jt=(Ks=re.showTooltip)!=null?Ks:!1,It=(Xs=re.size)!=null?Xs:"40px",_t=re.backgroundColor,pt=re.textColor;if(ct){if(P.style.width=It,P.style.height=It,P.style.minWidth=It,P.style.minHeight=It,P.style.fontSize="18px",P.style.lineHeight="1",P.innerHTML="",Rt){let W=parseFloat(It)||24,fe=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",ee=ve(Rt,W,fe,2);ee?(P.appendChild(ee),P.style.color=fe):(P.textContent=kt,pt?P.style.color=pt:P.classList.add("tvw-text-white"))}else P.textContent=kt,pt?P.style.color=pt:P.classList.add("tvw-text-white");P.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",_t?(P.style.backgroundColor=_t,P.classList.remove("tvw-bg-cw-primary")):P.classList.add("tvw-bg-cw-primary")}else P.textContent=(Gs=(Vs=t.copy)==null?void 0:Vs.sendButtonLabel)!=null?Gs:"Send",P.style.width="",P.style.height="",P.style.minWidth="",P.style.minHeight="",P.style.fontSize="",P.style.lineHeight="",P.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",_t?(P.style.backgroundColor=_t,P.classList.remove("tvw-bg-cw-accent")):P.classList.add("tvw-bg-cw-accent"),pt?P.style.color=pt:P.classList.add("tvw-text-white");re.borderWidth?(P.style.borderWidth=re.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),re.borderColor?P.style.borderColor=re.borderColor:P.style.borderColor="",re.paddingX?(P.style.paddingLeft=re.paddingX,P.style.paddingRight=re.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),re.paddingY?(P.style.paddingTop=re.paddingY,P.style.paddingBottom=re.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let $t=_e==null?void 0:_e.querySelector(".tvw-send-button-tooltip");if(jt&&Mt)if($t)$t.textContent=Mt,$t.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=Mt,_e==null||_e.insertBefore(W,P)}else $t&&($t.style.display="none");let Pt=(Zs=t.statusIndicator)!=null?Zs:{},pn=(Qs=Pt.visible)!=null?Qs:!0;if(Qe.style.display=pn?"":"none",_){let W=_.getStatus(),fe=ee=>{var Ee,Ce,Ve,De;return ee==="idle"?(Ee=Pt.idleText)!=null?Ee:ze.idle:ee==="connecting"?(Ce=Pt.connectingText)!=null?Ce:ze.connecting:ee==="connected"?(Ve=Pt.connectedText)!=null?Ve:ze.connected:ee==="error"?(De=Pt.errorText)!=null?De:ze.error:ze[ee]};Qe.textContent=fe(W)}},open(){w&&st(!0,"api")},close(){w&&st(!1,"api")},toggle(){w&&st(!C,"api")},clearChat(){_.clearMessages();try{localStorage.removeItem(Vt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vt}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Vt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}l={},b.syncFromMetadata()},setMessage(a){return!oe||_.isStreaming()?!1:(!C&&w&&st(!0,"system"),oe.value=a,oe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(_.isStreaming())return!1;let u=(a==null?void 0:a.trim())||oe.value.trim();return u?(!C&&w&&st(!0,"system"),oe.value="",_.sendMessage(u),!0):!1},startVoiceRecognition(){return K||_.isStreaming()||!$e()?!1:(!C&&w&&st(!0,"system"),de.manuallyDeactivated=!1,be(),Pe("user"),!0)},stopVoiceRecognition(){return K?(de.manuallyDeactivated=!0,be(),ce("user"),!0):!1},injectTestMessage(a){!C&&w&&st(!0,"system"),_.injectTestEvent(a)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,u){return s.on(a,u)},off(a,u){s.off(a,u)},isOpen(){return w&&C},isVoiceActive(){return de.active},getState(){return{open:w&&C,launcherEnabled:w,voiceActive:de.active,streaming:_.isStreaming()}},destroy(){Ie.forEach(a=>a()),G.remove(),g==null||g.destroy(),H==null||H.remove(),qe&&j.removeEventListener("click",qe)}};if((((Qn=r==null?void 0:r.debugTools)!=null?Qn:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,u={controller:xe,getMessages:xe.getMessages,getStatus:xe.getStatus,getMetadata:xe.getPersistentMetadata,updateMetadata:xe.updatePersistentMetadata,clearHistory:()=>xe.clearChat(),setVoiceActive:E=>E?xe.startVoiceRecognition():xe.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ie.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}return xe};var Yn={},Go=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},Zo=()=>{try{if(typeof Yn!="undefined"&&Yn.url)return new URL("../widget.css",Yn.url).href}catch{}return null},Co=n=>{let e=Zo(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let o=t.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},So=n=>{var m,d,T,f;let e=Go(n.target),r=document.createElement("div");r.className="vanilla-agent-host";let t=(T=(d=(m=n.config)==null?void 0:m.launcher)==null?void 0:d.enabled)!=null?T:!0;t||(r.style.height="100%"),e.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let b=r.attachShadow({mode:"open"});i=b,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),b.appendChild(s),Co(b)}else i=r,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),Co(r);let l=zn(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let p={...l,host:r,destroy(){l.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=p),p};function Qo(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function yn(n){var e,r;return(r=(e=n.parserType)!=null?e:Qo(n.streamParser))!=null?r:"plain"}function er(n,e="esm"){let r={...n};return delete r.postprocessMessage,delete r.initialMessages,e==="esm"?tr(r):e==="script-installer"?or(r):e==="script-advanced"?ir(r):e==="react-component"?nr(r):e==="react-advanced"?sr(r):rr(r)}function tr(n){let e=yn(n),r=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
57
57
  `)}function nr(n){let e=yn(n),r=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
58
58
  `)}function sr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"?e.push(` ${r}: ${t},`):typeof t=="number"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,t])=>{e.push(` ${r}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
59
59
  `)}function or(n){let e=yn(n),r=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
60
60
  `)}function rr(n){let e=yn(n),r=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
61
61
  `)}function ir(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"?e.push(` ${r}: ${t},`):typeof t=="number"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,t])=>{e.push(` ${r}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" }),"),e.push(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
62
- `)}var zi=So;export{Kt as AgentWidgetClient,tn as AgentWidgetSession,Ne as DEFAULT_WIDGET_CONFIG,sn as attachHeaderToContainer,on as buildComposer,lo as buildDefaultHeader,po as buildExpandedHeader,Ut as buildHeader,Ln as buildHeaderWithLayout,co as buildMinimalHeader,an as componentRegistry,wn as createActionManager,zn as createAgentExperience,No as createBubbleWithLayout,Xo as createComponentMiddleware,Fn as createComponentStreamParser,Bo as createFlexibleJsonStreamParser,Tn as createJsonStreamParser,Nn as createLocalStorageAdapter,Sn as createPlainTextParser,An as createRegexJsonParser,rn as createStandardBubble,hn as createTypingIndicator,En as createXmlParser,zi as default,Xt as defaultActionHandlers,fn as defaultJsonActionParser,Eo as directivePostprocessor,xn as escapeHtml,qn as extractComponentDirectiveFromMessage,er as generateCodeSnippet,uo as getHeaderLayout,_n as hasComponentDirective,Mn as headerLayouts,So as initAgentWidget,Ko as isComponentDirectiveType,no as markdownPostprocessor,Pn as mergeWithDefaults,mn as pluginRegistry,jn as renderComponentDirective};
62
+ `)}var zi=So;export{Kt as AgentWidgetClient,tn as AgentWidgetSession,Ne as DEFAULT_WIDGET_CONFIG,sn as attachHeaderToContainer,on as buildComposer,lo as buildDefaultHeader,po as buildExpandedHeader,Ut as buildHeader,Ln as buildHeaderWithLayout,co as buildMinimalHeader,an as componentRegistry,wn as createActionManager,zn as createAgentExperience,No as createBubbleWithLayout,Xo as createComponentMiddleware,Dn as createComponentStreamParser,Bo as createFlexibleJsonStreamParser,Tn as createJsonStreamParser,Nn as createLocalStorageAdapter,Sn as createPlainTextParser,An as createRegexJsonParser,rn as createStandardBubble,hn as createTypingIndicator,En as createXmlParser,zi as default,Xt as defaultActionHandlers,fn as defaultJsonActionParser,Eo as directivePostprocessor,xn as escapeHtml,qn as extractComponentDirectiveFromMessage,er as generateCodeSnippet,uo as getHeaderLayout,_n as hasComponentDirective,Mn as headerLayouts,So as initAgentWidget,Ko as isComponentDirectiveType,no as markdownPostprocessor,Pn as mergeWithDefaults,mn as pluginRegistry,jn as renderComponentDirective};
63
63
  //# sourceMappingURL=index.js.map