vanilla-agent 1.30.0 → 1.31.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
- import{Marked as mr}from"marked";var hr=n=>{if(n)return n},vn=n=>{var r,s;let t=n==null?void 0:n.markedOptions,o=new mr({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=hr(n==null?void 0:n.renderer);return e&&o.use({renderer:e}),i=>o.parse(i)},bn=n=>n?vn({markedOptions:n.options,renderer:n.renderer}):vn(),fr=vn(),Fs=n=>fr(n),Pn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ns=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),$s=n=>`%%FORM_PLACEHOLDER_${n}%%`,Os=(n,t)=>{let o=n;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=$s(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return e}return e}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let s=$s(t.length);return t.push({token:s,type:r}),s}),o},wr=n=>{let t=bn(n);return o=>{let e=[],r=Os(o,e),s=t(r);return e.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${Ns(l)}"></div>`;s=s.replace(d,f)}),s}},yr=n=>{let t=[],o=Os(n,t),e=Fs(o);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Ns(s)}"></div>`;e=e.replace(i,d)}),e};import{parse as Ds,STR as _s,OBJ as js}from"partial-json";var Cn=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),In=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)}},vr=n=>{var i,l;let t=(i=n.completedAt)!=null?i:Date.now(),o=(l=n.startedAt)!=null?l:t,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},qs=n=>n.status==="complete"?vr(n):n.status==="pending"?"Waiting":"",br=n=>{var r,s,i;let o=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((r=n.completedAt)!=null?r:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Us=n=>n.status==="complete"?br(n):"Using tool...",Cr=()=>{let n=null,t=0,o=e=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1
+ import{Marked as Cr}from"marked";var xr=n=>{if(n)return n},Sn=n=>{var r,s;let t=n==null?void 0:n.markedOptions,o=new Cr({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=xr(n==null?void 0:n.renderer);return e&&o.use({renderer:e}),i=>o.parse(i)},An=n=>n?Sn({markedOptions:n.options,renderer:n.renderer}):Sn(),Sr=Sn(),js=n=>Sr(n),Nn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),qs=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),_s=n=>`%%FORM_PLACEHOLDER_${n}%%`,Us=(n,t)=>{let o=n;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=_s(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return e}return e}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let s=_s(t.length);return t.push({token:s,type:r}),s}),o},Ar=n=>{let t=An(n);return o=>{let e=[],r=Us(o,e),s=t(r);return e.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),w=`<div class="tvw-form-directive" data-tv-form="${qs(l)}"></div>`;s=s.replace(d,w)}),s}},Tr=n=>{let t=[],o=Us(n,t),e=js(o);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${qs(s)}"></div>`;e=e.replace(i,d)}),e};import{parse as zs,STR as Js,OBJ as Ys}from"partial-json";var Tn=n=>n.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),On=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)}},Er=n=>{var i,l;let t=(i=n.completedAt)!=null?i:Date.now(),o=(l=n.startedAt)!=null?l:t,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Ks=n=>n.status==="complete"?Er(n):n.status==="pending"?"Waiting":"",Mr=n=>{var r,s,i;let o=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((r=n.completedAt)!=null?r:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Xs=n=>n.status==="complete"?Mr(n):"Using tool...",kr=()=>{let n=null,t=0,o=e=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(r);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=e.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 e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(e);return s!==null&&(n=s),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},xn=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},$n=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Fn=()=>{var t;let n=Cr();return{processChunk:async o=>{let e=o.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(o)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},Nn=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:o=>{let e=o.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(o.length<=t)return n!==null||n===""?{text:n||"",raw:o}:null;try{let r=Ds(o,_s|js);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?Cn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=Cn(r.text)))}catch{}return t=o.length,n!==null?{text:n,raw:o}:null},close:()=>{}}},xr=n=>{let t=null,o=0,r=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?Cn(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Cn(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:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=o)return t!==null?{text:t,raw:s}:null;try{let l=Ds(s,_s|js),d=r(l);d!==null&&(t=d)}catch{}return o=s.length,{text:t||"",raw:s}},close:()=>{}}},On=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var Sr="https://api.travrse.ai/v1/dispatch",zs="https://api.travrse.ai";function Ar(n){switch(n){case"json":return Nn;case"regex-json":return Fn;case"xml":return On;case"plain":default:return $n}}var Kt=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var o,e,r;this.apiUrl=(o=t.apiUrl)!=null?o:Sr,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:Ar(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(t){var e;let o=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||zs;return t==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,o;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,(o=(t=this.config).onSessionInit)==null||o.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.clientToken,flow_id:this.config.flowId})});if(!t.ok){let e=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${e.hint||e.error}`):t.status===403?new Error(`Origin not allowed: ${e.hint||e.error}`):new Error(e.error||"Failed to initialize session")}let o=await t.json();return{sessionId:o.session_id,expiresAt:new Date(o.expires_at),flow:o.flow,config:{welcomeMessage:o.config.welcome_message,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||zs}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.message_id)throw new Error(`message_id is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,message_id:t,type:o})}async submitCSATFeedback(t,o){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"nps",rating:t,comment:o})}async dispatch(t,o){return this.isClientTokenMode()?this.dispatchClientToken(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){var r,s,i,l;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let u=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:u}),u}let c=await this.buildPayload(t.messages),f={session_id:d.sessionId,messages:t.messages.map(u=>({id:u.id,role:u.role,content:u.rawContent||u.content})),...t.assistantMessageId&&{assistant_message_id:t.assistantMessageId},...c.metadata&&{metadata:c.metadata},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",f);let w=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f),signal:e.signal});if(!w.ok){let u=await w.json().catch(()=>({error:"Chat request failed"}));if(w.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let g=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:g}),g}if(w.status===429){let g=new Error(u.hint||"Message limit reached for this session.");throw o({type:"error",error:g}),g}let v=new Error(u.error||"Failed to send message");throw o({type:"error",error:v}),v}if(!w.body){let u=new Error("No response body received");throw o({type:"error",error:u}),u}o({type:"status",status:"connected"});try{await this.streamResponse(w.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&o({type:"error",error:c}),c}}async dispatchProxy(t,o){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);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(r),signal:e.signal},r)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:l}),l}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(t){let e={messages:t.slice().sort((r,s)=>{let i=new Date(r.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(r=>({role:r.role,content:r.rawContent||r.content,createdAt:r.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(e.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...e},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return e}async handleCustomSSEEvent(t,o,e,r,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let l=()=>{if(e.current)return e.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return e.current=d,r(d),d};if(i.text!==void 0){let d=l();d.content+=i.text,r(d)}return i.done&&(e.current&&(e.current.streaming=!1,r(e.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,o,e){var st,se,D,Ke,Ze,rt,St,At,_,fe,Xe,Ve,Je,it,P,Pe,ut,pt,Wt,yt,Ie,Ge,vt,at,Ee,B,ee,ke,Be,et,De,tt,Tt,gt,Bt,Ht,zt,Rt,We,ue,bt,Pt,mt,un,pn,Gt,Ot,Lt,gn,mn,hn,Rn,Dt,_t,Ye,Jt;let r=t.getReader(),s=new TextDecoder,i="",l=Date.now(),d=0,c=()=>l+d++,f=L=>{let ae=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,ye=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,pe=L.tools?L.tools.map(xe=>({...xe,chunks:xe.chunks?[...xe.chunks]:void 0})):void 0;return{...L,reasoning:ae,toolCall:ye,tools:pe}},w=L=>{o({type:"message",message:f(L)})},u=null,v={current:null},g=new Map,N=new Map,I={lastId:null,byStep:new Map},m={lastId:null,byCall:new Map},k=L=>{if(L==null)return null;try{return String(L)}catch{return null}},C=L=>{var ae,ye,pe,xe,He;return k((He=(xe=(pe=(ye=(ae=L.stepId)!=null?ae:L.step_id)!=null?ye:L.step)!=null?pe:L.parentId)!=null?xe:L.flowStepId)!=null?He:L.flow_step_id)},y=L=>{var ae,ye,pe,xe,He,Se,R;return k((R=(Se=(He=(xe=(pe=(ye=(ae=L.callId)!=null?ae:L.call_id)!=null?ye:L.requestId)!=null?pe:L.request_id)!=null?xe:L.toolCallId)!=null?He:L.tool_call_id)!=null?Se:L.stepId)!=null?R:L.step_id)},F=()=>u||(u={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},w(u),u),b=(L,ae)=>{I.lastId=ae,L&&I.byStep.set(L,ae)},T=(L,ae)=>{var He;let ye=(He=L.reasoningId)!=null?He:L.id,pe=C(L);if(ye){let Se=String(ye);return b(pe,Se),Se}if(pe){let Se=I.byStep.get(pe);if(Se)return I.lastId=Se,Se}if(I.lastId&&!ae)return I.lastId;if(!ae)return null;let xe=`reason-${c()}`;return b(pe,xe),xe},K=L=>{let ae=g.get(L);if(ae)return ae;let ye={id:`reason-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:L,status:"streaming",chunks:[]}};return g.set(L,ye),w(ye),ye},J=(L,ae)=>{m.lastId=ae,L&&m.byCall.set(L,ae)},j=(L,ae)=>{var He;let ye=(He=L.toolId)!=null?He:L.id,pe=y(L);if(ye){let Se=String(ye);return J(pe,Se),Se}if(pe){let Se=m.byCall.get(pe);if(Se)return m.lastId=Se,Se}if(m.lastId&&!ae)return m.lastId;if(!ae)return null;let xe=`tool-${c()}`;return J(pe,xe),xe},O=L=>{let ae=N.get(L);if(ae)return ae;let ye={id:`tool-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:L,status:"pending"}};return N.set(L,ye),w(ye),ye},q=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let ae=Number(L);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let ye=Date.parse(L);if(!Number.isNaN(ye))return ye}return Date.now()},U=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},Y=new Map,Q=new Map;for(;;){let{done:L,value:ae}=await r.read();if(L)break;i+=s.decode(ae,{stream:!0});let ye=i.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(e);return s!==null&&(n=s),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},En=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Dn=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},_n=()=>{var t;let n=kr();return{processChunk:async o=>{let e=o.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(o)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},jn=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:o=>{let e=o.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(o.length<=t)return n!==null||n===""?{text:n||"",raw:o}:null;try{let r=zs(o,Js|Ys);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?Tn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=Tn(r.text)))}catch{}return t=o.length,n!==null?{text:n,raw:o}:null},close:()=>{}}},Wr=n=>{let t=null,o=0,r=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?Tn(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Tn(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:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=o)return t!==null?{text:t,raw:s}:null;try{let l=zs(s,Js|Ys),d=r(l);d!==null&&(t=d)}catch{}return o=s.length,{text:t||"",raw:s}},close:()=>{}}},qn=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var Lr="https://api.travrse.ai/v1/dispatch",Vs="https://api.travrse.ai";function Br(n){switch(n){case"json":return jn;case"regex-json":return _n;case"xml":return qn;case"plain":default:return Dn}}var Jt=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var o,e,r;this.apiUrl=(o=t.apiUrl)!=null?o:Lr,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:Br(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(t){var e;let o=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Vs;return t==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,o;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,(o=(t=this.config).onSessionInit)==null||o.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.clientToken,flow_id:this.config.flowId})});if(!t.ok){let e=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${e.hint||e.error}`):t.status===403?new Error(`Origin not allowed: ${e.hint||e.error}`):new Error(e.error||"Failed to initialize session")}let o=await t.json();return{sessionId:o.session_id,expiresAt:new Date(o.expires_at),flow:o.flow,config:{welcomeMessage:o.config.welcome_message,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Vs}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.message_id)throw new Error(`message_id is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,message_id:t,type:o})}async submitCSATFeedback(t,o){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"nps",rating:t,comment:o})}async dispatch(t,o){return this.isClientTokenMode()?this.dispatchClientToken(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){var r,s,i,l;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let p=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:p}),p}let c=await this.buildPayload(t.messages),w={session_id:d.sessionId,messages:t.messages.map(p=>({id:p.id,role:p.role,content:p.rawContent||p.content})),...t.assistantMessageId&&{assistant_message_id:t.assistantMessageId},...c.metadata&&{metadata:c.metadata},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w);let g=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:e.signal});if(!g.ok){let p=await g.json().catch(()=>({error:"Chat request failed"}));if(g.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let m=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:m}),m}if(g.status===429){let m=new Error(p.hint||"Message limit reached for this session.");throw o({type:"error",error:m}),m}let v=new Error(p.error||"Failed to send message");throw o({type:"error",error:v}),v}if(!g.body){let p=new Error("No response body received");throw o({type:"error",error:p}),p}o({type:"status",status:"connected"});try{await this.streamResponse(g.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&o({type:"error",error:c}),c}}async dispatchProxy(t,o){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);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(r),signal:e.signal},r)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:l}),l}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(t){let e={messages:t.slice().sort((r,s)=>{let i=new Date(r.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(r=>({role:r.role,content:r.rawContent||r.content,createdAt:r.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(e.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...e},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return e}async handleCustomSSEEvent(t,o,e,r,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let l=()=>{if(e.current)return e.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return e.current=d,r(d),d};if(i.text!==void 0){let d=l();d.content+=i.text,r(d)}return i.done&&(e.current&&(e.current.streaming=!1,r(e.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,o,e){var it,oe,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,P,$e,ut,pt,Lt,bt,Ct,Fe,et,xt,Me,Le,b,Be,Ee,Ke,ot,st,gt,mt,Mt,Rt,zt,Nt,He,ht,pe,Pt,Bt,Ht,hn,fn,Qt,Ot,It,wn,yn,vn,Fn,Dt,_t,Ye;let r=t.getReader(),s=new TextDecoder,i="",l=Date.now(),d=0,c=()=>l+d++,w=B=>{let re=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,he=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Ie=B.tools?B.tools.map(fe=>({...fe,chunks:fe.chunks?[...fe.chunks]:void 0})):void 0;return{...B,reasoning:re,toolCall:he,tools:Ie}},g=B=>{o({type:"message",message:w(B)})},p=null,v={current:null},m=new Map,N=new Map,M={lastId:null,byStep:new Map},f={lastId:null,byCall:new Map},S=B=>{if(B==null)return null;try{return String(B)}catch{return null}},R=B=>{var re,he,Ie,fe,Ae;return S((Ae=(fe=(Ie=(he=(re=B.stepId)!=null?re:B.step_id)!=null?he:B.step)!=null?Ie:B.parentId)!=null?fe:B.flowStepId)!=null?Ae:B.flow_step_id)},y=B=>{var re,he,Ie,fe,Ae,be,H;return S((H=(be=(Ae=(fe=(Ie=(he=(re=B.callId)!=null?re:B.call_id)!=null?he:B.requestId)!=null?Ie:B.request_id)!=null?fe:B.toolCallId)!=null?Ae:B.tool_call_id)!=null?be:B.stepId)!=null?H:B.step_id)},F=()=>p||(p={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(p),p),x=(B,re)=>{M.lastId=re,B&&M.byStep.set(B,re)},k=(B,re)=>{var Ae;let he=(Ae=B.reasoningId)!=null?Ae:B.id,Ie=R(B);if(he){let be=String(he);return x(Ie,be),be}if(Ie){let be=M.byStep.get(Ie);if(be)return M.lastId=be,be}if(M.lastId&&!re)return M.lastId;if(!re)return null;let fe=`reason-${c()}`;return x(Ie,fe),fe},Y=B=>{let re=m.get(B);if(re)return re;let he={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"streaming",chunks:[]}};return m.set(B,he),g(he),he},z=(B,re)=>{f.lastId=re,B&&f.byCall.set(B,re)},j=(B,re)=>{var Ae;let he=(Ae=B.toolId)!=null?Ae:B.id,Ie=y(B);if(he){let be=String(he);return z(Ie,be),be}if(Ie){let be=f.byCall.get(Ie);if(be)return f.lastId=be,be}if(f.lastId&&!re)return f.lastId;if(!re)return null;let fe=`tool-${c()}`;return z(Ie,fe),fe},O=B=>{let re=N.get(B);if(re)return re;let he={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:B,status:"pending"}};return N.set(B,he),g(he),he},q=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let re=Number(B);if(!Number.isNaN(re)&&Number.isFinite(re))return re;let he=Date.parse(B);if(!Number.isNaN(he))return he}return Date.now()},U=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},J=new Map,V=new Map;for(;;){let{done:B,value:re}=await r.read();if(B)break;i+=s.decode(re,{stream:!0});let he=i.split(`
5
5
 
6
- `);i=(st=ye.pop())!=null?st:"";for(let pe of ye){let xe=pe.split(`
7
- `),He="message",Se="";for(let V of xe)V.startsWith("event:")?He=V.replace("event:","").trim():V.startsWith("data:")&&(Se+=V.replace("data:","").trim());if(!Se)continue;let R;try{R=JSON.parse(Se)}catch(V){o({type:"error",error:V instanceof Error?V:new Error("Failed to parse chat stream payload")});continue}let nt=He!=="message"?He:(se=R.type)!=null?se:"message";if(this.parseSSEEvent){v.current=u;let V=await this.handleCustomSSEEvent(R,o,v,w,c);if(v.current&&!u&&(u=v.current),V)continue}if(nt==="reason_start"){let V=(D=T(R,!0))!=null?D:`reason-${c()}`,H=K(V);H.reasoning=(Ke=H.reasoning)!=null?Ke:{id:V,status:"streaming",chunks:[]},H.reasoning.startedAt=(rt=H.reasoning.startedAt)!=null?rt:q((Ze=R.startedAt)!=null?Ze:R.timestamp),H.reasoning.completedAt=void 0,H.reasoning.durationMs=void 0,H.streaming=!0,H.reasoning.status="streaming",w(H)}else if(nt==="reason_chunk"){let V=(At=(St=T(R,!1))!=null?St:T(R,!0))!=null?At:`reason-${c()}`,H=K(V);H.reasoning=(_=H.reasoning)!=null?_:{id:V,status:"streaming",chunks:[]},H.reasoning.startedAt=(Xe=H.reasoning.startedAt)!=null?Xe:q((fe=R.startedAt)!=null?fe:R.timestamp);let x=(it=(Je=(Ve=R.reasoningText)!=null?Ve:R.text)!=null?Je:R.delta)!=null?it:"";if(x&&R.hidden!==!0&&H.reasoning.chunks.push(String(x)),H.reasoning.status=R.done?"complete":"streaming",R.done){H.reasoning.completedAt=q((P=R.completedAt)!=null?P:R.timestamp);let X=(Pe=H.reasoning.startedAt)!=null?Pe:Date.now();H.reasoning.durationMs=Math.max(0,((ut=H.reasoning.completedAt)!=null?ut:Date.now())-X)}H.streaming=H.reasoning.status!=="complete",w(H)}else if(nt==="reason_complete"){let V=(Wt=(pt=T(R,!1))!=null?pt:T(R,!0))!=null?Wt:`reason-${c()}`,H=g.get(V);if(H!=null&&H.reasoning){H.reasoning.status="complete",H.reasoning.completedAt=q((yt=R.completedAt)!=null?yt:R.timestamp);let X=(Ie=H.reasoning.startedAt)!=null?Ie:Date.now();H.reasoning.durationMs=Math.max(0,((Ge=H.reasoning.completedAt)!=null?Ge:Date.now())-X),H.streaming=!1,w(H)}let x=C(R);x&&I.byStep.delete(x)}else if(nt==="tool_start"){let V=(vt=j(R,!0))!=null?vt:`tool-${c()}`,H=O(V),x=(at=H.toolCall)!=null?at:{id:V,status:"pending"};x.name=(Ee=R.toolName)!=null?Ee:x.name,x.status="running",R.args!==void 0&&(x.args=R.args),x.startedAt=(ee=x.startedAt)!=null?ee:q((B=R.startedAt)!=null?B:R.timestamp),x.completedAt=void 0,x.durationMs=void 0,H.toolCall=x,H.streaming=!0,w(H)}else if(nt==="tool_chunk"){let V=(Be=(ke=j(R,!1))!=null?ke:j(R,!0))!=null?Be:`tool-${c()}`,H=O(V),x=(et=H.toolCall)!=null?et:{id:V,status:"running"};x.startedAt=(tt=x.startedAt)!=null?tt:q((De=R.startedAt)!=null?De:R.timestamp);let X=(Bt=(gt=(Tt=R.text)!=null?Tt:R.delta)!=null?gt:R.message)!=null?Bt:"";X&&(x.chunks=(Ht=x.chunks)!=null?Ht:[],x.chunks.push(String(X))),x.status="running",H.toolCall=x,H.streaming=!0,w(H)}else if(nt==="tool_complete"){let V=(Rt=(zt=j(R,!1))!=null?zt:j(R,!0))!=null?Rt:`tool-${c()}`,H=O(V),x=(We=H.toolCall)!=null?We:{id:V,status:"running"};if(x.status="complete",R.result!==void 0&&(x.result=R.result),typeof R.duration=="number"&&(x.duration=R.duration),x.completedAt=q((ue=R.completedAt)!=null?ue:R.timestamp),typeof R.duration=="number")x.durationMs=R.duration;else{let Ae=(bt=x.startedAt)!=null?bt:Date.now();x.durationMs=Math.max(0,((Pt=x.completedAt)!=null?Pt:Date.now())-Ae)}H.toolCall=x,H.streaming=!1,w(H);let X=y(R);X&&m.byCall.delete(X)}else if(nt==="step_chunk"){let V=R.stepType,H=R.executionType;if(V==="tool"||H==="context")continue;let x=F(),X=(Gt=(pn=(un=(mt=R.text)!=null?mt:R.delta)!=null?un:R.content)!=null?pn:R.chunk)!=null?Gt:"";if(X){let G=((Ot=Q.get(x.id))!=null?Ot:"")+X;x.rawContent=G,Y.has(x.id)||Y.set(x.id,this.createStreamParser());let le=Y.get(x.id),Te=G.trim().startsWith("{")||G.trim().startsWith("[");if(Te&&Q.set(x.id,G),le.__isPlainTextParser===!0){x.content+=X,Q.delete(x.id),Y.delete(x.id),x.rawContent=void 0,w(x);continue}let Fe=le.processChunk(G);if(Fe instanceof Promise)Fe.then(be=>{var je;let re=typeof be=="string"?be:(je=be==null?void 0:be.text)!=null?je:null;if(re!==null&&re.trim()!==""){let Ce=u;Ce&&Ce.id===x.id&&(Ce.content=re,w(Ce))}else if(!Te&&!G.trim().startsWith("<")){let Ce=u;Ce&&Ce.id===x.id&&(Ce.content+=X,Q.delete(Ce.id),Y.delete(Ce.id),Ce.rawContent=void 0,w(Ce))}}).catch(()=>{x.content+=X,Q.delete(x.id),Y.delete(x.id),x.rawContent=void 0,w(x)});else{let be=typeof Fe=="string"?Fe:(Lt=Fe==null?void 0:Fe.text)!=null?Lt:null;be!==null&&be.trim()!==""?(x.content=be,w(x)):!Te&&!G.trim().startsWith("<")&&(x.content+=X,Q.delete(x.id),Y.delete(x.id),x.rawContent=void 0,w(x))}}if(R.isComplete){let Ae=(mn=(gn=R.result)==null?void 0:gn.response)!=null?mn:x.content;if(Ae){let G=Q.get(x.id),le=G!=null?G:U(Ae);x.rawContent=le;let Te=Y.get(x.id),_e=null,Fe=!1;if(Te&&(_e=Te.getExtractedText(),_e===null&&(_e=xn(le)),_e===null)){let be=Te.processChunk(le);be instanceof Promise?(Fe=!0,be.then(re=>{var Ce;let je=typeof re=="string"?re:(Ce=re==null?void 0:re.text)!=null?Ce:null;if(je!==null){let qe=u;qe&&qe.id===x.id&&(qe.content=je,qe.streaming=!1,Y.delete(qe.id),Q.delete(qe.id),w(qe))}})):_e=typeof be=="string"?be:(hn=be==null?void 0:be.text)!=null?hn:null}if(!Fe){_e!==null&&_e.trim()!==""?x.content=_e:Q.has(x.id)||(x.content=U(Ae));let be=Y.get(x.id);if(be){let re=(Rn=be.close)==null?void 0:Rn.call(be);re instanceof Promise&&re.catch(()=>{}),Y.delete(x.id)}Q.delete(x.id),x.streaming=!1,w(x)}}}}else if(nt==="step_complete"){let V=R.stepType,H=R.executionType;if(V==="tool"||H==="context")continue;let x=(Dt=R.result)==null?void 0:Dt.response,X=F();if(x!=null){let Ae=Y.get(X.id),G=!1,le=!1;if(Ae){let Te=Ae.getExtractedText(),_e=Q.get(X.id),Fe=_e!=null?_e:U(x);if(X.rawContent=Fe,Te!==null&&Te.trim()!=="")X.content=Te,G=!0;else{let be=xn(Fe);if(be!==null)X.content=be,G=!0;else{let re=Ae.processChunk(Fe);if(re instanceof Promise)le=!0,re.then(je=>{var qe;let Ce=typeof je=="string"?je:(qe=je==null?void 0:je.text)!=null?qe:null;if(Ce!==null&&Ce.trim()!==""){let lt=u;lt&&lt.id===X.id&&(lt.content=Ce,lt.streaming=!1,Y.delete(lt.id),Q.delete(lt.id),w(lt))}else{let lt=Ae.getExtractedText(),wt=u;wt&&wt.id===X.id&&(lt!==null&&lt.trim()!==""?wt.content=lt:Q.has(wt.id)||(wt.content=U(x)),wt.streaming=!1,Y.delete(wt.id),Q.delete(wt.id),w(wt))}});else{let je=typeof re=="string"?re:(_t=re==null?void 0:re.text)!=null?_t:null;if(je!==null&&je.trim()!=="")X.content=je,G=!0;else{let Ce=Ae.getExtractedText();Ce!==null&&Ce.trim()!==""&&(X.content=Ce,G=!0)}}}}}if(!le){if(!X.rawContent){let Te=Q.get(X.id);X.rawContent=Te!=null?Te:U(x)}if(!G&&!Q.has(X.id)&&(X.content=U(x)),Ae){let Te=(Ye=Ae.close)==null?void 0:Ye.call(Ae);Te instanceof Promise&&Te.catch(()=>{})}Y.delete(X.id),Q.delete(X.id),X.streaming=!1,w(X)}}else Y.delete(X.id),Q.delete(X.id),X.streaming=!1,w(X)}else if(nt==="flow_complete"){let V=(Jt=R.result)==null?void 0:Jt.response;if(V!=null){let H=F(),x=Q.get(H.id),X=x!=null?x:U(V);H.rawContent=X;let Ae=U(V),G=Y.get(H.id);if(G){let _e=xn(X);if(_e!==null)Ae=_e;else{let Fe=G.processChunk(X);Fe instanceof Promise&&Fe.then(re=>{var Ce;let je=typeof re=="string"?re:(Ce=re==null?void 0:re.text)!=null?Ce:null;if(je!==null){let qe=u;qe&&qe.id===H.id&&(qe.content=je,qe.streaming=!1,w(qe))}});let be=G.getExtractedText();be!==null&&(Ae=be)}}Y.delete(H.id),Q.delete(H.id);let le=Ae!==H.content,Te=H.streaming!==!1;le&&(H.content=Ae),H.streaming=!1,(le||Te)&&w(H)}else if(u!==null){let H=u;Y.delete(H.id),Q.delete(H.id),H.streaming!==!1&&(H.streaming=!1,w(H))}o({type:"status",status:"idle"})}else nt==="error"&&R.error&&o({type:"error",error:R.error instanceof Error?R.error:new Error(String(R.error))})}}}};function Tr(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function Dn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function _n(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var on=class{constructor(t={},o){this.config=t;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=t=>{var o,e;t.type==="message"?this.upsertMessage(t.message):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null)):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(o=this.callbacks).onError)==null||e.call(o,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Kt(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var t,o;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(o=(t=this.callbacks).onError)==null||o.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}updateConfig(t){this.config={...this.config,...t},this.client=new Kt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}async sendMessage(t,o){var c,f,w,u,v;let e=t.trim();if(!e)return;(c=this.abortController)==null||c.abort();let r=Dn(),s=_n(),i={id:r,role:"user",content:e,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1};this.appendMessage(i),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:l.signal,assistantMessageId:s},this.handleEvent)}catch(g){let N={id:s,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(N),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(w=(f=this.callbacks).onError)==null||w.call(f,g):(v=(u=this.callbacks).onError)==null||v.call(u,new Error(String(g)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var r;return{...e,streaming:!1,sequence:(r=e.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){this.streaming!==t&&(this.streaming=t,this.callbacks.onStreamingChanged(t))}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),e=this.messages.findIndex(r=>r.id===o.id);if(e===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===e?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,e)=>{var d,c;let r=new Date(o.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,l=(c=e.sequence)!=null?c:0;return i!==l?i-l:o.id.localeCompare(e.id)})}};var jn=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Er=n=>{var s,i,l;let t=(s=n==null?void 0:n.colorScheme)!=null?s:"light",o=(i=n==null?void 0:n.theme)!=null?i:{},e=(l=n==null?void 0:n.darkTheme)!=null?l:o;return t==="light"?o:t==="dark"||jn()==="dark"?e:o},Js=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{n(jn())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(jn());o.addEventListener?(o.addEventListener("change",e),t.push(()=>o.removeEventListener("change",e))):o.addListener&&(o.addListener(e),t.push(()=>o.removeListener(e)))}return()=>{t.forEach(o=>o())}},Sn=(n,t)=>{let o=Er(t);Object.entries(o).forEach(([e,r])=>{if(r==null||r==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${s}`,String(r))})};import*as Mr from"lucide";var we=(n,t=24,o="currentColor",e=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Mr[r];return s?kr(s,t,o,e):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function kr(n,t,o,e){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(e)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([c,f])=>{c!=="stroke"&&d.setAttribute(c,String(f))}),r.appendChild(d)}}}),r}var h=(n,t)=>{let o=document.createElement(n);return t&&(o.className=t),o};import{Idiomorph as Wr}from"idiomorph";var Ys=(n,t,o={})=>{let{preserveTypingAnimation:e=!0}=o;Wr.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&e&&r.classList.contains("tvw-animate-typing"))return!1}}})};var Qe={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var xt={"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 sn=(n,t)=>{let o=h("button");o.type="button",o.innerHTML=`
6
+ `);i=(it=he.pop())!=null?it:"";for(let Ie of he){let fe=Ie.split(`
7
+ `),Ae="message",be="";for(let te of fe)te.startsWith("event:")?Ae=te.replace("event:","").trim():te.startsWith("data:")&&(be+=te.replace("data:","").trim());if(!be)continue;let H;try{H=JSON.parse(be)}catch(te){o({type:"error",error:te instanceof Error?te:new Error("Failed to parse chat stream payload")});continue}let ft=Ae!=="message"?Ae:(oe=H.type)!=null?oe:"message";if(this.parseSSEEvent){v.current=p;let te=await this.handleCustomSSEEvent(H,o,v,g,c);if(v.current&&!p&&(p=v.current),te)continue}if(ft==="reason_start"){let te=(D=k(H,!0))!=null?D:`reason-${c()}`,W=Y(te);W.reasoning=(Ve=W.reasoning)!=null?Ve:{id:te,status:"streaming",chunks:[]},W.reasoning.startedAt=(at=W.reasoning.startedAt)!=null?at:q((nt=H.startedAt)!=null?nt:H.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",g(W)}else if(ft==="reason_chunk"){let te=(Et=(Tt=k(H,!1))!=null?Tt:k(H,!0))!=null?Et:`reason-${c()}`,W=Y(te);W.reasoning=(_=W.reasoning)!=null?_:{id:te,status:"streaming",chunks:[]},W.reasoning.startedAt=(Ge=W.reasoning.startedAt)!=null?Ge:q((ue=H.startedAt)!=null?ue:H.timestamp);let E=(Ze=(_e=(Qe=H.reasoningText)!=null?Qe:H.text)!=null?_e:H.delta)!=null?Ze:"";if(E&&H.hidden!==!0&&W.reasoning.chunks.push(String(E)),W.reasoning.status=H.done?"complete":"streaming",H.done){W.reasoning.completedAt=q((P=H.completedAt)!=null?P:H.timestamp);let K=($e=W.reasoning.startedAt)!=null?$e:Date.now();W.reasoning.durationMs=Math.max(0,((ut=W.reasoning.completedAt)!=null?ut:Date.now())-K)}W.streaming=W.reasoning.status!=="complete",g(W)}else if(ft==="reason_complete"){let te=(Lt=(pt=k(H,!1))!=null?pt:k(H,!0))!=null?Lt:`reason-${c()}`,W=m.get(te);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=q((bt=H.completedAt)!=null?bt:H.timestamp);let K=(Ct=W.reasoning.startedAt)!=null?Ct:Date.now();W.reasoning.durationMs=Math.max(0,((Fe=W.reasoning.completedAt)!=null?Fe:Date.now())-K),W.streaming=!1,g(W)}let E=R(H);E&&M.byStep.delete(E)}else if(ft==="tool_start"){let te=(et=j(H,!0))!=null?et:`tool-${c()}`,W=O(te),E=(xt=W.toolCall)!=null?xt:{id:te,status:"pending"};E.name=(Me=H.toolName)!=null?Me:E.name,E.status="running",H.args!==void 0&&(E.args=H.args),E.startedAt=(b=E.startedAt)!=null?b:q((Le=H.startedAt)!=null?Le:H.timestamp),E.completedAt=void 0,E.durationMs=void 0,W.toolCall=E,W.streaming=!0,g(W)}else if(ft==="tool_chunk"){let te=(Ee=(Be=j(H,!1))!=null?Be:j(H,!0))!=null?Ee:`tool-${c()}`,W=O(te),E=(Ke=W.toolCall)!=null?Ke:{id:te,status:"running"};E.startedAt=(st=E.startedAt)!=null?st:q((ot=H.startedAt)!=null?ot:H.timestamp);let K=(Mt=(mt=(gt=H.text)!=null?gt:H.delta)!=null?mt:H.message)!=null?Mt:"";K&&(E.chunks=(Rt=E.chunks)!=null?Rt:[],E.chunks.push(String(K))),E.status="running",W.toolCall=E,W.streaming=!0,g(W)}else if(ft==="tool_complete"){let te=(Nt=(zt=j(H,!1))!=null?zt:j(H,!0))!=null?Nt:`tool-${c()}`,W=O(te),E=(He=W.toolCall)!=null?He:{id:te,status:"running"};if(E.status="complete",H.result!==void 0&&(E.result=H.result),typeof H.duration=="number"&&(E.duration=H.duration),E.completedAt=q((ht=H.completedAt)!=null?ht:H.timestamp),typeof H.duration=="number")E.durationMs=H.duration;else{let ke=(pe=E.startedAt)!=null?pe:Date.now();E.durationMs=Math.max(0,((Pt=E.completedAt)!=null?Pt:Date.now())-ke)}W.toolCall=E,W.streaming=!1,g(W);let K=y(H);K&&f.byCall.delete(K)}else if(ft==="step_chunk"){let te=H.stepType,W=H.executionType;if(te==="tool"||W==="context")continue;let E=F(),K=(fn=(hn=(Ht=(Bt=H.text)!=null?Bt:H.delta)!=null?Ht:H.content)!=null?hn:H.chunk)!=null?fn:"";if(K){let ye=((Qt=V.get(E.id))!=null?Qt:"")+K;E.rawContent=ye,J.has(E.id)||J.set(E.id,this.createStreamParser());let ie=J.get(E.id),Q=ye.trim().startsWith("{")||ye.trim().startsWith("[");if(Q&&V.set(E.id,ye),ie.__isPlainTextParser===!0){E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E);continue}let je=ie.processChunk(ye);if(je instanceof Promise)je.then(ge=>{var ve;let Ce=typeof ge=="string"?ge:(ve=ge==null?void 0:ge.text)!=null?ve:null;if(Ce!==null&&Ce.trim()!==""){let xe=p;xe&&xe.id===E.id&&(xe.content=Ce,g(xe))}else if(!Q&&!ye.trim().startsWith("<")){let xe=p;xe&&xe.id===E.id&&(xe.content+=K,V.delete(xe.id),J.delete(xe.id),xe.rawContent=void 0,g(xe))}}).catch(()=>{E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E)});else{let ge=typeof je=="string"?je:(Ot=je==null?void 0:je.text)!=null?Ot:null;ge!==null&&ge.trim()!==""?(E.content=ge,g(E)):!Q&&!ye.trim().startsWith("<")&&(E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E))}}if(H.isComplete){let ke=(wn=(It=H.result)==null?void 0:It.response)!=null?wn:E.content;if(ke){let ye=V.get(E.id),ie=ye!=null?ye:U(ke);E.rawContent=ie;let Q=J.get(E.id),Re=null,je=!1;if(Q&&(Re=Q.getExtractedText(),Re===null&&(Re=En(ie)),Re===null)){let ge=Q.processChunk(ie);ge instanceof Promise?(je=!0,ge.then(Ce=>{var xe;let ve=typeof Ce=="string"?Ce:(xe=Ce==null?void 0:Ce.text)!=null?xe:null;if(ve!==null){let Ue=p;Ue&&Ue.id===E.id&&(Ue.content=ve,Ue.streaming=!1,J.delete(Ue.id),V.delete(Ue.id),g(Ue))}})):Re=typeof ge=="string"?ge:(yn=ge==null?void 0:ge.text)!=null?yn:null}if(!je){Re!==null&&Re.trim()!==""?E.content=Re:V.has(E.id)||(E.content=U(ke));let ge=J.get(E.id);if(ge){let Ce=(vn=ge.close)==null?void 0:vn.call(ge);Ce instanceof Promise&&Ce.catch(()=>{}),J.delete(E.id)}V.delete(E.id),E.streaming=!1,g(E)}}}}else if(ft==="step_complete"){let te=H.stepType,W=H.executionType;if(te==="tool"||W==="context")continue;let E=(Fn=H.result)==null?void 0:Fn.response,K=F();if(E!=null){let ke=J.get(K.id),ye=!1,ie=!1;if(ke){let Q=ke.getExtractedText(),Re=V.get(K.id),je=Re!=null?Re:U(E);if(K.rawContent=je,Q!==null&&Q.trim()!=="")K.content=Q,ye=!0;else{let ge=En(je);if(ge!==null)K.content=ge,ye=!0;else{let Ce=ke.processChunk(je);if(Ce instanceof Promise)ie=!0,Ce.then(ve=>{var Ue;let xe=typeof ve=="string"?ve:(Ue=ve==null?void 0:ve.text)!=null?Ue:null;if(xe!==null&&xe.trim()!==""){let lt=p;lt&&lt.id===K.id&&(lt.content=xe,lt.streaming=!1,J.delete(lt.id),V.delete(lt.id),g(lt))}else{let lt=ke.getExtractedText(),vt=p;vt&&vt.id===K.id&&(lt!==null&&lt.trim()!==""?vt.content=lt:V.has(vt.id)||(vt.content=U(E)),vt.streaming=!1,J.delete(vt.id),V.delete(vt.id),g(vt))}});else{let ve=typeof Ce=="string"?Ce:(Dt=Ce==null?void 0:Ce.text)!=null?Dt:null;if(ve!==null&&ve.trim()!=="")K.content=ve,ye=!0;else{let xe=ke.getExtractedText();xe!==null&&xe.trim()!==""&&(K.content=xe,ye=!0)}}}}}if(!ie){if(!K.rawContent){let Q=V.get(K.id);K.rawContent=Q!=null?Q:U(E)}if(!ye&&!V.has(K.id)&&(K.content=U(E)),ke){let Q=(_t=ke.close)==null?void 0:_t.call(ke);Q instanceof Promise&&Q.catch(()=>{})}J.delete(K.id),V.delete(K.id),K.streaming=!1,g(K)}}else J.delete(K.id),V.delete(K.id),K.streaming=!1,g(K)}else if(ft==="flow_complete"){let te=(Ye=H.result)==null?void 0:Ye.response;if(te!=null){let W=F(),E=V.get(W.id),K=E!=null?E:U(te);W.rawContent=K;let ke=U(te),ye=J.get(W.id);if(ye){let Re=En(K);if(Re!==null)ke=Re;else{let je=ye.processChunk(K);je instanceof Promise&&je.then(Ce=>{var xe;let ve=typeof Ce=="string"?Ce:(xe=Ce==null?void 0:Ce.text)!=null?xe:null;if(ve!==null){let Ue=p;Ue&&Ue.id===W.id&&(Ue.content=ve,Ue.streaming=!1,g(Ue))}});let ge=ye.getExtractedText();ge!==null&&(ke=ge)}}J.delete(W.id),V.delete(W.id);let ie=ke!==W.content,Q=W.streaming!==!1;ie&&(W.content=ke),W.streaming=!1,(ie||Q)&&g(W)}else if(p!==null){let W=p;J.delete(W.id),V.delete(W.id),W.streaming!==!1&&(W.streaming=!1,g(W))}o({type:"status",status:"idle"})}else ft==="error"&&H.error&&o({type:"error",error:H.error instanceof Error?H.error:new Error(String(H.error))})}}}};function Hr(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function Un(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function zn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var dn=class{constructor(t={},o){this.config=t;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=t=>{var o,e;t.type==="message"?this.upsertMessage(t.message):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null)):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(o=this.callbacks).onError)==null||e.call(o,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Jt(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var t,o;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(o=(t=this.callbacks).onError)==null||o.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}updateConfig(t){this.config={...this.config,...t},this.client=new Jt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}async sendMessage(t,o){var c,w,g,p,v;let e=t.trim();if(!e)return;(c=this.abortController)==null||c.abort();let r=Un(),s=zn(),i={id:r,role:"user",content:e,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1};this.appendMessage(i),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:l.signal,assistantMessageId:s},this.handleEvent)}catch(m){let N={id:s,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(N),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m instanceof Error?(g=(w=this.callbacks).onError)==null||g.call(w,m):(v=(p=this.callbacks).onError)==null||v.call(p,new Error(String(m)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var r;return{...e,streaming:!1,sequence:(r=e.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){this.streaming!==t&&(this.streaming=t,this.callbacks.onStreamingChanged(t))}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),e=this.messages.findIndex(r=>r.id===o.id);if(e===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===e?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,e)=>{var d,c;let r=new Date(o.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,l=(c=e.sequence)!=null?c:0;return i!==l?i-l:o.id.localeCompare(e.id)})}};var Jn=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ir=n=>{var s,i,l;let t=(s=n==null?void 0:n.colorScheme)!=null?s:"light",o=(i=n==null?void 0:n.theme)!=null?i:{},e=(l=n==null?void 0:n.darkTheme)!=null?l:o;return t==="light"?o:t==="dark"||Jn()==="dark"?e:o},Gs=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{n(Jn())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(Jn());o.addEventListener?(o.addEventListener("change",e),t.push(()=>o.removeEventListener("change",e))):o.addListener&&(o.addListener(e),t.push(()=>o.removeListener(e)))}return()=>{t.forEach(o=>o())}},Mn=(n,t)=>{let o=Ir(t);Object.entries(o).forEach(([e,r])=>{if(r==null||r==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${s}`,String(r))})};import*as Rr from"lucide";var de=(n,t=24,o="currentColor",e=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Rr[r];return s?Pr(s,t,o,e):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function Pr(n,t,o,e){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(e)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([c,w])=>{c!=="stroke"&&d.setAttribute(c,String(w))}),r.appendChild(d)}}}),r}var h=(n,t)=>{let o=document.createElement(n);return t&&(o.className=t),o};import{Idiomorph as $r}from"idiomorph";var Qs=(n,t,o={})=>{let{preserveTypingAnimation:e=!0}=o;$r.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&e&&r.classList.contains("tvw-animate-typing"))return!1}}})};var tt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var At={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var cn=(n,t)=>{let o=h("button");o.type="button",o.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,23 +12,23 @@ import{Marked as mr}from"marked";var hr=n=>{if(n)return n},vn=n=>{var r,s;let t=
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
- `,o.addEventListener("click",t);let e=s=>{var m,k,C,y,F,b,T,K,J,j,O,q;let i=(m=s.launcher)!=null?m:{},l=o.querySelector("[data-role='launcher-title']");l&&(l.textContent=(k=i.title)!=null?k:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(C=i.subtitle)!=null?C:"Get answers fast");let c=o.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let f=o.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let U=(y=i.agentIconSize)!=null?y:"40px";if(f.style.height=U,f.style.width=U,f.innerHTML="",i.agentIconName){let Y=parseFloat(U)||24,Q=we(i.agentIconName,Y*.6,"#ffffff",2);Q?(f.appendChild(Q),f.style.display=""):(f.textContent=(F=i.agentIconText)!=null?F:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(b=i.agentIconText)!=null?b:"\u{1F4AC}",f.style.display="")}let w=o.querySelector("[data-role='launcher-image']");if(w){let U=(T=i.agentIconSize)!=null?T:"40px";w.style.height=U,w.style.width=U,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(w.src=i.iconUrl,w.style.display="block"):w.style.display="none"}let u=o.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let U=(K=i.callToActionIconSize)!=null?K:"32px";u.style.height=U,u.style.width=U,i.callToActionIconBackgroundColor?(u.style.backgroundColor=i.callToActionIconBackgroundColor,u.classList.remove("tvw-bg-cw-primary")):(u.style.backgroundColor="",u.classList.add("tvw-bg-cw-primary"));let Y=0;if(i.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=i.callToActionIconPadding,Y=(parseFloat(i.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),i.callToActionIconHidden)u.style.display="none";else if(u.style.display="",u.innerHTML="",i.callToActionIconName){let Q=parseFloat(U)||24,st=Math.max(Q-Y,8),se=we(i.callToActionIconName,st,"currentColor",2);se?u.appendChild(se):u.textContent=(J=i.callToActionIconText)!=null?J:"\u2197"}else u.textContent=(j=i.callToActionIconText)!=null?j:"\u2197"}let v=i.position&&xt[i.position]?xt[i.position]:xt["bottom-right"],g="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-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${g} ${v}`;let N="1px solid #e5e7eb",I="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(O=i.border)!=null?O:N,o.style.boxShadow=(q=i.shadow)!=null?q:I},r=()=>{o.removeEventListener("click",t),o.remove()};return n&&e(n),{element:o,update:e,destroy:r}};var Nt=n=>{var j,O,q,U,Y,Q,st,se,D,Ke,Ze,rt,St,At,_,fe,Xe,Ve,Je,it,P,Pe,ut,pt,Wt,yt,Ie,Ge,vt,at,Ee,B;let{config:t,showClose:o=!0}=n,e=h("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"),r=(j=t==null?void 0:t.launcher)!=null?j:{},s=(O=r.headerIconSize)!=null?O:"48px",i=(q=r.closeButtonSize)!=null?q:"32px",l=(U=r.closeButtonPlacement)!=null?U:"inline",d=(Y=r.headerIconHidden)!=null?Y:!1,c=r.headerIconName,f=h("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=s,f.style.width=s,!d)if(c){let ee=parseFloat(s)||24,ke=we(c,ee*.6,"#ffffff",2);ke?f.replaceChildren(ke):f.textContent=(st=(Q=t==null?void 0:t.launcher)==null?void 0:Q.agentIconText)!=null?st:"\u{1F4AC}"}else if((se=t==null?void 0:t.launcher)!=null&&se.iconUrl){let ee=h("img");ee.src=t.launcher.iconUrl,ee.alt="",ee.className="tvw-rounded-xl tvw-object-cover",ee.style.height=s,ee.style.width=s,f.replaceChildren(ee)}else f.textContent=(Ke=(D=t==null?void 0:t.launcher)==null?void 0:D.agentIconText)!=null?Ke:"\u{1F4AC}";let w=h("div","tvw-flex tvw-flex-col"),u=h("span","tvw-text-base tvw-font-semibold");u.textContent=(rt=(Ze=t==null?void 0:t.launcher)==null?void 0:Ze.title)!=null?rt:"Chat Assistant";let v=h("span","tvw-text-xs tvw-text-cw-muted");v.textContent=(At=(St=t==null?void 0:t.launcher)==null?void 0:St.subtitle)!=null?At:"Here to help you get answers fast",w.append(u,v),d?e.append(w):e.append(f,w);let g=(_=r.clearChat)!=null?_:{},N=(fe=g.enabled)!=null?fe:!0,I=(Xe=g.placement)!=null?Xe:"inline",m=null,k=null;if(N){let ee=(Ve=g.size)!=null?Ve:"32px",ke=(Je=g.iconName)!=null?Je:"refresh-cw",Be=(it=g.iconColor)!=null?it:"",et=(P=g.backgroundColor)!=null?P:"",De=(Pe=g.borderWidth)!=null?Pe:"",tt=(ut=g.borderColor)!=null?ut:"",Tt=(pt=g.borderRadius)!=null?pt:"",gt=(Wt=g.paddingX)!=null?Wt:"",Bt=(yt=g.paddingY)!=null?yt:"",Ht=(Ie=g.tooltipText)!=null?Ie:"Clear chat",zt=(Ge=g.showTooltip)!=null?Ge:!0;k=h("div",I==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),I==="top-right"&&(k.style.right="48px"),m=h("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=ee,m.style.width=ee,m.type="button",m.setAttribute("aria-label",Ht);let Rt=we(ke,"20px",Be||"",2);if(Rt&&m.appendChild(Rt),Be&&(m.style.color=Be,m.classList.remove("tvw-text-cw-muted")),et&&(m.style.backgroundColor=et,m.classList.remove("hover:tvw-bg-gray-100")),De||tt){let We=De||"0px",ue=tt||"transparent";m.style.border=`${We} solid ${ue}`,m.classList.remove("tvw-border-none")}if(Tt&&(m.style.borderRadius=Tt,m.classList.remove("tvw-rounded-full")),gt?(m.style.paddingLeft=gt,m.style.paddingRight=gt):(m.style.paddingLeft="",m.style.paddingRight=""),Bt?(m.style.paddingTop=Bt,m.style.paddingBottom=Bt):(m.style.paddingTop="",m.style.paddingBottom=""),k.appendChild(m),zt&&Ht&&m&&k){let We=null,ue=()=>{if(We||!m)return;We=h("div","tvw-clear-chat-tooltip"),We.textContent=Ht;let Pt=h("div");Pt.className="tvw-clear-chat-tooltip-arrow",We.appendChild(Pt);let mt=m.getBoundingClientRect();We.style.position="fixed",We.style.left=`${mt.left+mt.width/2}px`,We.style.top=`${mt.top-8}px`,We.style.transform="translate(-50%, -100%)",document.body.appendChild(We)},bt=()=>{We&&We.parentNode&&(We.parentNode.removeChild(We),We=null)};k.addEventListener("mouseenter",ue),k.addEventListener("mouseleave",bt),m.addEventListener("focus",ue),m.addEventListener("blur",bt),k._cleanupTooltip=()=>{bt(),k&&(k.removeEventListener("mouseenter",ue),k.removeEventListener("mouseleave",bt)),m&&(m.removeEventListener("focus",ue),m.removeEventListener("blur",bt))}}I==="inline"&&e.appendChild(k)}let C=h("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":N&&I==="inline"?"":"tvw-ml-auto"),y=h("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");y.style.height=i,y.style.width=i,y.type="button";let F=(vt=r.closeButtonTooltipText)!=null?vt:"Close chat",b=(at=r.closeButtonShowTooltip)!=null?at:!0;y.setAttribute("aria-label",F),y.style.display=o?"":"none";let T=(Ee=r.closeButtonIconName)!=null?Ee:"x",K=(B=r.closeButtonIconText)!=null?B:"\xD7",J=we(T,"20px",r.closeButtonColor||"",2);if(J?y.appendChild(J):y.textContent=K,r.closeButtonColor?(y.style.color=r.closeButtonColor,y.classList.remove("tvw-text-cw-muted")):(y.style.color="",y.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(y.style.backgroundColor=r.closeButtonBackgroundColor,y.classList.remove("hover:tvw-bg-gray-100")):(y.style.backgroundColor="",y.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let ee=r.closeButtonBorderWidth||"0px",ke=r.closeButtonBorderColor||"transparent";y.style.border=`${ee} solid ${ke}`,y.classList.remove("tvw-border-none")}else y.style.border="",y.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(y.style.borderRadius=r.closeButtonBorderRadius,y.classList.remove("tvw-rounded-full")):(y.style.borderRadius="",y.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(y.style.paddingLeft=r.closeButtonPaddingX,y.style.paddingRight=r.closeButtonPaddingX):(y.style.paddingLeft="",y.style.paddingRight=""),r.closeButtonPaddingY?(y.style.paddingTop=r.closeButtonPaddingY,y.style.paddingBottom=r.closeButtonPaddingY):(y.style.paddingTop="",y.style.paddingBottom=""),C.appendChild(y),b&&F){let ee=null,ke=()=>{if(ee)return;ee=h("div","tvw-clear-chat-tooltip"),ee.textContent=F;let et=h("div");et.className="tvw-clear-chat-tooltip-arrow",ee.appendChild(et);let De=y.getBoundingClientRect();ee.style.position="fixed",ee.style.left=`${De.left+De.width/2}px`,ee.style.top=`${De.top-8}px`,ee.style.transform="translate(-50%, -100%)",document.body.appendChild(ee)},Be=()=>{ee&&ee.parentNode&&(ee.parentNode.removeChild(ee),ee=null)};C.addEventListener("mouseenter",ke),C.addEventListener("mouseleave",Be),y.addEventListener("focus",ke),y.addEventListener("blur",Be),C._cleanupTooltip=()=>{Be(),C.removeEventListener("mouseenter",ke),C.removeEventListener("mouseleave",Be),y.removeEventListener("focus",ke),y.removeEventListener("blur",Be)}}return l!=="top-right"&&e.appendChild(C),{header:e,iconHolder:f,headerTitle:u,headerSubtitle:v,closeButton:y,closeButtonWrapper:C,clearChatButton:m,clearChatButtonWrapper:k}},rn=(n,t,o)=>{var i,l,d,c;let e=(i=o==null?void 0:o.launcher)!=null?i:{},r=(l=e.closeButtonPlacement)!=null?l:"inline",s=(c=(d=e.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),r==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var Ks=n=>Nt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Xs=n=>{var g,N,I,m;let{config:t,showClose:o=!0,onClose:e}=n,r=(g=t==null?void 0:t.launcher)!=null?g:{},s=h("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=h("span","tvw-text-base tvw-font-semibold");i.textContent=(N=r.title)!=null?N:"Chat Assistant",s.appendChild(i);let l=(I=r.closeButtonSize)!=null?I:"32px",d=h("div",""),c=h("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");c.style.height=l,c.style.width=l,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=o?"":"none";let f=(m=r.closeButtonIconName)!=null?m:"x",w=we(f,"20px",r.closeButtonColor||"",2);w?c.appendChild(w):c.textContent="\xD7",e&&c.addEventListener("click",e),d.appendChild(c),s.appendChild(d);let u=h("div");u.style.display="none";let v=h("span");return v.style.display="none",{header:s,iconHolder:u,headerTitle:i,headerSubtitle:v,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Vs=n=>{var y,F,b,T,K,J,j,O;let{config:t,showClose:o=!0,onClose:e,onClearChat:r}=n,s=(y=t==null?void 0:t.launcher)!=null?y:{},i=h("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=h("div","tvw-flex tvw-items-center tvw-gap-3"),d=(F=s.headerIconSize)!=null?F:"56px",c=h("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let f=s.headerIconName;if(f){let q=parseFloat(d)||24,U=we(f,q*.5,"#ffffff",2);U?c.replaceChildren(U):c.textContent=(b=s.agentIconText)!=null?b:"\u{1F4AC}"}else if(s.iconUrl){let q=h("img");q.src=s.iconUrl,q.alt="",q.className="tvw-rounded-xl tvw-object-cover",q.style.height=d,q.style.width=d,c.replaceChildren(q)}else c.textContent=(T=s.agentIconText)!=null?T:"\u{1F4AC}";let w=h("div","tvw-flex tvw-flex-col tvw-flex-1"),u=h("span","tvw-text-lg tvw-font-semibold");u.textContent=(K=s.title)!=null?K:"Chat Assistant";let v=h("span","tvw-text-sm tvw-text-cw-muted");v.textContent=(J=s.subtitle)!=null?J:"Here to help you get answers fast",w.append(u,v),l.append(c,w);let g=(j=s.closeButtonSize)!=null?j:"32px",N=h("div",""),I=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");I.style.height=g,I.style.width=g,I.type="button",I.setAttribute("aria-label","Close chat"),I.style.display=o?"":"none";let m=(O=s.closeButtonIconName)!=null?O:"x",k=we(m,"20px",s.closeButtonColor||"",2);k?I.appendChild(k):I.textContent="\xD7",e&&I.addEventListener("click",e),N.appendChild(I),l.appendChild(N),i.appendChild(l);let C=h("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return C.textContent="Online and ready to help",i.appendChild(C),{header:i,iconHolder:c,headerTitle:u,headerSubtitle:v,closeButton:I,closeButtonWrapper:N,clearChatButton:null,clearChatButtonWrapper:null}},qn={default:Ks,minimal:Xs,expanded:Vs},Gs=n=>{var t;return(t=qn[n])!=null?t:qn.default},an=(n,t,o)=>{var i,l,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=h("div");f.style.display="none";let w=h("span"),u=h("span"),v=h("button");v.style.display="none";let g=h("div");return g.style.display="none",{header:c,iconHolder:f,headerTitle:w,headerSubtitle:u,closeButton:v,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",s=Gs(e)({config:n,showClose:(d=(l=t==null?void 0:t.showCloseButton)!=null?l:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Lr=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'}},ln=n=>{var Q,st,se,D,Ke,Ze,rt,St,At,_,fe,Xe,Ve,Je,it,P,Pe,ut,pt,Wt,yt,Ie,Ge,vt,at;let{config:t}=n,o=h("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=h("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((Q=t==null?void 0:t.voiceRecognition)==null?void 0:Q.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=h("form",`tvw-widget-composer tvw-flex tvw-items-end ${r&&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`);d.style.outline="none";let c=h("textarea");c.placeholder=(se=(st=t==null?void 0:t.copy)==null?void 0:st.inputPlaceholder)!=null?se:"Type your message\u2026",c.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",c.rows=1;let f=(Ke=(D=t==null?void 0:t.theme)==null?void 0:D.inputFontFamily)!=null?Ke:"sans-serif",w=(rt=(Ze=t==null?void 0:t.theme)==null?void 0:Ze.inputFontWeight)!=null?rt:"400";c.style.fontFamily=Lr(f),c.style.fontWeight=w,c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.addEventListener("focus",()=>{c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.style.boxShadow="none"}),c.addEventListener("blur",()=>{c.style.border="none",c.style.outline="none"});let u=(St=t==null?void 0:t.sendButton)!=null?St:{},v=(At=u.useIcon)!=null?At:!1,g=(_=u.iconText)!=null?_:"\u2191",N=u.iconName,I=(fe=u.tooltipText)!=null?fe:"Send message",m=(Xe=u.showTooltip)!=null?Xe:!1,k=(Ve=u.size)!=null?Ve:"40px",C=u.backgroundColor,y=u.textColor,F=h("div","tvw-send-button-wrapper"),b=h("button",v?"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(b.type="submit",v){if(b.style.width=k,b.style.height=k,b.style.minWidth=k,b.style.minHeight=k,b.style.fontSize="18px",b.style.lineHeight="1",b.innerHTML="",N){let Ee=parseFloat(k)||24,B=y&&typeof y=="string"&&y.trim()?y.trim():"currentColor",ee=we(N,Ee,B,2);ee?(b.appendChild(ee),b.style.color=B):(b.textContent=g,y?b.style.color=y:b.classList.add("tvw-text-white"))}else b.textContent=g,y?b.style.color=y:b.classList.add("tvw-text-white");C?b.style.backgroundColor=C:b.classList.add("tvw-bg-cw-primary")}else b.textContent=(it=(Je=t==null?void 0:t.copy)==null?void 0:Je.sendButtonLabel)!=null?it:"Send",y?b.style.color=y:b.classList.add("tvw-text-white");if(u.borderWidth&&(b.style.borderWidth=u.borderWidth,b.style.borderStyle="solid"),u.borderColor&&(b.style.borderColor=u.borderColor),u.paddingX?(b.style.paddingLeft=u.paddingX,b.style.paddingRight=u.paddingX):(b.style.paddingLeft="",b.style.paddingRight=""),u.paddingY?(b.style.paddingTop=u.paddingY,b.style.paddingBottom=u.paddingY):(b.style.paddingTop="",b.style.paddingBottom=""),m&&I){let Ee=h("div","tvw-send-button-tooltip");Ee.textContent=I,F.appendChild(Ee)}F.appendChild(b);let T=(P=t==null?void 0:t.voiceRecognition)!=null?P:{},K=T.enabled===!0,J=null,j=null,O=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(K&&O){j=h("div","tvw-send-button-wrapper"),J=h("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),J.type="button",J.setAttribute("aria-label","Start voice recognition");let Ee=(Pe=T.iconName)!=null?Pe:"mic",B=(ut=T.iconSize)!=null?ut:k,ee=parseFloat(B)||24,ke=(pt=T.backgroundColor)!=null?pt:C,Be=(Wt=T.iconColor)!=null?Wt:y;J.style.width=B,J.style.height=B,J.style.minWidth=B,J.style.minHeight=B,J.style.fontSize="18px",J.style.lineHeight="1";let et=Be||"currentColor",De=we(Ee,ee,et,1.5);De?(J.appendChild(De),J.style.color=et):(J.textContent="\u{1F3A4}",J.style.color=et),ke?J.style.backgroundColor=ke:J.classList.add("tvw-bg-cw-primary"),Be?J.style.color=Be:!Be&&!y&&J.classList.add("tvw-text-white"),T.borderWidth&&(J.style.borderWidth=T.borderWidth,J.style.borderStyle="solid"),T.borderColor&&(J.style.borderColor=T.borderColor),T.paddingX&&(J.style.paddingLeft=T.paddingX,J.style.paddingRight=T.paddingX),T.paddingY&&(J.style.paddingTop=T.paddingY,J.style.paddingBottom=T.paddingY),j.appendChild(J);let tt=(yt=T.tooltipText)!=null?yt:"Start voice recognition";if(((Ie=T.showTooltip)!=null?Ie:!1)&&tt){let gt=h("div","tvw-send-button-tooltip");gt.textContent=tt,j.appendChild(gt)}}d.addEventListener("click",Ee=>{Ee.target!==b&&Ee.target!==F&&Ee.target!==J&&Ee.target!==j&&c.focus()}),d.append(c),j&&d.append(j),d.append(F);let q=h("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),U=(Ge=t==null?void 0:t.statusIndicator)!=null?Ge:{},Y=(vt=U.visible)!=null?vt:!0;return q.style.display=Y?"":"none",q.textContent=(at=U.idleText)!=null?at:"Online",o.append(e,d,q),{footer:o,suggestions:e,composerForm:d,textarea:c,sendButton:b,sendButtonWrapper:F,micButton:J,micButtonWrapper:j,statusText:q}};var Qs=n=>{var d,c,f,w,u,v,g;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let N=h("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),I=h("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),m=(w=(f=n==null?void 0:n.launcher)==null?void 0:f.width)!=null?w:"100%";return N.style.width=m,I.style.width="100%",N.appendChild(I),{wrapper:N,panel:I}}let o=(u=n==null?void 0:n.launcher)!=null?u:{},e=o.position&&xt[o.position]?xt[o.position]:xt["bottom-right"],r=h("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=h("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(g=(v=n==null?void 0:n.launcher)==null?void 0:v.width)!=null?g:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,r.appendChild(s),{wrapper:r,panel:s}},Zs=(n,t=!0)=>{var w,u,v,g,N;let o=h("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"),e=(w=n==null?void 0:n.layout)==null?void 0:w.header,r=e?an(n,e,{showClose:t}):Nt({config:n,showClose:t}),s=h("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=h("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=h("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(v=(u=n==null?void 0:n.copy)==null?void 0:u.welcomeTitle)!=null?v:"Hello \u{1F44B}";let d=h("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");d.textContent=(N=(g=n==null?void 0:n.copy)==null?void 0:g.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",i.append(l,d);let c=h("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,c);let f=ln({config:n});return rn(o,r,n),o.append(s,f.footer),{container:o,body:s,messagesWrapper:c,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:d,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:f.footer}};var An=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(t),n.appendChild(o),n.appendChild(e),n.appendChild(r),n},Br=(n,t)=>{let o=h("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"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let r=h("img");r.src=e,r.alt=t==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=e,o.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},er=(n,t)=>{let o=h("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?o.textContent=t.format(e):o.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Hr=(n,t="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.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:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.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 o},tr=(n,t,o)=>{var g,N,I,m,k,C;let e=(g=t.showCopy)!=null?g:!0,r=(N=t.showUpvote)!=null?N:!0,s=(I=t.showDownvote)!=null?I:!0,i=(m=t.visibility)!=null?m:"hover",l=(k=t.align)!=null?k:"right",d=(C=t.layout)!=null?C:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],w=h("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);w.id=`actions-${n.id}`,w.setAttribute("data-actions-for",n.id);let u=null,v=(y,F,b,T)=>{let K=document.createElement("button");K.className="tvw-message-action-btn",K.setAttribute("aria-label",F),K.setAttribute("title",F),T&&K.setAttribute("data-action",T);let J=we(y,14,"currentColor",2);return J&&K.appendChild(J),K.addEventListener("click",j=>{j.preventDefault(),j.stopPropagation(),b()}),K};if(e){let y=v("copy","Copy message",()=>{let F=n.content||"";navigator.clipboard.writeText(F).then(()=>{y.classList.add("tvw-message-action-success");let b=we("check",14,"currentColor",2);b&&(y.innerHTML="",y.appendChild(b)),setTimeout(()=>{y.classList.remove("tvw-message-action-success");let T=we("copy",14,"currentColor",2);T&&(y.innerHTML="",y.appendChild(T))},2e3)}).catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",b)}),o!=null&&o.onCopy&&o.onCopy(n),t.onCopy&&t.onCopy(n)},"copy");w.appendChild(y)}if(r){let y=v("thumbs-up","Upvote",()=>{if(u==="upvote")u=null,y.classList.remove("tvw-message-action-active");else{let b=w.querySelector('[data-action="downvote"]');b&&b.classList.remove("tvw-message-action-active"),u="upvote",y.classList.add("tvw-message-action-active");let T={type:"upvote",messageId:n.id,message:n};o!=null&&o.onFeedback&&o.onFeedback(T),t.onFeedback&&t.onFeedback(T)}},"upvote");w.appendChild(y)}if(s){let y=v("thumbs-down","Downvote",()=>{if(u==="downvote")u=null,y.classList.remove("tvw-message-action-active");else{let b=w.querySelector('[data-action="upvote"]');b&&b.classList.remove("tvw-message-action-active"),u="downvote",y.classList.add("tvw-message-action-active");let T={type:"downvote",messageId:n.id,message:n};o!=null&&o.onFeedback&&o.onFeedback(T),t.onFeedback&&t.onFeedback(T)}},"downvote");w.appendChild(y)}return w},dn=(n,t,o,e,r)=>{var C,y,F,b,T;let s=o!=null?o:{},i=(C=s.layout)!=null?C:"bubble",l=s.avatar,d=s.timestamp,c=(y=l==null?void 0:l.show)!=null?y:!1,f=(F=d==null?void 0:d.show)!=null?F:!1,w=(b=l==null?void 0:l.position)!=null?b:"left",u=(T=d==null?void 0:d.position)!=null?T:"below",v=Hr(n.role,i),g=h("div",v.join(" "));g.id=`bubble-${n.id}`,g.setAttribute("data-message-id",n.id);let N=document.createElement("div");if(N.innerHTML=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),f&&u==="inline"&&n.createdAt){let K=er(n,d);K.classList.add("tvw-ml-2","tvw-inline"),N.appendChild(K)}if(g.appendChild(N),f&&u==="below"&&n.createdAt){let K=er(n,d);K.classList.add("tvw-mt-1"),g.appendChild(K)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let K=An();g.appendChild(K)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let K=tr(n,e,r);g.appendChild(K)}if(!c||n.role==="system")return g;let m=h("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),k=Br(l,n.role);return w==="right"||w==="left"&&n.role==="user"?m.append(g,k):m.append(k,g),g.classList.remove("tvw-max-w-[85%]"),g.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),m},Rr=(n,t,o,e,r)=>{let s=o!=null?o:{};return n.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):dn(n,t,o,e,r)};var Un=new Set,zn=n=>{let t=n.reasoning,o=h("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(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),!t)return o;let e=Un.has(n.id),r=h("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");r.type="button",r.setAttribute("aria-expanded",e?"true":"false");let s=h("div","tvw-flex tvw-flex-col tvw-text-left"),i=h("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=h("span","tvw-text-xs tvw-text-cw-primary");l.textContent=qs(t),s.appendChild(l),t.status==="complete"?i.style.display="none":i.style.display="";let d=h("div","tvw-flex tvw-items-center"),f=we(e?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=e?"Hide":"Show";let w=h("div","tvw-flex tvw-items-center tvw-ml-auto");w.append(d),r.append(s,w);let u=h("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");u.style.display=e?"":"none";let v=t.chunks.join(""),g=h("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");g.textContent=v||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),u.appendChild(g);let N=()=>{r.setAttribute("aria-expanded",e?"true":"false"),d.innerHTML="";let k=we(e?"chevron-up":"chevron-down",16,"currentColor",2);k?d.appendChild(k):d.textContent=e?"Hide":"Show",u.style.display=e?"":"none"},I=()=>{e=!e,e?Un.add(n.id):Un.delete(n.id),N()};return r.addEventListener("pointerdown",m=>{m.preventDefault(),I()}),r.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),I())}),N(),o.append(r,u),o};var Jn=new Set,Yn=(n,t)=>{var I;let o=n.toolCall,e=(I=t==null?void 0:t.toolCall)!=null?I:{},r=h("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(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),e.backgroundColor&&(r.style.backgroundColor=e.backgroundColor),e.borderColor&&(r.style.borderColor=e.borderColor),e.borderWidth&&(r.style.borderWidth=e.borderWidth),e.borderRadius&&(r.style.borderRadius=e.borderRadius),!o)return r;let s=Jn.has(n.id),i=h("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"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let l=h("div","tvw-flex tvw-flex-col tvw-text-left"),d=h("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(d.style.color=e.headerTextColor),d.textContent=Us(o),l.appendChild(d);let c=h("div","tvw-flex tvw-items-center"),f=e.toggleTextColor||e.headerTextColor||"currentColor",w=we(s?"chevron-up":"chevron-down",16,f,2);w?c.appendChild(w):c.textContent=s?"Hide":"Show";let u=h("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");u.append(c),i.append(l,u);let v=h("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(v.style.display=s?"":"none",e.contentBackgroundColor&&(v.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(v.style.color=e.contentTextColor),e.contentPaddingX&&(v.style.paddingLeft=e.contentPaddingX,v.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(v.style.paddingTop=e.contentPaddingY,v.style.paddingBottom=e.contentPaddingY),o.name){let m=h("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?m.style.color=e.contentTextColor:e.headerTextColor&&(m.style.color=e.headerTextColor),m.textContent=o.name,v.appendChild(m)}if(o.args!==void 0){let m=h("div","tvw-space-y-1"),k=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(k.style.color=e.labelTextColor),k.textContent="Arguments";let C=h("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");C.style.fontSize="0.75rem",C.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(C.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(C.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(C.style.color=e.codeBlockTextColor),C.textContent=In(o.args),m.append(k,C),v.appendChild(m)}if(o.chunks&&o.chunks.length){let m=h("div","tvw-space-y-1"),k=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(k.style.color=e.labelTextColor),k.textContent="Activity";let C=h("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");C.style.fontSize="0.75rem",C.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(C.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(C.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(C.style.color=e.codeBlockTextColor),C.textContent=o.chunks.join(`
16
- `),m.append(k,C),v.appendChild(m)}if(o.status==="complete"&&o.result!==void 0){let m=h("div","tvw-space-y-1"),k=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(k.style.color=e.labelTextColor),k.textContent="Result";let C=h("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");C.style.fontSize="0.75rem",C.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(C.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(C.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(C.style.color=e.codeBlockTextColor),C.textContent=In(o.result),m.append(k,C),v.appendChild(m)}if(o.status==="complete"&&typeof o.duration=="number"){let m=h("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(m.style.color=e.contentTextColor),m.textContent=`Duration: ${o.duration}ms`,v.appendChild(m)}let g=()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let m=e.toggleTextColor||e.headerTextColor||"currentColor",k=we(s?"chevron-up":"chevron-down",16,m,2);k?c.appendChild(k):c.textContent=s?"Hide":"Show",v.style.display=s?"":"none"},N=()=>{s=!s,s?Jn.add(n.id):Jn.delete(n.id),g()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),N()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),N())}),g(),r.append(i,v),r};var nr=n=>{let t=[];return{buttons:t,render:(e,r,s,i,l)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:r?r.getMessages():[]).some(v=>v.role==="user"))return;let f=document.createDocumentFragment(),w=r?r.isStreaming():!1,u=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(v=>{let g=h("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");g.type="button",g.textContent=v,g.disabled=w,l!=null&&l.fontFamily&&(g.style.fontFamily=u(l.fontFamily)),l!=null&&l.fontWeight&&(g.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(g.style.paddingLeft=l.paddingX,g.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(g.style.paddingTop=l.paddingY,g.style.paddingBottom=l.paddingY),g.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(v))}),f.appendChild(g),t.push(g)}),n.appendChild(f)}}};var or={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"}},Kn=(n,t,o,e)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var g,N,I;if(s.dataset.enhanced==="true")return;let i=(g=s.dataset.tvForm)!=null?g:"init";s.dataset.enhanced="true";let l=(N=or[i])!=null?N:or.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=h("div","tvw-space-y-1"),c=h("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=l.title,d.appendChild(c),l.description){let m=h("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,d.appendChild(m)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var b,T;let k=h("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");k.htmlFor=`${t.id}-${i}-${m.name}`;let C=h("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");C.textContent=m.label,k.appendChild(C);let y=(b=m.type)!=null?b:"text",F;y==="textarea"?(F=document.createElement("textarea"),F.rows=3):(F=document.createElement("input"),F.type=y),F.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",F.id=`${t.id}-${i}-${m.name}`,F.name=m.name,F.placeholder=(T=m.placeholder)!=null?T:"",m.required&&(F.required=!0),k.appendChild(F),f.appendChild(k)});let w=h("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),u=h("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),v=h("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");v.type="submit",v.textContent=(I=l.submitLabel)!=null?I:"Submit",w.appendChild(u),w.appendChild(v),f.appendChild(w),s.replaceChildren(d,f),f.addEventListener("submit",async m=>{var F,b;m.preventDefault();let k=(F=o.formEndpoint)!=null?F:"/form",C=new FormData(f),y={};C.forEach((T,K)=>{y[K]=T}),y.type=i,v.disabled=!0,u.textContent="Submitting\u2026";try{let T=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let K=await T.json();u.textContent=(b=K.message)!=null?b:"Thanks! We'll be in touch soon.",K.success&&K.nextPrompt&&await e.sendMessage(String(K.nextPrompt))}catch(T){u.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{v.disabled=!1}})})};var Xn=class{constructor(){this.plugins=new Map}register(t){var o;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(o=t.onRegister)==null||o.call(t)}unregister(t){var e;let o=this.plugins.get(t);o&&((e=o.onUnregister)==null||e.call(o),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>{var e,r;return((e=o.priority)!=null?e:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let e=new Set(t.map(s=>s.id));return[...o.filter(s=>!e.has(s.id)),...t].sort((s,i)=>{var l,d;return((l=i.priority)!=null?l:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var o;return(o=t.onUnregister)==null?void 0:o.call(t)}),this.plugins.clear()}},Tn=new Xn;var sr={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"},rr={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",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"},Le={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:sr,darkTheme:rr,colorScheme:"light",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,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",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:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Vn(n){var t,o,e,r,s,i,l,d,c,f,w,u,v,g,N,I,m,k,C;return n?{...Le,...n,theme:{...Le.theme,...n.theme},darkTheme:{...Le.darkTheme,...n.darkTheme},launcher:{...Le.launcher,...n.launcher,clearChat:{...(t=Le.launcher)==null?void 0:t.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Le.copy,...n.copy},sendButton:{...Le.sendButton,...n.sendButton},statusIndicator:{...Le.statusIndicator,...n.statusIndicator},voiceRecognition:{...Le.voiceRecognition,...n.voiceRecognition},features:{...Le.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:Le.suggestionChips,suggestionChipsConfig:{...Le.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Le.layout,...n.layout,header:{...(r=Le.layout)==null?void 0:r.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Le.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(c=(d=Le.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(w=(f=n.layout)==null?void 0:f.messages)==null?void 0:w.avatar},timestamp:{...(v=(u=Le.layout)==null?void 0:u.messages)==null?void 0:v.timestamp,...(N=(g=n.layout)==null?void 0:g.messages)==null?void 0:N.timestamp}},slots:{...(I=Le.layout)==null?void 0:I.slots,...(m=n.layout)==null?void 0:m.slots}},markdown:{...Le.markdown,...n.markdown,options:{...(k=Le.markdown)==null?void 0:k.options,...(C=n.markdown)==null?void 0:C.options}},messageActions:{...Le.messageActions,...n.messageActions}}:Le}var ir=()=>{let n=new Map,t=(r,s)=>(n.has(r)||n.set(r,new Set),n.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=n.get(r))==null||i.delete(s)};return{on:t,off:o,emit:(r,s)=>{var i;(i=n.get(r))==null||i.forEach(l=>{try{l(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Pr=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},Ir=n=>{let t=n.trim(),o=t.indexOf("{");if(o===-1)return null;let e=0;for(let r=o;r<t.length;r+=1){let s=t[r];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return t.slice(o,r+1)}return null},En=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=Pr(n),o=Ir(t);if(!o)return null;let e=JSON.parse(o);if(!e||typeof e!="object"||!e.action)return null;let{action:r,...s}=e;return{type:String(r),payload:s,raw:e}}catch{return null}},Gn=n=>typeof n=="string"?n:n==null?"":String(n),Xt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Gn(n.payload.text)},messageAndClick:(n,t)=>{var r;if(n.type!=="message_and_click")return;let o=n.payload,e=Gn(o.element);if(e&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Gn(o.text)}}},ar=n=>Array.isArray(n)?n.map(t=>String(t)):[],Mn=n=>{let t=new Set(ar(n.getMetadata().processedActionMessageIds)),o=()=>{t=new Set(ar(n.getMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(t);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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((c,f)=>c||(f==null?void 0:f({text:i,message:s.message}))||null,null):null;if(!l)return null;t.add(s.message.id),e();let d={action:l,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let f=c(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!f)continue;if(f.handled){let w=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:w}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var $r=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Fr=n=>n.map(t=>({...t,streaming:!1})),Qn=(n="vanilla-agent-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?$r(o.getItem(n)):null},save:o=>{let e=t();if(e)try{let r={...o,messages:o.messages?Fr(o.messages):void 0};e.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Zn=class{constructor(){this.components=new Map}register(t,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([o,e])=>{this.register(o,e)})}},cn=new Zn;import{parse as Nr,STR as Or,OBJ as Dr}from"partial-json";function _r(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function jr(n,t){if(!_r(n))return null;let o=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:o,raw:t}}function eo(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:o=>{let e=o.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(o.length<=t)return n;try{let r=Nr(o,Or|Dr),s=jr(r,o);s&&(n=s)}catch{}return t=o.length,n},reset:()=>{n=null,t=0}}}function qr(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function to(n,t){let{config:o,message:e,onPropsUpdate:r}=t,s=cn.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:e,config:o,updateProps:l=>{r&&r(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Ur(){let n=eo();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function no(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function oo(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var zr=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function so(n){let{onSubmit:t,onDismiss:o,title:e="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:c=zr}=n,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let w=null,u=document.createElement("div");u.className="tvw-feedback-content";let v=document.createElement("div");v.className="tvw-feedback-header";let g=document.createElement("h3");g.className="tvw-feedback-title",g.textContent=e,v.appendChild(g);let N=document.createElement("p");N.className="tvw-feedback-subtitle",N.textContent=r,v.appendChild(N),u.appendChild(v);let I=document.createElement("div");I.className="tvw-feedback-rating tvw-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let m=[];for(let b=1;b<=5;b++){let T=document.createElement("button");T.type="button",T.className="tvw-feedback-rating-btn tvw-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${b} star${b>1?"s":""}: ${c[b-1]}`),T.title=c[b-1],T.dataset.rating=String(b),T.innerHTML=`
15
+ `,o.addEventListener("click",t);let e=s=>{var f,S,R,y,F,x,k,Y,z,j,O,q;let i=(f=s.launcher)!=null?f:{},l=o.querySelector("[data-role='launcher-title']");l&&(l.textContent=(S=i.title)!=null?S:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(R=i.subtitle)!=null?R:"Get answers fast");let c=o.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let w=o.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let U=(y=i.agentIconSize)!=null?y:"40px";if(w.style.height=U,w.style.width=U,w.innerHTML="",i.agentIconName){let J=parseFloat(U)||24,V=de(i.agentIconName,J*.6,"#ffffff",2);V?(w.appendChild(V),w.style.display=""):(w.textContent=(F=i.agentIconText)!=null?F:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(x=i.agentIconText)!=null?x:"\u{1F4AC}",w.style.display="")}let g=o.querySelector("[data-role='launcher-image']");if(g){let U=(k=i.agentIconSize)!=null?k:"40px";g.style.height=U,g.style.width=U,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(g.src=i.iconUrl,g.style.display="block"):g.style.display="none"}let p=o.querySelector("[data-role='launcher-call-to-action-icon']");if(p){let U=(Y=i.callToActionIconSize)!=null?Y:"32px";p.style.height=U,p.style.width=U,i.callToActionIconBackgroundColor?(p.style.backgroundColor=i.callToActionIconBackgroundColor,p.classList.remove("tvw-bg-cw-primary")):(p.style.backgroundColor="",p.classList.add("tvw-bg-cw-primary"));let J=0;if(i.callToActionIconPadding?(p.style.boxSizing="border-box",p.style.padding=i.callToActionIconPadding,J=(parseFloat(i.callToActionIconPadding)||0)*2):(p.style.boxSizing="",p.style.padding=""),i.callToActionIconHidden)p.style.display="none";else if(p.style.display="",p.innerHTML="",i.callToActionIconName){let V=parseFloat(U)||24,it=Math.max(V-J,8),oe=de(i.callToActionIconName,it,"currentColor",2);oe?p.appendChild(oe):p.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else p.textContent=(j=i.callToActionIconText)!=null?j:"\u2197"}let v=i.position&&At[i.position]?At[i.position]:At["bottom-right"],m="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-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${m} ${v}`;let N="1px solid #e5e7eb",M="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(O=i.border)!=null?O:N,o.style.boxShadow=(q=i.shadow)!=null?q:M},r=()=>{o.removeEventListener("click",t),o.remove()};return n&&e(n),{element:o,update:e,destroy:r}};var Ft=n=>{var j,O,q,U,J,V,it,oe,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,P,$e,ut,pt,Lt,bt,Ct,Fe,et,xt,Me,Le;let{config:t,showClose:o=!0}=n,e=h("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"),r=(j=t==null?void 0:t.launcher)!=null?j:{},s=(O=r.headerIconSize)!=null?O:"48px",i=(q=r.closeButtonSize)!=null?q:"32px",l=(U=r.closeButtonPlacement)!=null?U:"inline",d=(J=r.headerIconHidden)!=null?J:!1,c=r.headerIconName,w=h("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=s,w.style.width=s,!d)if(c){let b=parseFloat(s)||24,Be=de(c,b*.6,"#ffffff",2);Be?w.replaceChildren(Be):w.textContent=(it=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?it:"\u{1F4AC}"}else if((oe=t==null?void 0:t.launcher)!=null&&oe.iconUrl){let b=h("img");b.src=t.launcher.iconUrl,b.alt="",b.className="tvw-rounded-xl tvw-object-cover",b.style.height=s,b.style.width=s,w.replaceChildren(b)}else w.textContent=(Ve=(D=t==null?void 0:t.launcher)==null?void 0:D.agentIconText)!=null?Ve:"\u{1F4AC}";let g=h("div","tvw-flex tvw-flex-col"),p=h("span","tvw-text-base tvw-font-semibold");p.textContent=(at=(nt=t==null?void 0:t.launcher)==null?void 0:nt.title)!=null?at:"Chat Assistant";let v=h("span","tvw-text-xs tvw-text-cw-muted");v.textContent=(Et=(Tt=t==null?void 0:t.launcher)==null?void 0:Tt.subtitle)!=null?Et:"Here to help you get answers fast",g.append(p,v),d?e.append(g):e.append(w,g);let m=(_=r.clearChat)!=null?_:{},N=(ue=m.enabled)!=null?ue:!0,M=(Ge=m.placement)!=null?Ge:"inline",f=null,S=null;if(N){let b=(Qe=m.size)!=null?Qe:"32px",Be=(_e=m.iconName)!=null?_e:"refresh-cw",Ee=(Ze=m.iconColor)!=null?Ze:"",Ke=(P=m.backgroundColor)!=null?P:"",ot=($e=m.borderWidth)!=null?$e:"",st=(ut=m.borderColor)!=null?ut:"",gt=(pt=m.borderRadius)!=null?pt:"",mt=(Lt=m.paddingX)!=null?Lt:"",Mt=(bt=m.paddingY)!=null?bt:"",Rt=(Ct=m.tooltipText)!=null?Ct:"Clear chat",zt=(Fe=m.showTooltip)!=null?Fe:!0;S=h("div",M==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),M==="top-right"&&(S.style.right="48px"),f=h("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"),f.style.height=b,f.style.width=b,f.type="button",f.setAttribute("aria-label",Rt);let Nt=de(Be,"20px",Ee||"",2);if(Nt&&f.appendChild(Nt),Ee&&(f.style.color=Ee,f.classList.remove("tvw-text-cw-muted")),Ke&&(f.style.backgroundColor=Ke,f.classList.remove("hover:tvw-bg-gray-100")),ot||st){let He=ot||"0px",ht=st||"transparent";f.style.border=`${He} solid ${ht}`,f.classList.remove("tvw-border-none")}if(gt&&(f.style.borderRadius=gt,f.classList.remove("tvw-rounded-full")),mt?(f.style.paddingLeft=mt,f.style.paddingRight=mt):(f.style.paddingLeft="",f.style.paddingRight=""),Mt?(f.style.paddingTop=Mt,f.style.paddingBottom=Mt):(f.style.paddingTop="",f.style.paddingBottom=""),S.appendChild(f),zt&&Rt&&f&&S){let He=null,ht=()=>{if(He||!f)return;He=h("div","tvw-clear-chat-tooltip"),He.textContent=Rt;let Pt=h("div");Pt.className="tvw-clear-chat-tooltip-arrow",He.appendChild(Pt);let Bt=f.getBoundingClientRect();He.style.position="fixed",He.style.left=`${Bt.left+Bt.width/2}px`,He.style.top=`${Bt.top-8}px`,He.style.transform="translate(-50%, -100%)",document.body.appendChild(He)},pe=()=>{He&&He.parentNode&&(He.parentNode.removeChild(He),He=null)};S.addEventListener("mouseenter",ht),S.addEventListener("mouseleave",pe),f.addEventListener("focus",ht),f.addEventListener("blur",pe),S._cleanupTooltip=()=>{pe(),S&&(S.removeEventListener("mouseenter",ht),S.removeEventListener("mouseleave",pe)),f&&(f.removeEventListener("focus",ht),f.removeEventListener("blur",pe))}}M==="inline"&&e.appendChild(S)}let R=h("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":N&&M==="inline"?"":"tvw-ml-auto"),y=h("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");y.style.height=i,y.style.width=i,y.type="button";let F=(et=r.closeButtonTooltipText)!=null?et:"Close chat",x=(xt=r.closeButtonShowTooltip)!=null?xt:!0;y.setAttribute("aria-label",F),y.style.display=o?"":"none";let k=(Me=r.closeButtonIconName)!=null?Me:"x",Y=(Le=r.closeButtonIconText)!=null?Le:"\xD7",z=de(k,"20px",r.closeButtonColor||"",2);if(z?y.appendChild(z):y.textContent=Y,r.closeButtonColor?(y.style.color=r.closeButtonColor,y.classList.remove("tvw-text-cw-muted")):(y.style.color="",y.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(y.style.backgroundColor=r.closeButtonBackgroundColor,y.classList.remove("hover:tvw-bg-gray-100")):(y.style.backgroundColor="",y.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let b=r.closeButtonBorderWidth||"0px",Be=r.closeButtonBorderColor||"transparent";y.style.border=`${b} solid ${Be}`,y.classList.remove("tvw-border-none")}else y.style.border="",y.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(y.style.borderRadius=r.closeButtonBorderRadius,y.classList.remove("tvw-rounded-full")):(y.style.borderRadius="",y.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(y.style.paddingLeft=r.closeButtonPaddingX,y.style.paddingRight=r.closeButtonPaddingX):(y.style.paddingLeft="",y.style.paddingRight=""),r.closeButtonPaddingY?(y.style.paddingTop=r.closeButtonPaddingY,y.style.paddingBottom=r.closeButtonPaddingY):(y.style.paddingTop="",y.style.paddingBottom=""),R.appendChild(y),x&&F){let b=null,Be=()=>{if(b)return;b=h("div","tvw-clear-chat-tooltip"),b.textContent=F;let Ke=h("div");Ke.className="tvw-clear-chat-tooltip-arrow",b.appendChild(Ke);let ot=y.getBoundingClientRect();b.style.position="fixed",b.style.left=`${ot.left+ot.width/2}px`,b.style.top=`${ot.top-8}px`,b.style.transform="translate(-50%, -100%)",document.body.appendChild(b)},Ee=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};R.addEventListener("mouseenter",Be),R.addEventListener("mouseleave",Ee),y.addEventListener("focus",Be),y.addEventListener("blur",Ee),R._cleanupTooltip=()=>{Ee(),R.removeEventListener("mouseenter",Be),R.removeEventListener("mouseleave",Ee),y.removeEventListener("focus",Be),y.removeEventListener("blur",Ee)}}return l!=="top-right"&&e.appendChild(R),{header:e,iconHolder:w,headerTitle:p,headerSubtitle:v,closeButton:y,closeButtonWrapper:R,clearChatButton:f,clearChatButtonWrapper:S}},Yt=(n,t,o)=>{var i,l,d,c;let e=(i=o==null?void 0:o.launcher)!=null?i:{},r=(l=e.closeButtonPlacement)!=null?l:"inline",s=(c=(d=e.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),r==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var Zs=n=>Ft({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),er=n=>{var m,N,M,f;let{config:t,showClose:o=!0,onClose:e}=n,r=(m=t==null?void 0:t.launcher)!=null?m:{},s=h("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=h("span","tvw-text-base tvw-font-semibold");i.textContent=(N=r.title)!=null?N:"Chat Assistant",s.appendChild(i);let l=(M=r.closeButtonSize)!=null?M:"32px",d=h("div",""),c=h("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");c.style.height=l,c.style.width=l,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=o?"":"none";let w=(f=r.closeButtonIconName)!=null?f:"x",g=de(w,"20px",r.closeButtonColor||"",2);g?c.appendChild(g):c.textContent="\xD7",e&&c.addEventListener("click",e),d.appendChild(c),s.appendChild(d);let p=h("div");p.style.display="none";let v=h("span");return v.style.display="none",{header:s,iconHolder:p,headerTitle:i,headerSubtitle:v,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},tr=n=>{var y,F,x,k,Y,z,j,O;let{config:t,showClose:o=!0,onClose:e,onClearChat:r}=n,s=(y=t==null?void 0:t.launcher)!=null?y:{},i=h("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=h("div","tvw-flex tvw-items-center tvw-gap-3"),d=(F=s.headerIconSize)!=null?F:"56px",c=h("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let w=s.headerIconName;if(w){let q=parseFloat(d)||24,U=de(w,q*.5,"#ffffff",2);U?c.replaceChildren(U):c.textContent=(x=s.agentIconText)!=null?x:"\u{1F4AC}"}else if(s.iconUrl){let q=h("img");q.src=s.iconUrl,q.alt="",q.className="tvw-rounded-xl tvw-object-cover",q.style.height=d,q.style.width=d,c.replaceChildren(q)}else c.textContent=(k=s.agentIconText)!=null?k:"\u{1F4AC}";let g=h("div","tvw-flex tvw-flex-col tvw-flex-1"),p=h("span","tvw-text-lg tvw-font-semibold");p.textContent=(Y=s.title)!=null?Y:"Chat Assistant";let v=h("span","tvw-text-sm tvw-text-cw-muted");v.textContent=(z=s.subtitle)!=null?z:"Here to help you get answers fast",g.append(p,v),l.append(c,g);let m=(j=s.closeButtonSize)!=null?j:"32px",N=h("div",""),M=h("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=m,M.style.width=m,M.type="button",M.setAttribute("aria-label","Close chat"),M.style.display=o?"":"none";let f=(O=s.closeButtonIconName)!=null?O:"x",S=de(f,"20px",s.closeButtonColor||"",2);S?M.appendChild(S):M.textContent="\xD7",e&&M.addEventListener("click",e),N.appendChild(M),l.appendChild(N),i.appendChild(l);let R=h("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return R.textContent="Online and ready to help",i.appendChild(R),{header:i,iconHolder:c,headerTitle:p,headerSubtitle:v,closeButton:M,closeButtonWrapper:N,clearChatButton:null,clearChatButtonWrapper:null}},Yn={default:Zs,minimal:er,expanded:tr},nr=n=>{var t;return(t=Yn[n])!=null?t:Yn.default},un=(n,t,o)=>{var i,l,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),w=h("div");w.style.display="none";let g=h("span"),p=h("span"),v=h("button");v.style.display="none";let m=h("div");return m.style.display="none",{header:c,iconHolder:w,headerTitle:g,headerSubtitle:p,closeButton:v,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",s=nr(e)({config:n,showClose:(d=(l=t==null?void 0:t.showCloseButton)!=null?l:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Fr=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'}},pn=n=>{var V,it,oe,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,P,$e,ut,pt,Lt,bt,Ct,Fe,et,xt;let{config:t}=n,o=h("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=h("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((V=t==null?void 0:t.voiceRecognition)==null?void 0:V.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=h("form",`tvw-widget-composer tvw-flex tvw-items-end ${r&&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`);d.style.outline="none";let c=h("textarea");c.placeholder=(oe=(it=t==null?void 0:t.copy)==null?void 0:it.inputPlaceholder)!=null?oe:"Type your message\u2026",c.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",c.rows=1;let w=(Ve=(D=t==null?void 0:t.theme)==null?void 0:D.inputFontFamily)!=null?Ve:"sans-serif",g=(at=(nt=t==null?void 0:t.theme)==null?void 0:nt.inputFontWeight)!=null?at:"400";c.style.fontFamily=Fr(w),c.style.fontWeight=g,c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.addEventListener("focus",()=>{c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.style.boxShadow="none"}),c.addEventListener("blur",()=>{c.style.border="none",c.style.outline="none"});let p=(Tt=t==null?void 0:t.sendButton)!=null?Tt:{},v=(Et=p.useIcon)!=null?Et:!1,m=(_=p.iconText)!=null?_:"\u2191",N=p.iconName,M=(ue=p.tooltipText)!=null?ue:"Send message",f=(Ge=p.showTooltip)!=null?Ge:!1,S=(Qe=p.size)!=null?Qe:"40px",R=p.backgroundColor,y=p.textColor,F=h("div","tvw-send-button-wrapper"),x=h("button",v?"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(x.type="submit",v){if(x.style.width=S,x.style.height=S,x.style.minWidth=S,x.style.minHeight=S,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",N){let Me=parseFloat(S)||24,Le=y&&typeof y=="string"&&y.trim()?y.trim():"currentColor",b=de(N,Me,Le,2);b?(x.appendChild(b),x.style.color=Le):(x.textContent=m,y?x.style.color=y:x.classList.add("tvw-text-white"))}else x.textContent=m,y?x.style.color=y:x.classList.add("tvw-text-white");R?x.style.backgroundColor=R:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(Ze=(_e=t==null?void 0:t.copy)==null?void 0:_e.sendButtonLabel)!=null?Ze:"Send",y?x.style.color=y:x.classList.add("tvw-text-white");if(p.borderWidth&&(x.style.borderWidth=p.borderWidth,x.style.borderStyle="solid"),p.borderColor&&(x.style.borderColor=p.borderColor),p.paddingX?(x.style.paddingLeft=p.paddingX,x.style.paddingRight=p.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),p.paddingY?(x.style.paddingTop=p.paddingY,x.style.paddingBottom=p.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),f&&M){let Me=h("div","tvw-send-button-tooltip");Me.textContent=M,F.appendChild(Me)}F.appendChild(x);let k=(P=t==null?void 0:t.voiceRecognition)!=null?P:{},Y=k.enabled===!0,z=null,j=null,O=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Y&&O){j=h("div","tvw-send-button-wrapper"),z=h("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),z.type="button",z.setAttribute("aria-label","Start voice recognition");let Me=($e=k.iconName)!=null?$e:"mic",Le=(ut=k.iconSize)!=null?ut:S,b=parseFloat(Le)||24,Be=(pt=k.backgroundColor)!=null?pt:R,Ee=(Lt=k.iconColor)!=null?Lt:y;z.style.width=Le,z.style.height=Le,z.style.minWidth=Le,z.style.minHeight=Le,z.style.fontSize="18px",z.style.lineHeight="1";let Ke=Ee||"currentColor",ot=de(Me,b,Ke,1.5);ot?(z.appendChild(ot),z.style.color=Ke):(z.textContent="\u{1F3A4}",z.style.color=Ke),Be?z.style.backgroundColor=Be:z.classList.add("tvw-bg-cw-primary"),Ee?z.style.color=Ee:!Ee&&!y&&z.classList.add("tvw-text-white"),k.borderWidth&&(z.style.borderWidth=k.borderWidth,z.style.borderStyle="solid"),k.borderColor&&(z.style.borderColor=k.borderColor),k.paddingX&&(z.style.paddingLeft=k.paddingX,z.style.paddingRight=k.paddingX),k.paddingY&&(z.style.paddingTop=k.paddingY,z.style.paddingBottom=k.paddingY),j.appendChild(z);let st=(bt=k.tooltipText)!=null?bt:"Start voice recognition";if(((Ct=k.showTooltip)!=null?Ct:!1)&&st){let mt=h("div","tvw-send-button-tooltip");mt.textContent=st,j.appendChild(mt)}}d.addEventListener("click",Me=>{Me.target!==x&&Me.target!==F&&Me.target!==z&&Me.target!==j&&c.focus()}),d.append(c),j&&d.append(j),d.append(F);let q=h("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),U=(Fe=t==null?void 0:t.statusIndicator)!=null?Fe:{},J=(et=U.visible)!=null?et:!0;return q.style.display=J?"":"none",q.textContent=(xt=U.idleText)!=null?xt:"Online",o.append(e,d,q),{footer:o,suggestions:e,composerForm:d,textarea:c,sendButton:x,sendButtonWrapper:F,micButton:z,micButtonWrapper:j,statusText:q}};var or=n=>{var d,c,w,g,p,v,m;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let N=h("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),M=h("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),f=(g=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?g:"100%";return N.style.width=f,M.style.width="100%",N.appendChild(M),{wrapper:N,panel:M}}let o=(p=n==null?void 0:n.launcher)!=null?p:{},e=o.position&&At[o.position]?At[o.position]:At["bottom-right"],r=h("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=h("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(m=(v=n==null?void 0:n.launcher)==null?void 0:v.width)!=null?m:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,r.appendChild(s),{wrapper:r,panel:s}},sr=(n,t=!0)=>{var v,m,N,M,f,S,R;let o=h("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"),e=(v=n==null?void 0:n.layout)==null?void 0:v.header,r=((m=n==null?void 0:n.layout)==null?void 0:m.showHeader)!==!1,s=e?un(n,e,{showClose:t}):Ft({config:n,showClose:t}),i=h("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");i.id="vanilla-agent-scroll-container";let l=h("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=h("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(M=(N=n==null?void 0:n.copy)==null?void 0:N.welcomeTitle)!=null?M:"Hello \u{1F44B}";let c=h("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(S=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",l.append(d,c);let w=h("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(l,w);let g=pn({config:n}),p=((R=n==null?void 0:n.layout)==null?void 0:R.showFooter)!==!1;return r?Yt(o,s,n):(s.header.style.display="none",Yt(o,s,n)),o.append(i),p||(g.footer.style.display="none"),o.append(g.footer),{container:o,body:i,messagesWrapper:w,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:c,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer}};var kn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(t),n.appendChild(o),n.appendChild(e),n.appendChild(r),n},Nr=(n,t)=>{let o=h("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"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let r=h("img");r.src=e,r.alt=t==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=e,o.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},rr=(n,t)=>{let o=h("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?o.textContent=t.format(e):o.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Or=(n,t="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.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:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.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 o},ir=(n,t,o)=>{var m,N,M,f,S,R;let e=(m=t.showCopy)!=null?m:!0,r=(N=t.showUpvote)!=null?N:!0,s=(M=t.showDownvote)!=null?M:!0,i=(f=t.visibility)!=null?f:"hover",l=(S=t.align)!=null?S:"right",d=(R=t.layout)!=null?R:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],g=h("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`);g.id=`actions-${n.id}`,g.setAttribute("data-actions-for",n.id);let p=null,v=(y,F,x,k)=>{let Y=document.createElement("button");Y.className="tvw-message-action-btn",Y.setAttribute("aria-label",F),Y.setAttribute("title",F),k&&Y.setAttribute("data-action",k);let z=de(y,14,"currentColor",2);return z&&Y.appendChild(z),Y.addEventListener("click",j=>{j.preventDefault(),j.stopPropagation(),x()}),Y};if(e){let y=v("copy","Copy message",()=>{let F=n.content||"";navigator.clipboard.writeText(F).then(()=>{y.classList.add("tvw-message-action-success");let x=de("check",14,"currentColor",2);x&&(y.innerHTML="",y.appendChild(x)),setTimeout(()=>{y.classList.remove("tvw-message-action-success");let k=de("copy",14,"currentColor",2);k&&(y.innerHTML="",y.appendChild(k))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),o!=null&&o.onCopy&&o.onCopy(n),t.onCopy&&t.onCopy(n)},"copy");g.appendChild(y)}if(r){let y=v("thumbs-up","Upvote",()=>{if(p==="upvote")p=null,y.classList.remove("tvw-message-action-active");else{let x=g.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),p="upvote",y.classList.add("tvw-message-action-active");let k={type:"upvote",messageId:n.id,message:n};o!=null&&o.onFeedback&&o.onFeedback(k),t.onFeedback&&t.onFeedback(k)}},"upvote");g.appendChild(y)}if(s){let y=v("thumbs-down","Downvote",()=>{if(p==="downvote")p=null,y.classList.remove("tvw-message-action-active");else{let x=g.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),p="downvote",y.classList.add("tvw-message-action-active");let k={type:"downvote",messageId:n.id,message:n};o!=null&&o.onFeedback&&o.onFeedback(k),t.onFeedback&&t.onFeedback(k)}},"downvote");g.appendChild(y)}return g},gn=(n,t,o,e,r)=>{var R,y,F,x,k;let s=o!=null?o:{},i=(R=s.layout)!=null?R:"bubble",l=s.avatar,d=s.timestamp,c=(y=l==null?void 0:l.show)!=null?y:!1,w=(F=d==null?void 0:d.show)!=null?F:!1,g=(x=l==null?void 0:l.position)!=null?x:"left",p=(k=d==null?void 0:d.position)!=null?k:"below",v=Or(n.role,i),m=h("div",v.join(" "));m.id=`bubble-${n.id}`,m.setAttribute("data-message-id",n.id);let N=document.createElement("div");if(N.innerHTML=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),w&&p==="inline"&&n.createdAt){let Y=rr(n,d);Y.classList.add("tvw-ml-2","tvw-inline"),N.appendChild(Y)}if(m.appendChild(N),w&&p==="below"&&n.createdAt){let Y=rr(n,d);Y.classList.add("tvw-mt-1"),m.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=kn();m.appendChild(Y)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let Y=ir(n,e,r);m.appendChild(Y)}if(!c||n.role==="system")return m;let f=h("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),S=Nr(l,n.role);return g==="right"||g==="left"&&n.role==="user"?f.append(m,S):f.append(S,m),m.classList.remove("tvw-max-w-[85%]"),m.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),f},Dr=(n,t,o,e,r)=>{let s=o!=null?o:{};return n.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):gn(n,t,o,e,r)};var Kt=new Set,ar=(n,t)=>{let o=Kt.has(n),e=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".tvw-border-t");if(!e||!r)return;e.setAttribute("aria-expanded",o?"true":"false");let s=e.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=de(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},Kn=n=>{let t=n.reasoning,o=h("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(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),!t)return o;let e=Kt.has(n.id),r=h("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");r.type="button",r.setAttribute("aria-expanded",e?"true":"false"),r.setAttribute("data-expand-header","true"),r.setAttribute("data-bubble-type","reasoning");let s=h("div","tvw-flex tvw-flex-col tvw-text-left"),i=h("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=h("span","tvw-text-xs tvw-text-cw-primary");l.textContent=Ks(t),s.appendChild(l),t.status==="complete"?i.style.display="none":i.style.display="";let d=h("div","tvw-flex tvw-items-center"),w=de(e?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=e?"Hide":"Show";let g=h("div","tvw-flex tvw-items-center tvw-ml-auto");g.append(d),r.append(s,g);let p=h("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");p.style.display=e?"":"none";let v=t.chunks.join(""),m=h("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return m.textContent=v||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),p.appendChild(m),(()=>{r.setAttribute("aria-expanded",e?"true":"false"),d.innerHTML="";let f=de(e?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=e?"Hide":"Show",p.style.display=e?"":"none"})(),o.append(r,p),o};var Xt=new Set,lr=(n,t,o)=>{var c;let e=Xt.has(n),r=(c=o==null?void 0:o.toolCall)!=null?c:{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",e?"true":"false");let l=s.querySelector(".tvw-ml-auto"),d=l==null?void 0:l.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let w=r.toggleTextColor||r.headerTextColor||"currentColor",g=de(e?"chevron-up":"chevron-down",16,w,2);g?d.appendChild(g):d.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},Xn=(n,t)=>{var N;let o=n.toolCall,e=(N=t==null?void 0:t.toolCall)!=null?N:{},r=h("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(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),e.backgroundColor&&(r.style.backgroundColor=e.backgroundColor),e.borderColor&&(r.style.borderColor=e.borderColor),e.borderWidth&&(r.style.borderWidth=e.borderWidth),e.borderRadius&&(r.style.borderRadius=e.borderRadius),!o)return r;let s=Xt.has(n.id),i=h("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"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let l=h("div","tvw-flex tvw-flex-col tvw-text-left"),d=h("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(d.style.color=e.headerTextColor),d.textContent=Xs(o),l.appendChild(d);let c=h("div","tvw-flex tvw-items-center"),w=e.toggleTextColor||e.headerTextColor||"currentColor",g=de(s?"chevron-up":"chevron-down",16,w,2);g?c.appendChild(g):c.textContent=s?"Hide":"Show";let p=h("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");p.append(c),i.append(l,p);let v=h("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(v.style.display=s?"":"none",e.contentBackgroundColor&&(v.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(v.style.color=e.contentTextColor),e.contentPaddingX&&(v.style.paddingLeft=e.contentPaddingX,v.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(v.style.paddingTop=e.contentPaddingY,v.style.paddingBottom=e.contentPaddingY),o.name){let M=h("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?M.style.color=e.contentTextColor:e.headerTextColor&&(M.style.color=e.headerTextColor),M.textContent=o.name,v.appendChild(M)}if(o.args!==void 0){let M=h("div","tvw-space-y-1"),f=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(f.style.color=e.labelTextColor),f.textContent="Arguments";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(S.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(S.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(S.style.color=e.codeBlockTextColor),S.textContent=On(o.args),M.append(f,S),v.appendChild(M)}if(o.chunks&&o.chunks.length){let M=h("div","tvw-space-y-1"),f=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(f.style.color=e.labelTextColor),f.textContent="Activity";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(S.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(S.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(S.style.color=e.codeBlockTextColor),S.textContent=o.chunks.join(`
16
+ `),M.append(f,S),v.appendChild(M)}if(o.status==="complete"&&o.result!==void 0){let M=h("div","tvw-space-y-1"),f=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(f.style.color=e.labelTextColor),f.textContent="Result";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(S.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(S.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(S.style.color=e.codeBlockTextColor),S.textContent=On(o.result),M.append(f,S),v.appendChild(M)}if(o.status==="complete"&&typeof o.duration=="number"){let M=h("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(M.style.color=e.contentTextColor),M.textContent=`Duration: ${o.duration}ms`,v.appendChild(M)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let M=e.toggleTextColor||e.headerTextColor||"currentColor",f=de(s?"chevron-up":"chevron-down",16,M,2);f?c.appendChild(f):c.textContent=s?"Hide":"Show",v.style.display=s?"":"none"})(),r.append(i,v),r};var dr=n=>{let t=[];return{buttons:t,render:(e,r,s,i,l)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:r?r.getMessages():[]).some(v=>v.role==="user"))return;let w=document.createDocumentFragment(),g=r?r.isStreaming():!1,p=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(v=>{let m=h("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");m.type="button",m.textContent=v,m.disabled=g,l!=null&&l.fontFamily&&(m.style.fontFamily=p(l.fontFamily)),l!=null&&l.fontWeight&&(m.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(m.style.paddingLeft=l.paddingX,m.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(m.style.paddingTop=l.paddingY,m.style.paddingBottom=l.paddingY),m.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(v))}),w.appendChild(m),t.push(m)}),n.appendChild(w)}}};var cr={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"}},Vn=(n,t,o,e)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var m,N,M;if(s.dataset.enhanced==="true")return;let i=(m=s.dataset.tvForm)!=null?m:"init";s.dataset.enhanced="true";let l=(N=cr[i])!=null?N:cr.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=h("div","tvw-space-y-1"),c=h("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=l.title,d.appendChild(c),l.description){let f=h("p","tvw-text-sm tvw-text-cw-muted");f.textContent=l.description,d.appendChild(f)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(f=>{var x,k;let S=h("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${t.id}-${i}-${f.name}`;let R=h("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");R.textContent=f.label,S.appendChild(R);let y=(x=f.type)!=null?x:"text",F;y==="textarea"?(F=document.createElement("textarea"),F.rows=3):(F=document.createElement("input"),F.type=y),F.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",F.id=`${t.id}-${i}-${f.name}`,F.name=f.name,F.placeholder=(k=f.placeholder)!=null?k:"",f.required&&(F.required=!0),S.appendChild(F),w.appendChild(S)});let g=h("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),p=h("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),v=h("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");v.type="submit",v.textContent=(M=l.submitLabel)!=null?M:"Submit",g.appendChild(p),g.appendChild(v),w.appendChild(g),s.replaceChildren(d,w),w.addEventListener("submit",async f=>{var F,x;f.preventDefault();let S=(F=o.formEndpoint)!=null?F:"/form",R=new FormData(w),y={};R.forEach((k,Y)=>{y[Y]=k}),y.type=i,v.disabled=!0,p.textContent="Submitting\u2026";try{let k=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let Y=await k.json();p.textContent=(x=Y.message)!=null?x:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await e.sendMessage(String(Y.nextPrompt))}catch(k){p.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{v.disabled=!1}})})};var Gn=class{constructor(){this.plugins=new Map}register(t){var o;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(o=t.onRegister)==null||o.call(t)}unregister(t){var e;let o=this.plugins.get(t);o&&((e=o.onUnregister)==null||e.call(o),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>{var e,r;return((e=o.priority)!=null?e:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let e=new Set(t.map(s=>s.id));return[...o.filter(s=>!e.has(s.id)),...t].sort((s,i)=>{var l,d;return((l=i.priority)!=null?l:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var o;return(o=t.onUnregister)==null?void 0:o.call(t)}),this.plugins.clear()}},Wn=new Gn;var ur={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"},pr={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",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"},We={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:ur,darkTheme:pr,colorScheme:"light",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,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",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:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Qn(n){var t,o,e,r,s,i,l,d,c,w,g,p,v,m,N,M,f,S,R;return n?{...We,...n,theme:{...We.theme,...n.theme},darkTheme:{...We.darkTheme,...n.darkTheme},launcher:{...We.launcher,...n.launcher,clearChat:{...(t=We.launcher)==null?void 0:t.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...We.copy,...n.copy},sendButton:{...We.sendButton,...n.sendButton},statusIndicator:{...We.statusIndicator,...n.statusIndicator},voiceRecognition:{...We.voiceRecognition,...n.voiceRecognition},features:{...We.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:We.suggestionChips,suggestionChipsConfig:{...We.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...We.layout,...n.layout,header:{...(r=We.layout)==null?void 0:r.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=We.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(c=(d=We.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(g=(w=n.layout)==null?void 0:w.messages)==null?void 0:g.avatar},timestamp:{...(v=(p=We.layout)==null?void 0:p.messages)==null?void 0:v.timestamp,...(N=(m=n.layout)==null?void 0:m.messages)==null?void 0:N.timestamp}},slots:{...(M=We.layout)==null?void 0:M.slots,...(f=n.layout)==null?void 0:f.slots}},markdown:{...We.markdown,...n.markdown,options:{...(S=We.markdown)==null?void 0:S.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...We.messageActions,...n.messageActions}}:We}var gr=()=>{let n=new Map,t=(r,s)=>(n.has(r)||n.set(r,new Set),n.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=n.get(r))==null||i.delete(s)};return{on:t,off:o,emit:(r,s)=>{var i;(i=n.get(r))==null||i.forEach(l=>{try{l(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var _r=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},jr=n=>{let t=n.trim(),o=t.indexOf("{");if(o===-1)return null;let e=0;for(let r=o;r<t.length;r+=1){let s=t[r];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return t.slice(o,r+1)}return null},Ln=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=_r(n),o=jr(t);if(!o)return null;let e=JSON.parse(o);if(!e||typeof e!="object"||!e.action)return null;let{action:r,...s}=e;return{type:String(r),payload:s,raw:e}}catch{return null}},Zn=n=>typeof n=="string"?n:n==null?"":String(n),Vt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Zn(n.payload.text)},messageAndClick:(n,t)=>{var r;if(n.type!=="message_and_click")return;let o=n.payload,e=Zn(o.element);if(e&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Zn(o.text)}}},mr=n=>Array.isArray(n)?n.map(t=>String(t)):[],Bn=n=>{let t=new Set(mr(n.getMetadata().processedActionMessageIds)),o=()=>{t=new Set(mr(n.getMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(t);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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((c,w)=>c||(w==null?void 0:w({text:i,message:s.message}))||null,null):null;if(!l)return null;t.add(s.message.id),e();let d={action:l,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let w=c(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!w)continue;if(w.handled){let g=w.persistMessage!==!1;return{text:w.displayText!==void 0?w.displayText:"",persist:g}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:o}};var qr=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Ur=n=>n.map(t=>({...t,streaming:!1})),eo=(n="vanilla-agent-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?qr(o.getItem(n)):null},save:o=>{let e=t();if(e)try{let r={...o,messages:o.messages?Ur(o.messages):void 0};e.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var to=class{constructor(){this.components=new Map}register(t,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([o,e])=>{this.register(o,e)})}},mn=new to;import{parse as zr,STR as Jr,OBJ as Yr}from"partial-json";function Kr(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function Xr(n,t){if(!Kr(n))return null;let o=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:o,raw:t}}function no(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:o=>{let e=o.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(o.length<=t)return n;try{let r=zr(o,Jr|Yr),s=Xr(r,o);s&&(n=s)}catch{}return t=o.length,n},reset:()=>{n=null,t=0}}}function Vr(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function oo(n,t){let{config:o,message:e,onPropsUpdate:r}=t,s=mn.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:e,config:o,updateProps:l=>{r&&r(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Gr(){let n=no();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function so(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function ro(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var Qr=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function io(n){let{onSubmit:t,onDismiss:o,title:e="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:c=Qr}=n,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-csat",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Customer satisfaction feedback");let g=null,p=document.createElement("div");p.className="tvw-feedback-content";let v=document.createElement("div");v.className="tvw-feedback-header";let m=document.createElement("h3");m.className="tvw-feedback-title",m.textContent=e,v.appendChild(m);let N=document.createElement("p");N.className="tvw-feedback-subtitle",N.textContent=r,v.appendChild(N),p.appendChild(v);let M=document.createElement("div");M.className="tvw-feedback-rating tvw-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let f=[];for(let x=1;x<=5;x++){let k=document.createElement("button");k.type="button",k.className="tvw-feedback-rating-btn tvw-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${c[x-1]}`),k.title=c[x-1],k.dataset.rating=String(x),k.innerHTML=`
17
17
  <svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
18
18
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
19
19
  </svg>
20
- `,T.addEventListener("click",()=>{w=b,m.forEach((K,J)=>{let j=J<b;K.classList.toggle("selected",j),K.setAttribute("aria-checked",J===b-1?"true":"false")})}),m.push(T),I.appendChild(T)}u.appendChild(I);let k=null;if(d){let b=document.createElement("div");b.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),b.appendChild(k),u.appendChild(b)}let C=document.createElement("div");C.className="tvw-feedback-actions";let y=document.createElement("button");y.type="button",y.className="tvw-feedback-btn tvw-feedback-btn-skip",y.textContent=l,y.addEventListener("click",()=>{o==null||o(),f.remove()});let F=document.createElement("button");return F.type="button",F.className="tvw-feedback-btn tvw-feedback-btn-submit",F.textContent=i,F.addEventListener("click",async()=>{if(w===null){I.classList.add("tvw-feedback-shake"),setTimeout(()=>I.classList.remove("tvw-feedback-shake"),500);return}F.disabled=!0,F.textContent="Submitting...";try{let b=(k==null?void 0:k.value.trim())||void 0;await t(w,b),f.remove()}catch(b){F.disabled=!1,F.textContent=i,console.error("[CSAT Feedback] Failed to submit:",b)}}),C.appendChild(y),C.appendChild(F),u.appendChild(C),f.appendChild(u),f}function ro(n){let{onSubmit:t,onDismiss:o,title:e="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:f="Very likely"}=n,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-nps",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Net Promoter Score feedback");let u=null,v=document.createElement("div");v.className="tvw-feedback-content";let g=document.createElement("div");g.className="tvw-feedback-header";let N=document.createElement("h3");N.className="tvw-feedback-title",N.textContent=e,g.appendChild(N);let I=document.createElement("p");I.className="tvw-feedback-subtitle",I.textContent=r,g.appendChild(I),v.appendChild(g);let m=document.createElement("div");m.className="tvw-feedback-rating tvw-feedback-rating-nps",m.setAttribute("role","radiogroup"),m.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="tvw-feedback-labels";let C=document.createElement("span");C.className="tvw-feedback-label-low",C.textContent=c;let y=document.createElement("span");y.className="tvw-feedback-label-high",y.textContent=f,k.appendChild(C),k.appendChild(y);let F=document.createElement("div");F.className="tvw-feedback-numbers";let b=[];for(let O=0;O<=10;O++){let q=document.createElement("button");q.type="button",q.className="tvw-feedback-rating-btn tvw-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${O} out of 10`),q.textContent=String(O),q.dataset.rating=String(O),O<=6?q.classList.add("tvw-feedback-detractor"):O<=8?q.classList.add("tvw-feedback-passive"):q.classList.add("tvw-feedback-promoter"),q.addEventListener("click",()=>{u=O,b.forEach((U,Y)=>{U.classList.toggle("selected",Y===O),U.setAttribute("aria-checked",Y===O?"true":"false")})}),b.push(q),F.appendChild(q)}m.appendChild(k),m.appendChild(F),v.appendChild(m);let T=null;if(d){let O=document.createElement("div");O.className="tvw-feedback-comment-container",T=document.createElement("textarea"),T.className="tvw-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),O.appendChild(T),v.appendChild(O)}let K=document.createElement("div");K.className="tvw-feedback-actions";let J=document.createElement("button");J.type="button",J.className="tvw-feedback-btn tvw-feedback-btn-skip",J.textContent=l,J.addEventListener("click",()=>{o==null||o(),w.remove()});let j=document.createElement("button");return j.type="button",j.className="tvw-feedback-btn tvw-feedback-btn-submit",j.textContent=i,j.addEventListener("click",async()=>{if(u===null){F.classList.add("tvw-feedback-shake"),setTimeout(()=>F.classList.remove("tvw-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let O=(T==null?void 0:T.value.trim())||void 0;await t(u,O),w.remove()}catch(O){j.disabled=!1,j.textContent=i,console.error("[NPS Feedback] Failed to submit:",O)}}),K.appendChild(J),K.appendChild(j),v.appendChild(K),w.appendChild(v),w}var Vt="vanilla-agent-chat-history",Jr=30*1e3,io=n=>!n||typeof n!="object"?{}:{...n},lr=n=>n.map(t=>({...t,streaming:!1})),dr=(n,t)=>{let o=n!=null&&n.markdown?bn(n.markdown):null;return e=>{var i,l,d;let r=(i=e.text)!=null?i:"",s=(l=e.message.rawContent)!=null?l:null;if(t){let c=t.process({text:r,raw:s!=null?s:r,message:e.message,streaming:e.streaming});c!==null&&(r=c.text,c.persist||(e.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...e,text:r,raw:(d=s!=null?s:e.text)!=null?d:""}):o?o(r):Pn(r)}},ao=(n,t,o)=>{var Ce,qe,lt,wt,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let e=Vn(t),r=Tn.getForInstance(e.plugins);e.components&&cn.registerAll(e.components);let s=ir(),i=(Ce=e.storageAdapter)!=null?Ce:Qn(),l={},d=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")d=a;else if(a){let p=a;p.metadata&&(l=io(p.metadata)),(qe=p.messages)!=null&&qe.length&&(e={...e,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let c=()=>l,f=a=>{var E;l=(E=a({...l}))!=null?E:{},Gt()},w=e.actionParsers&&e.actionParsers.length?e.actionParsers:[En],u=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xt.message,Xt.messageAndClick],v=Mn({parsers:w,handlers:u,getMetadata:c,updateMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});v.syncFromMetadata();let g=(wt=(lt=e.launcher)==null?void 0:lt.enabled)!=null?wt:!0,N=(uo=(co=e.launcher)==null?void 0:co.autoExpand)!=null?uo:!1,I=N,m=g,k=(go=(po=e.layout)==null?void 0:po.header)==null?void 0:go.layout,C=g?N:!0,y=dr(e,v),F=(ho=(mo=e.features)==null?void 0:mo.showReasoning)!=null?ho:!0,b=(wo=(fo=e.features)==null?void 0:fo.showToolCalls)!=null?wo:!0,T={onCopy:a=>{var p,E;s.emit("message:copy",a),B!=null&&B.isClientTokenMode()&&B.submitMessageFeedback(a.id,"copy").catch($=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",$)}),(E=(p=e.messageActions)==null?void 0:p.onCopy)==null||E.call(p,a)},onFeedback:a=>{var p,E;s.emit("message:feedback",a),B!=null&&B.isClientTokenMode()&&B.submitMessageFeedback(a.messageId,a.type).catch($=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",$)}),(E=(p=e.messageActions)==null?void 0:p.onFeedback)==null||E.call(p,a)}},K=(yo=e.statusIndicator)!=null?yo:{},J=a=>{var p,E,$,A;return a==="idle"?(p=K.idleText)!=null?p:Qe.idle:a==="connecting"?(E=K.connectingText)!=null?E:Qe.connecting:a==="connected"?($=K.connectedText)!=null?$:Qe.connected:a==="error"?(A=K.errorText)!=null?A:Qe.error:Qe[a]},{wrapper:j,panel:O}=Qs(e),q=Zs(e,g),{container:U,body:Y,messagesWrapper:Q,suggestions:st,textarea:se,sendButton:D,sendButtonWrapper:Ke,composerForm:Ze,statusText:rt,introTitle:St,introSubtitle:At,closeButton:_,iconHolder:fe,headerTitle:Xe,headerSubtitle:Ve,header:Je,footer:it}=q,P=q.micButton,Pe=q.micButtonWrapper,ut=r.find(a=>a.renderHeader);if(ut!=null&&ut.renderHeader){let a=ut.renderHeader({config:e,defaultRenderer:()=>{let p=Nt({config:e,showClose:g});return rn(U,p,e),p.header},onClose:()=>Ye(!1,"user")});if(a){let p=U.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Je=a)}}let pt=r.find(a=>a.renderComposer);if(pt!=null&&pt.renderComposer){let a=pt.renderComposer({config:e,defaultRenderer:()=>ln({config:e}).footer,onSubmit:p=>{B&&!B.isStreaming()&&B.sendMessage(p)},disabled:!1});a&&(it.replaceWith(a),it=a)}(()=>{var $,A;let a=(A=($=e.layout)==null?void 0:$.slots)!=null?A:{},p=te=>{switch(te){case"body-top":return U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Q;case"footer-top":return st;case"composer":return Ze;case"footer-bottom":return rt;default:return null}},E=(te,ge)=>{var S;switch(te){case"header-left":case"header-center":case"header-right":if(te==="header-left")Je.insertBefore(ge,Je.firstChild);else if(te==="header-right")Je.appendChild(ge);else{let M=Je.querySelector(".tvw-flex-col");M?(S=M.parentNode)==null||S.insertBefore(ge,M.nextSibling):Je.appendChild(ge)}break;case"body-top":let Z=Y.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");Z?Z.replaceWith(ge):Y.insertBefore(ge,Y.firstChild);break;case"body-bottom":Y.appendChild(ge);break;case"footer-top":st.replaceWith(ge);break;case"footer-bottom":rt.replaceWith(ge);break;default:break}};for(let[te,ge]of Object.entries(a))if(ge)try{let S=ge({config:e,defaultContent:()=>p(te)});S&&E(te,S)}catch(S){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${te}":`,S)}})(),O.appendChild(U),n.appendChild(j);let yt=()=>{var ne,Ne,ht,z,ce,jt,qt,It,$t,fn,$e,wn,Qt,Zt,Yt,yn;let a=(Ne=(ne=e.launcher)==null?void 0:ne.sidebarMode)!=null?Ne:!1,p=a||((z=(ht=e.launcher)==null?void 0:ht.fullHeight)!=null?z:!1),E=(ce=e.theme)!=null?ce:{},$=(qt=(jt=e.launcher)==null?void 0:jt.position)!=null?qt:"bottom-left",A=$==="bottom-left"||$==="top-left",te=a?"none":"1px solid var(--tvw-cw-border)",ge=a?A?"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)",S=a?"0":"16px",Z=(It=E.panelBorder)!=null?It:te,M=($t=E.panelShadow)!=null?$t:ge,me=(fn=E.panelBorderRadius)!=null?fn:S;n.style.cssText="",j.style.cssText="",O.style.cssText="",U.style.cssText="",Y.style.cssText="",it.style.cssText="";let de=(wn=($e=e==null?void 0:e.launcher)==null?void 0:$e.width)!=null?wn:e==null?void 0:e.launcherWidth,Re=de!=null?de:"min(400px, calc(100vw - 24px))";a||(O.style.width=Re,O.style.maxWidth=Re),O.style.boxShadow=M,O.style.borderRadius=me,U.style.border=Z,U.style.borderRadius=me;let ve=((Qt=e.launcher)==null?void 0:Qt.enabled)===!1;if(p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.height="100%",ve&&(j.style.overflow="hidden"),O.style.display="flex",O.style.flexDirection="column",O.style.flex="1 1 0%",O.style.minHeight="0",O.style.maxHeight="100%",O.style.height="100%",O.style.overflow="hidden",U.style.display="flex",U.style.flexDirection="column",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.maxHeight="100%",U.style.overflow="hidden",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.overflowY="auto",it.style.flexShrink="0"),j.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&&!ve&&((Zt=xt[$])!=null?Zt:xt["bottom-right"]).split(" ").forEach(Ft=>j.classList.add(Ft)),a){let Et=(yn=(Yt=e.launcher)==null?void 0:Yt.sidebarWidth)!=null?yn:"420px";j.style.cssText=`
20
+ `,k.addEventListener("click",()=>{g=x,f.forEach((Y,z)=>{let j=z<x;Y.classList.toggle("selected",j),Y.setAttribute("aria-checked",z===x-1?"true":"false")})}),f.push(k),M.appendChild(k)}p.appendChild(M);let S=null;if(d){let x=document.createElement("div");x.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),x.appendChild(S),p.appendChild(x)}let R=document.createElement("div");R.className="tvw-feedback-actions";let y=document.createElement("button");y.type="button",y.className="tvw-feedback-btn tvw-feedback-btn-skip",y.textContent=l,y.addEventListener("click",()=>{o==null||o(),w.remove()});let F=document.createElement("button");return F.type="button",F.className="tvw-feedback-btn tvw-feedback-btn-submit",F.textContent=i,F.addEventListener("click",async()=>{if(g===null){M.classList.add("tvw-feedback-shake"),setTimeout(()=>M.classList.remove("tvw-feedback-shake"),500);return}F.disabled=!0,F.textContent="Submitting...";try{let x=(S==null?void 0:S.value.trim())||void 0;await t(g,x),w.remove()}catch(x){F.disabled=!1,F.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),R.appendChild(y),R.appendChild(F),p.appendChild(R),w.appendChild(p),w}function ao(n){let{onSubmit:t,onDismiss:o,title:e="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:w="Very likely"}=n,g=document.createElement("div");g.className="tvw-feedback-container tvw-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let p=null,v=document.createElement("div");v.className="tvw-feedback-content";let m=document.createElement("div");m.className="tvw-feedback-header";let N=document.createElement("h3");N.className="tvw-feedback-title",N.textContent=e,m.appendChild(N);let M=document.createElement("p");M.className="tvw-feedback-subtitle",M.textContent=r,m.appendChild(M),v.appendChild(m);let f=document.createElement("div");f.className="tvw-feedback-rating tvw-feedback-rating-nps",f.setAttribute("role","radiogroup"),f.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="tvw-feedback-labels";let R=document.createElement("span");R.className="tvw-feedback-label-low",R.textContent=c;let y=document.createElement("span");y.className="tvw-feedback-label-high",y.textContent=w,S.appendChild(R),S.appendChild(y);let F=document.createElement("div");F.className="tvw-feedback-numbers";let x=[];for(let O=0;O<=10;O++){let q=document.createElement("button");q.type="button",q.className="tvw-feedback-rating-btn tvw-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${O} out of 10`),q.textContent=String(O),q.dataset.rating=String(O),O<=6?q.classList.add("tvw-feedback-detractor"):O<=8?q.classList.add("tvw-feedback-passive"):q.classList.add("tvw-feedback-promoter"),q.addEventListener("click",()=>{p=O,x.forEach((U,J)=>{U.classList.toggle("selected",J===O),U.setAttribute("aria-checked",J===O?"true":"false")})}),x.push(q),F.appendChild(q)}f.appendChild(S),f.appendChild(F),v.appendChild(f);let k=null;if(d){let O=document.createElement("div");O.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),O.appendChild(k),v.appendChild(O)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let z=document.createElement("button");z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-skip",z.textContent=l,z.addEventListener("click",()=>{o==null||o(),g.remove()});let j=document.createElement("button");return j.type="button",j.className="tvw-feedback-btn tvw-feedback-btn-submit",j.textContent=i,j.addEventListener("click",async()=>{if(p===null){F.classList.add("tvw-feedback-shake"),setTimeout(()=>F.classList.remove("tvw-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let O=(k==null?void 0:k.value.trim())||void 0;await t(p,O),g.remove()}catch(O){j.disabled=!1,j.textContent=i,console.error("[NPS Feedback] Failed to submit:",O)}}),Y.appendChild(z),Y.appendChild(j),v.appendChild(Y),g.appendChild(v),g}var Gt="vanilla-agent-chat-history",Zr=30*1e3,lo=n=>!n||typeof n!="object"?{}:{...n},hr=n=>n.map(t=>({...t,streaming:!1})),fr=(n,t)=>{let o=n!=null&&n.markdown?An(n.markdown):null;return e=>{var i,l,d;let r=(i=e.text)!=null?i:"",s=(l=e.message.rawContent)!=null?l:null;if(t){let c=t.process({text:r,raw:s!=null?s:r,message:e.message,streaming:e.streaming});c!==null&&(r=c.text,c.persist||(e.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...e,text:r,raw:(d=s!=null?s:e.text)!=null?d:""}):o?o(r):Nn(r)}},co=(n,t,o)=>{var Ue,lt,vt,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let e=Qn(t),r=Wn.getForInstance(e.plugins);e.components&&mn.registerAll(e.components);let s=gr(),i=(Ue=e.storageAdapter)!=null?Ue:eo(),l={},d=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")d=a;else if(a){let u=a;u.metadata&&(l=lo(u.metadata)),(lt=u.messages)!=null&&lt.length&&(e={...e,initialMessages:u.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let c=()=>l,w=a=>{var T;l=(T=a({...l}))!=null?T:{},Qt()},g=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ln],p=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Vt.message,Vt.messageAndClick],v=Bn({parsers:g,handlers:p,getMetadata:c,updateMetadata:w,emit:s.emit,documentRef:typeof document!="undefined"?document:null});v.syncFromMetadata();let m=(po=(vt=e.launcher)==null?void 0:vt.enabled)!=null?po:!0,N=(mo=(go=e.launcher)==null?void 0:go.autoExpand)!=null?mo:!1,M=N,f=m,S=(fo=(ho=e.layout)==null?void 0:ho.header)==null?void 0:fo.layout,R=m?N:!0,y=fr(e,v),F=(yo=(wo=e.features)==null?void 0:wo.showReasoning)!=null?yo:!0,x=(bo=(vo=e.features)==null?void 0:vo.showToolCalls)!=null?bo:!0,k={onCopy:a=>{var u,T;s.emit("message:copy",a),b!=null&&b.isClientTokenMode()&&b.submitMessageFeedback(a.id,"copy").catch(I=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",I)}),(T=(u=e.messageActions)==null?void 0:u.onCopy)==null||T.call(u,a)},onFeedback:a=>{var u,T;s.emit("message:feedback",a),b!=null&&b.isClientTokenMode()&&b.submitMessageFeedback(a.messageId,a.type).catch(I=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",I)}),(T=(u=e.messageActions)==null?void 0:u.onFeedback)==null||T.call(u,a)}},Y=(Co=e.statusIndicator)!=null?Co:{},z=a=>{var u,T,I,C;return a==="idle"?(u=Y.idleText)!=null?u:tt.idle:a==="connecting"?(T=Y.connectingText)!=null?T:tt.connecting:a==="connected"?(I=Y.connectedText)!=null?I:tt.connected:a==="error"?(C=Y.errorText)!=null?C:tt.error:tt[a]},{wrapper:j,panel:O}=or(e),q=sr(e,m),{container:U,body:J,messagesWrapper:V,suggestions:it,textarea:oe,sendButton:D,sendButtonWrapper:Ve,composerForm:nt,statusText:at,introTitle:Tt,introSubtitle:Et,closeButton:_,iconHolder:ue,headerTitle:Ge,headerSubtitle:Qe,header:_e,footer:Ze}=q,P=q.micButton,$e=q.micButtonWrapper,ut=r.find(a=>a.renderHeader);if(ut!=null&&ut.renderHeader){let a=ut.renderHeader({config:e,defaultRenderer:()=>{let u=Ft({config:e,showClose:m});return Yt(U,u,e),u.header},onClose:()=>Ye(!1,"user")});if(a){let u=U.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(a),_e=a)}}let pt=r.find(a=>a.renderComposer);if(pt!=null&&pt.renderComposer){let a=pt.renderComposer({config:e,defaultRenderer:()=>pn({config:e}).footer,onSubmit:u=>{b&&!b.isStreaming()&&b.sendMessage(u)},disabled:!1});a&&(Ze.replaceWith(a),Ze=a)}(()=>{var I,C;let a=(C=(I=e.layout)==null?void 0:I.slots)!=null?C:{},u=G=>{switch(G){case"body-top":return U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return V;case"footer-top":return it;case"composer":return nt;case"footer-bottom":return at;default:return null}},T=(G,ae)=>{var A;switch(G){case"header-left":case"header-center":case"header-right":if(G==="header-left")_e.insertBefore(ae,_e.firstChild);else if(G==="header-right")_e.appendChild(ae);else{let X=_e.querySelector(".tvw-flex-col");X?(A=X.parentNode)==null||A.insertBefore(ae,X.nextSibling):_e.appendChild(ae)}break;case"body-top":let ee=J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ee?ee.replaceWith(ae):J.insertBefore(ae,J.firstChild);break;case"body-bottom":J.appendChild(ae);break;case"footer-top":it.replaceWith(ae);break;case"footer-bottom":at.replaceWith(ae);break;default:break}};for(let[G,ae]of Object.entries(a))if(ae)try{let A=ae({config:e,defaultContent:()=>u(G)});A&&T(G,A)}catch(A){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${G}":`,A)}})();let bt=a=>{let T=a.target.closest('button[data-expand-header="true"]');if(!T)return;let I=T.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!I)return;let C=I.getAttribute("data-message-id");if(!C)return;let G=T.getAttribute("data-bubble-type");G==="reasoning"?(Kt.has(C)?Kt.delete(C):Kt.add(C),ar(C,I)):G==="tool"&&(Xt.has(C)?Xt.delete(C):Xt.add(C),lr(C,I,e))};V.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),bt(a))}),V.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),bt(a))}),O.appendChild(U),n.appendChild(j);let Ct=()=>{var le,Ne,Oe,Xe,wt,Z,Se,jt,qt,Zt,en,bn,De,Cn,tn,nn;let a=(Ne=(le=e.launcher)==null?void 0:le.sidebarMode)!=null?Ne:!1,u=a||((Xe=(Oe=e.launcher)==null?void 0:Oe.fullHeight)!=null?Xe:!1),T=(wt=e.theme)!=null?wt:{},I=(Se=(Z=e.launcher)==null?void 0:Z.position)!=null?Se:"bottom-left",C=I==="bottom-left"||I==="top-left",G=a?"none":"1px solid var(--tvw-cw-border)",ae=a?C?"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)",A=a?"0":"16px",ee=(jt=T.panelBorder)!=null?jt:G,X=(qt=T.panelShadow)!=null?qt:ae,me=(Zt=T.panelBorderRadius)!=null?Zt:A;n.style.cssText="",j.style.cssText="",O.style.cssText="",U.style.cssText="",J.style.cssText="",Ze.style.cssText="";let $=(bn=(en=e==null?void 0:e.launcher)==null?void 0:en.width)!=null?bn:e==null?void 0:e.launcherWidth,Pe=$!=null?$:"min(400px, calc(100vw - 24px))";a||(O.style.width=Pe,O.style.maxWidth=Pe),O.style.boxShadow=X,O.style.borderRadius=me,U.style.border=ee,U.style.borderRadius=me;let we=((De=e.launcher)==null?void 0:De.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.height="100%",we&&(j.style.overflow="hidden"),O.style.display="flex",O.style.flexDirection="column",O.style.flex="1 1 0%",O.style.minHeight="0",O.style.maxHeight="100%",O.style.height="100%",O.style.overflow="hidden",U.style.display="flex",U.style.flexDirection="column",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.maxHeight="100%",U.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Ze.style.flexShrink="0"),j.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&&!we&&((Cn=At[I])!=null?Cn:At["bottom-right"]).split(" ").forEach(on=>j.classList.add(on)),a){let $t=(nn=(tn=e.launcher)==null?void 0:tn.sidebarWidth)!=null?nn:"420px";j.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
24
- width: ${Et} !important;
24
+ width: ${$t} !important;
25
25
  height: 100vh !important;
26
26
  max-height: 100vh !important;
27
27
  margin: 0 !important;
28
28
  padding: 0 !important;
29
29
  display: flex !important;
30
30
  flex-direction: column !important;
31
- ${A?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
31
+ ${C?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
32
  `,O.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
@@ -40,7 +40,7 @@ import{Marked as mr}from"marked";var hr=n=>{if(n)return n},vn=n=>{var r,s;let t=
40
40
  min-height: 0 !important;
41
41
  margin: 0 !important;
42
42
  padding: 0 !important;
43
- box-shadow: ${M} !important;
43
+ box-shadow: ${X} !important;
44
44
  border-radius: ${me} !important;
45
45
  `,O.style.setProperty("width","100%","important"),O.style.setProperty("max-width","100%","important"),U.style.cssText=`
46
46
  display: flex !important;
@@ -52,17 +52,17 @@ import{Marked as mr}from"marked";var hr=n=>{if(n)return n},vn=n=>{var r,s;let t=
52
52
  max-height: 100% !important;
53
53
  overflow: hidden !important;
54
54
  border-radius: ${me} !important;
55
- border: ${Z} !important;
56
- `,it.style.cssText=`
55
+ border: ${ee} !important;
56
+ `,Ze.style.cssText=`
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!ve){let Et="max-height: -moz-available !important; max-height: stretch !important;",Ft=a?"":"padding-top: 1.25em !important;";j.style.cssText+=Et+Ft}};yt(),Sn(n,e);let Ie=[],Ge=null,vt=()=>{Ge&&(Ge(),Ge=null),e.colorScheme==="auto"&&(Ge=Js(()=>{Sn(n,e)}))};vt(),Ie.push(()=>{Ge&&(Ge(),Ge=null)});let at=nr(st),Ee=null,B,ee=!1,ke=!0,Be=0,et=0,De=null,tt=!1,Tt=0,gt=!1,Bt=125,Ht=2e3,zt=5,Rt=50,We=new Map,ue={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},bt=(bo=(vo=e.voiceRecognition)==null?void 0:vo.autoResume)!=null?bo:!1,Pt=a=>{s.emit("voice:state",{active:ue.active,source:a,timestamp:Date.now()})},mt=()=>{f(a=>({...a,voiceState:{active:ue.active,timestamp:Date.now(),manuallyDeactivated:ue.manuallyDeactivated}}))},un=()=>{var $,A;if((($=e.voiceRecognition)==null?void 0:$.enabled)===!1)return;let a=io(l.voiceState),p=!!a.active,E=Number((A=a.timestamp)!=null?A:0);ue.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-E<Jr&&setTimeout(()=>{ue.active||(ue.manuallyDeactivated=!1,nt("restore"))},1e3)},pn=()=>B?lr(B.getMessages()).filter(a=>!a.__skipPersist):[];function Gt(a){if(!(i!=null&&i.save))return;let E={messages:a?lr(a):B?pn():[],metadata:l};try{let $=i.save(E);$ instanceof Promise&&$.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch($){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",$)}}let Ot=(a=!1)=>{if(!ke)return;let p=Date.now();tt&&p<Tt&&!a||(tt&&p>=Tt&&(tt=!1),!(!a&&!ee)&&(p-et<Bt||(et=p,De&&cancelAnimationFrame(De),De=requestAnimationFrame(()=>{tt||!ke||(gt=!0,Y.scrollTop=Y.scrollHeight,Be=Y.scrollTop,requestAnimationFrame(()=>{gt=!1}),De=null)}))))},Lt=null,gn=()=>j.querySelector("#vanilla-agent-scroll-container")||Y,mn=(a,p=500)=>{let E=a.scrollTop,$=a.clientHeight,A=a.scrollHeight,te=A-E;if(E+$>=A-2||Math.abs(te)<5)return;Lt!==null&&(cancelAnimationFrame(Lt),Lt=null);let S=performance.now(),Z=me=>1-Math.pow(1-me,3),M=me=>{let de=a.scrollHeight;de!==A&&(A=de,te=A-E);let Re=me-S,ve=Math.min(Re/p,1),ne=Z(ve),Ne=E+te*ne;a.scrollTop=Ne,ve<1?Lt=requestAnimationFrame(M):(a.scrollTop=a.scrollHeight,Lt=null)};Lt=requestAnimationFrame(M)},hn=a=>{let p=new Map;a.forEach(E=>{let $=We.get(E.id);p.set(E.id,{streaming:E.streaming,role:E.role}),!$&&E.role==="assistant"&&s.emit("assistant:message",E),E.role==="assistant"&&($!=null&&$.streaming)&&E.streaming===!1&&s.emit("assistant:complete",E)}),We.clear(),p.forEach((E,$)=>{We.set($,E)})},Dt=(a,p,E)=>{let $=document.createElement("div");p.forEach(S=>{var Re,ve;let Z=null,M=r.find(ne=>!!(S.variant==="reasoning"&&ne.renderReasoning||S.variant==="tool"&&ne.renderToolCall||!S.variant&&ne.renderMessage)),me=(Re=e.layout)==null?void 0:Re.messages;if(M)if(S.variant==="reasoning"&&S.reasoning&&M.renderReasoning){if(!F)return;Z=M.renderReasoning({message:S,defaultRenderer:()=>zn(S),config:e})}else if(S.variant==="tool"&&S.toolCall&&M.renderToolCall){if(!b)return;Z=M.renderToolCall({message:S,defaultRenderer:()=>Yn(S,e),config:e})}else M.renderMessage&&(Z=M.renderMessage({message:S,defaultRenderer:()=>{let ne=dn(S,E,me,e.messageActions,T);return S.role!=="user"&&Kn(ne,S,e,B),ne},config:e}));if(!Z&&S.role==="assistant"&&!S.variant&&e.enableComponentStreaming!==!1&&no(S)){let Ne=oo(S);if(Ne){let ht=to(Ne,{config:e,message:S,transform:E});if(ht){let z=document.createElement("div");if(z.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(" "),z.id=`bubble-${S.id}`,z.setAttribute("data-message-id",S.id),S.content&&S.content.trim()){let ce=document.createElement("div");ce.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ce.innerHTML=E({text:S.content,message:S,streaming:!!S.streaming,raw:S.rawContent}),z.appendChild(ce)}z.appendChild(ht),Z=z}}}if(!Z)if(S.variant==="reasoning"&&S.reasoning){if(!F)return;Z=zn(S)}else if(S.variant==="tool"&&S.toolCall){if(!b)return;Z=Yn(S,e)}else{let ne=(ve=e.layout)==null?void 0:ve.messages;ne!=null&&ne.renderUserMessage&&S.role==="user"?Z=ne.renderUserMessage({message:S,config:e,streaming:!!S.streaming}):ne!=null&&ne.renderAssistantMessage&&S.role==="assistant"?Z=ne.renderAssistantMessage({message:S,config:e,streaming:!!S.streaming}):Z=dn(S,E,ne,e.messageActions,T),S.role!=="user"&&Z&&Kn(Z,S,e,B)}let de=document.createElement("div");de.className="tvw-flex",de.id=`wrapper-${S.id}`,de.setAttribute("data-wrapper-id",S.id),S.role==="user"&&de.classList.add("tvw-justify-end"),de.appendChild(Z),$.appendChild(de)});let A=p.some(S=>S.role==="assistant"&&S.streaming),te=p[p.length-1],ge=(te==null?void 0:te.role)==="assistant"&&!te.streaming;if(ee&&p.some(S=>S.role==="user")&&!A&&!ge){let S=An(),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.setAttribute("data-typing-indicator","true"),Z.appendChild(S);let M=document.createElement("div");M.className="tvw-flex",M.id="wrapper-typing-indicator",M.setAttribute("data-wrapper-id","typing-indicator"),M.appendChild(Z),$.appendChild(M)}Ys(a,$),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let S=gn();mn(S)})})},_t=()=>{g&&(C?(j.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-95","tvw-opacity-0"),O.classList.add("tvw-scale-100","tvw-opacity-100"),G?G.element.style.display="none":le&&(le.style.display="none")):(j.classList.add("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-100","tvw-opacity-100"),O.classList.add("tvw-scale-95","tvw-opacity-0"),G?G.element.style.display="":le&&(le.style.display="")))},Ye=(a,p="user")=>{if(!g||C===a)return;let E=C;C=a,_t(),C&&(Te(),Ot(!0));let $={open:C,source:p,timestamp:Date.now()};C&&!E?s.emit("widget:opened",$):!C&&E&&s.emit("widget:closed",$),s.emit("widget:state",{open:C,launcherEnabled:g,voiceActive:ue.active,streaming:B.isStreaming()})},Jt=a=>{D.disabled=a,P&&(P.disabled=a),at.buttons.forEach(p=>{p.disabled=a})},L=()=>{var A,te,ge,S,Z,M,me,de,Re,ve,ne,Ne,ht,z;St.textContent=(te=(A=e.copy)==null?void 0:A.welcomeTitle)!=null?te:"Hello \u{1F44B}",At.textContent=(S=(ge=e.copy)==null?void 0:ge.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",se.placeholder=(M=(Z=e.copy)==null?void 0:Z.inputPlaceholder)!=null?M:"How can I help...",((de=(me=e.sendButton)==null?void 0:me.useIcon)!=null?de:!1)||(D.textContent=(ve=(Re=e.copy)==null?void 0:Re.sendButtonLabel)!=null?ve:"Send");let p=(Ne=(ne=e.theme)==null?void 0:ne.inputFontFamily)!=null?Ne:"sans-serif",E=(z=(ht=e.theme)==null?void 0:ht.inputFontWeight)!=null?z:"400",$=ce=>{switch(ce){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=$(p),se.style.fontWeight=E};B=new on(e,{onMessagesChanged(a){Dt(Q,a,y),B&&(a.some($=>$.role==="user")?at.render([],B,se,a):at.render(e.suggestionChips,B,se,a,e.suggestionChipsConfig)),Ot(!ee),hn(a);let p=[...a].reverse().find(E=>E.role==="user");ue.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Gt(a)},onStatusChanged(a){var $;let p=($=e.statusIndicator)!=null?$:{},E=A=>{var te,ge,S,Z;return A==="idle"?(te=p.idleText)!=null?te:Qe.idle:A==="connecting"?(ge=p.connectingText)!=null?ge:Qe.connecting:A==="connected"?(S=p.connectedText)!=null?S:Qe.connected:A==="error"?(Z=p.errorText)!=null?Z:Qe.error:Qe[A]};rt.textContent=E(a)},onStreamingChanged(a){ee=a,Jt(a),B&&Dt(Q,B.getMessages(),y),a||Ot(!0)}}),d&&d.then(a=>{var p;a&&(a.metadata&&(l=io(a.metadata),v.syncFromMetadata()),(p=a.messages)!=null&&p.length&&B.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let ae=a=>{a.preventDefault();let p=se.value.trim();p&&(se.value="",B.sendMessage(p))},ye=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),D.click())},pe=null,xe=!1,He=null,Se=null,R=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,nt=(a="user")=>{var te,ge,S,Z;if(xe||B.isStreaming())return;let p=R();if(!p)return;pe=new p;let $=(ge=((te=e.voiceRecognition)!=null?te:{}).pauseDuration)!=null?ge:2e3;pe.continuous=!0,pe.interimResults=!0,pe.lang="en-US";let A=se.value;pe.onresult=M=>{let me="",de="";for(let ve=0;ve<M.results.length;ve++){let ne=M.results[ve],Ne=ne[0].transcript;ne.isFinal?me+=Ne+" ":de=Ne}let Re=A+me+de;se.value=Re,He&&clearTimeout(He),(me||de)&&(He=window.setTimeout(()=>{let ve=se.value.trim();ve&&pe&&xe&&(V(),se.value="",B.sendMessage(ve,{viaVoice:!0}))},$))},pe.onerror=M=>{M.error!=="no-speech"&&V()},pe.onend=()=>{if(xe){let M=se.value.trim();M&&M!==A.trim()&&(se.value="",B.sendMessage(M,{viaVoice:!0})),V()}};try{if(pe.start(),xe=!0,ue.active=!0,a!=="system"&&(ue.manuallyDeactivated=!1),Pt(a),mt(),P){Se={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor};let M=(S=e.voiceRecognition)!=null?S:{},me=(Z=M.recordingBackgroundColor)!=null?Z:"#ef4444",de=M.recordingIconColor,Re=M.recordingBorderColor;if(P.classList.add("tvw-voice-recording"),P.style.backgroundColor=me,de){P.style.color=de;let ve=P.querySelector("svg");ve&&ve.setAttribute("stroke",de)}Re&&(P.style.borderColor=Re),P.setAttribute("aria-label","Stop voice recognition")}}catch{V("system")}},V=(a="user")=>{if(xe){if(xe=!1,He&&(clearTimeout(He),He=null),pe){try{pe.stop()}catch{}pe=null}if(ue.active=!1,Pt(a),mt(),P){if(P.classList.remove("tvw-voice-recording"),Se){P.style.backgroundColor=Se.backgroundColor,P.style.color=Se.color,P.style.borderColor=Se.borderColor;let p=P.querySelector("svg");p&&p.setAttribute("stroke",Se.color||"currentColor"),Se=null}P.setAttribute("aria-label","Start voice recognition")}}},H=(a,p)=>{var Ne,ht,z,ce,jt,qt,It;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let $=h("div","tvw-send-button-wrapper"),A=h("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let te=(Ne=a==null?void 0:a.iconName)!=null?Ne:"mic",ge=(ht=p==null?void 0:p.size)!=null?ht:"40px",S=(z=a==null?void 0:a.iconSize)!=null?z:ge,Z=parseFloat(S)||24,M=(ce=a==null?void 0:a.backgroundColor)!=null?ce:p==null?void 0:p.backgroundColor,me=(jt=a==null?void 0:a.iconColor)!=null?jt:p==null?void 0:p.textColor;A.style.width=S,A.style.height=S,A.style.minWidth=S,A.style.minHeight=S,A.style.fontSize="18px",A.style.lineHeight="1";let de=me||"currentColor",Re=we(te,Z,de,1.5);Re?(A.appendChild(Re),A.style.color=de):(A.textContent="\u{1F3A4}",A.style.color=de),M?A.style.backgroundColor=M:A.classList.add("tvw-bg-cw-primary"),me?A.style.color=me:!me&&!(p!=null&&p.textColor)&&A.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(A.style.borderWidth=a.borderWidth,A.style.borderStyle="solid"),a!=null&&a.borderColor&&(A.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(A.style.paddingLeft=a.paddingX,A.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(A.style.paddingTop=a.paddingY,A.style.paddingBottom=a.paddingY),$.appendChild(A);let ve=(qt=a==null?void 0:a.tooltipText)!=null?qt:"Start voice recognition";if(((It=a==null?void 0:a.showTooltip)!=null?It:!1)&&ve){let $t=h("div","tvw-send-button-tooltip");$t.textContent=ve,$.appendChild($t)}return{micButton:A,micButtonWrapper:$}},x=()=>{if(xe){let a=se.value.trim();ue.manuallyDeactivated=!0,mt(),V("user"),a&&(se.value="",B.sendMessage(a))}else ue.manuallyDeactivated=!1,mt(),nt("user")};P&&(P.addEventListener("click",x),Ie.push(()=>{V("system"),P&&P.removeEventListener("click",x)}));let X=s.on("assistant:complete",()=>{bt&&(ue.active||ue.manuallyDeactivated||bt==="assistant"&&!ue.lastUserMessageWasVoice||setTimeout(()=>{!ue.active&&!ue.manuallyDeactivated&&nt("auto")},600))});Ie.push(X);let Ae=()=>{Ye(!C,"user")},G=null,le=null;if(g){let a=r.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:e,defaultRenderer:()=>sn(e,Ae).element,onToggle:Ae});p&&(le=p)}le||(G=sn(e,Ae))}G?n.appendChild(G.element):le&&n.appendChild(le),_t(),at.render(e.suggestionChips,B,se,void 0,e.suggestionChipsConfig),L(),Jt(B.isStreaming()),Ot(!0),un();let Te=()=>{var E,$,A,te,ge,S,Z,M;let a=($=(E=e.launcher)==null?void 0:E.sidebarMode)!=null?$:!1,p=a||((te=(A=e.launcher)==null?void 0:A.fullHeight)!=null?te:!1);if(!g){O.style.height="",O.style.width="";return}if(!a){let me=(S=(ge=e==null?void 0:e.launcher)==null?void 0:ge.width)!=null?S:e==null?void 0:e.launcherWidth,de=me!=null?me:"min(400px, calc(100vw - 24px))";O.style.width=de,O.style.maxWidth=de}if(!p){let me=window.innerHeight,de=64,Re=(M=(Z=e.launcher)==null?void 0:Z.heightOffset)!=null?M:0,ve=Math.max(200,me-de),ne=Math.min(640,ve),Ne=Math.max(200,ne-Re);O.style.height=`${Ne}px`}};Te(),window.addEventListener("resize",Te),Ie.push(()=>window.removeEventListener("resize",Te)),Be=Y.scrollTop;let _e=()=>{let a=Y.scrollTop,p=Y.scrollHeight,E=Y.clientHeight,$=p-a-E,A=Math.abs(a-Be);if(Be=a,!gt&&!(A<=zt)){if(!ke&&$<Rt){tt=!1,ke=!0;return}ke&&$>Rt&&(tt=!0,Tt=Date.now()+Ht,ke=!1)}};Y.addEventListener("scroll",_e,{passive:!0}),Ie.push(()=>Y.removeEventListener("scroll",_e)),Ie.push(()=>{De&&cancelAnimationFrame(De)});let Fe=()=>{_&&(Ee&&(_.removeEventListener("click",Ee),Ee=null),g?(_.style.display="",Ee=()=>{C=!1,_t()},_.addEventListener("click",Ee)):_.style.display="none")};Fe(),(()=>{let{clearChatButton:a}=q;a&&a.addEventListener("click",()=>{B.clearMessages();try{localStorage.removeItem(Vt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vt}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Vt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let E=i.clear();E instanceof Promise&&E.catch($=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",$)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},v.syncFromMetadata()})})(),Ze.addEventListener("submit",ae),se.addEventListener("keydown",ye),Ie.push(()=>{Ze.removeEventListener("submit",ae),se.removeEventListener("keydown",ye)}),Ie.push(()=>{B.cancel()}),G?Ie.push(()=>{G==null||G.destroy()}):le&&Ie.push(()=>{le==null||le.remove()});let re={update(a){var xo,So,Ao,To,Eo,Mo,ko,Wo,Lo,Bo,Ho,Ro,Po,Io,$o,Fo,No,Oo,Do,_o,jo,qo,Uo,zo,Jo,Yo,Ko,Xo,Vo,Go,Qo,Zo,es,ts,ns,os,ss,rs,is,as,ls,ds,cs,us,ps,gs,ms,hs,fs,ws,ys,vs,bs,Cs,xs,Ss,As,Ts,Es,Ms,ks,Ws,Ls,Bs,Hs,Rs,Ps,Is;let p=e.toolCall,E=e.colorScheme;e={...e,...a},yt(),Sn(n,e),e.colorScheme!==E&&vt();let $=Tn.getForInstance(e.plugins);if(r.length=0,r.push(...$),g=(So=(xo=e.launcher)==null?void 0:xo.enabled)!=null?So:!0,N=(To=(Ao=e.launcher)==null?void 0:Ao.autoExpand)!=null?To:!1,F=(Mo=(Eo=e.features)==null?void 0:Eo.showReasoning)!=null?Mo:!0,b=(Wo=(ko=e.features)==null?void 0:ko.showToolCalls)!=null?Wo:!0,((Lo=e.launcher)==null?void 0:Lo.enabled)===!1&&G&&(G.destroy(),G=null),((Bo=e.launcher)==null?void 0:Bo.enabled)===!1&&le&&(le.remove(),le=null),((Ho=e.launcher)==null?void 0:Ho.enabled)!==!1&&!G&&!le){let W=r.find(he=>he.renderLauncher);if(W!=null&&W.renderLauncher){let he=W.renderLauncher({config:e,defaultRenderer:()=>sn(e,Ae).element,onToggle:Ae});he&&(le=he,n.appendChild(le))}le||(G=sn(e,Ae),n.appendChild(G.element))}G&&G.update(e),Xe&&((Ro=e.launcher)==null?void 0:Ro.title)!==void 0&&(Xe.textContent=e.launcher.title),Ve&&((Po=e.launcher)==null?void 0:Po.subtitle)!==void 0&&(Ve.textContent=e.launcher.subtitle);let A=(Io=e.layout)==null?void 0:Io.header;if((A==null?void 0:A.layout)!==k&&Je){let W=A?an(e,A,{showClose:g,onClose:()=>Ye(!1,"user")}):Nt({config:e,showClose:g,onClose:()=>Ye(!1,"user")});Je.replaceWith(W.header),Je=W.header,fe=W.iconHolder,Xe=W.headerTitle,Ve=W.headerSubtitle,_=W.closeButton,k=A==null?void 0:A.layout}else if(A&&(fe&&(fe.style.display=A.showIcon===!1?"none":""),Xe&&(Xe.style.display=A.showTitle===!1?"none":""),Ve&&(Ve.style.display=A.showSubtitle===!1?"none":""),_&&(_.style.display=A.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let W=A.showClearChat;if(W!==void 0){q.clearChatButtonWrapper.style.display=W?"":"none";let{closeButtonWrapper:he}=q;he&&!he.classList.contains("tvw-absolute")&&(W?he.classList.remove("tvw-ml-auto"):he.classList.add("tvw-ml-auto"))}}g!==m?g?Ye(N,"auto"):(C=!0,_t()):N!==I&&Ye(N,"auto"),I=N,m=g,Te(),Fe(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&B&&Dt(Q,B.getMessages(),y);let M=($o=e.launcher)!=null?$o:{},me=(Fo=M.headerIconHidden)!=null?Fo:!1,de=(Oo=(No=e.layout)==null?void 0:No.header)==null?void 0:Oo.showIcon,Re=me||de===!1,ve=M.headerIconName,ne=(Do=M.headerIconSize)!=null?Do:"48px";if(fe){let W=U.querySelector(".tvw-border-b-cw-divider"),he=W==null?void 0:W.querySelector(".tvw-flex-col");if(Re)fe.style.display="none",W&&he&&!W.contains(he)&&W.insertBefore(he,W.firstChild);else{if(fe.style.display="",fe.style.height=ne,fe.style.width=ne,W&&he&&(W.contains(fe)?fe.nextSibling!==he&&(fe.remove(),W.insertBefore(fe,he)):W.insertBefore(fe,he)),ve){let oe=parseFloat(ne)||24,Me=we(ve,oe*.6,"#ffffff",2);Me?fe.replaceChildren(Me):fe.textContent=(_o=M.agentIconText)!=null?_o:"\u{1F4AC}"}else if(M.iconUrl){let oe=fe.querySelector("img");if(oe)oe.src=M.iconUrl,oe.style.height=ne,oe.style.width=ne;else{let Me=document.createElement("img");Me.src=M.iconUrl,Me.alt="",Me.className="tvw-rounded-xl tvw-object-cover",Me.style.height=ne,Me.style.width=ne,fe.replaceChildren(Me)}}else{let oe=fe.querySelector("svg"),Me=fe.querySelector("img");(oe||Me)&&fe.replaceChildren(),fe.textContent=(jo=M.agentIconText)!=null?jo:"\u{1F4AC}"}let Oe=fe.querySelector("img");Oe&&(Oe.style.height=ne,Oe.style.width=ne)}}let Ne=(Uo=(qo=e.layout)==null?void 0:qo.header)==null?void 0:Uo.showTitle,ht=(Jo=(zo=e.layout)==null?void 0:zo.header)==null?void 0:Jo.showSubtitle;if(Xe&&(Xe.style.display=Ne===!1?"none":""),Ve&&(Ve.style.display=ht===!1?"none":""),_){((Ko=(Yo=e.layout)==null?void 0:Yo.header)==null?void 0:Ko.showCloseButton)===!1?_.style.display="none":_.style.display="";let he=(Xo=M.closeButtonSize)!=null?Xo:"32px",Oe=(Vo=M.closeButtonPlacement)!=null?Vo:"inline";_.style.height=he,_.style.width=he;let{closeButtonWrapper:oe}=q,Me=Oe==="top-right",dt=oe==null?void 0:oe.classList.contains("tvw-absolute");if(oe&&Me!==dt)if(oe.remove(),Me)oe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",U.style.position="relative",U.appendChild(oe);else{let ie=(Qo=(Go=M.clearChat)==null?void 0:Go.placement)!=null?Qo:"inline",ze=(es=(Zo=M.clearChat)==null?void 0:Zo.enabled)!=null?es:!0;oe.className=ze&&ie==="inline"?"":"tvw-ml-auto";let ct=U.querySelector(".tvw-border-b-cw-divider");ct&&ct.appendChild(oe)}if(M.closeButtonColor?(_.style.color=M.closeButtonColor,_.classList.remove("tvw-text-cw-muted")):(_.style.color="",_.classList.add("tvw-text-cw-muted")),M.closeButtonBackgroundColor?(_.style.backgroundColor=M.closeButtonBackgroundColor,_.classList.remove("hover:tvw-bg-gray-100")):(_.style.backgroundColor="",_.classList.add("hover:tvw-bg-gray-100")),M.closeButtonBorderWidth||M.closeButtonBorderColor){let ie=M.closeButtonBorderWidth||"0px",ze=M.closeButtonBorderColor||"transparent";_.style.border=`${ie} solid ${ze}`,_.classList.remove("tvw-border-none")}else _.style.border="",_.classList.add("tvw-border-none");M.closeButtonBorderRadius?(_.style.borderRadius=M.closeButtonBorderRadius,_.classList.remove("tvw-rounded-full")):(_.style.borderRadius="",_.classList.add("tvw-rounded-full")),M.closeButtonPaddingX?(_.style.paddingLeft=M.closeButtonPaddingX,_.style.paddingRight=M.closeButtonPaddingX):(_.style.paddingLeft="",_.style.paddingRight=""),M.closeButtonPaddingY?(_.style.paddingTop=M.closeButtonPaddingY,_.style.paddingBottom=M.closeButtonPaddingY):(_.style.paddingTop="",_.style.paddingBottom="");let ot=(ts=M.closeButtonIconName)!=null?ts:"x",kt=(ns=M.closeButtonIconText)!=null?ns:"\xD7";_.innerHTML="";let ft=we(ot,"20px",M.closeButtonColor||"",2);ft?_.appendChild(ft):_.textContent=kt;let Ue=(os=M.closeButtonTooltipText)!=null?os:"Close chat",Ct=(ss=M.closeButtonShowTooltip)!=null?ss:!0;if(_.setAttribute("aria-label",Ue),oe&&(oe._cleanupTooltip&&(oe._cleanupTooltip(),delete oe._cleanupTooltip),Ct&&Ue)){let ie=null,ze=()=>{if(ie||!_)return;ie=h("div","tvw-clear-chat-tooltip"),ie.textContent=Ue;let nn=h("div");nn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(nn);let Ut=_.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Ut.left+Ut.width/2}px`,ie.style.top=`${Ut.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};oe.addEventListener("mouseenter",ze),oe.addEventListener("mouseleave",ct),_.addEventListener("focus",ze),_.addEventListener("blur",ct),oe._cleanupTooltip=()=>{ct(),oe&&(oe.removeEventListener("mouseenter",ze),oe.removeEventListener("mouseleave",ct)),_&&(_.removeEventListener("focus",ze),_.removeEventListener("blur",ct))}}}let{clearChatButton:z,clearChatButtonWrapper:ce}=q;if(z){let W=(rs=M.clearChat)!=null?rs:{},he=(is=W.enabled)!=null?is:!0,Oe=(ls=(as=e.layout)==null?void 0:as.header)==null?void 0:ls.showClearChat,oe=Oe!==void 0?Oe:he,Me=(ds=W.placement)!=null?ds:"inline";if(ce){ce.style.display=oe?"":"none";let{closeButtonWrapper:dt}=q;dt&&!dt.classList.contains("tvw-absolute")&&(oe?dt.classList.remove("tvw-ml-auto"):dt.classList.add("tvw-ml-auto"));let ot=Me==="top-right",kt=ce.classList.contains("tvw-absolute");if(ot!==kt&&oe){if(ce.remove(),ot)ce.className="tvw-absolute tvw-top-4 tvw-z-50",ce.style.right="48px",U.style.position="relative",U.appendChild(ce);else{ce.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",ce.style.right="";let Ue=U.querySelector(".tvw-border-b-cw-divider"),Ct=q.closeButtonWrapper;Ue&&Ct&&Ct.parentElement===Ue?Ue.insertBefore(ce,Ct):Ue&&Ue.appendChild(ce)}let ft=q.closeButtonWrapper;ft&&!ft.classList.contains("tvw-absolute")&&(ot?ft.classList.add("tvw-ml-auto"):ft.classList.remove("tvw-ml-auto"))}}if(oe){let dt=(cs=W.size)!=null?cs:"32px";z.style.height=dt,z.style.width=dt;let ot=(us=W.iconName)!=null?us:"refresh-cw",kt=(ps=W.iconColor)!=null?ps:"";z.innerHTML="";let ft=we(ot,"20px",kt||"",2);if(ft&&z.appendChild(ft),kt?(z.style.color=kt,z.classList.remove("tvw-text-cw-muted")):(z.style.color="",z.classList.add("tvw-text-cw-muted")),W.backgroundColor?(z.style.backgroundColor=W.backgroundColor,z.classList.remove("hover:tvw-bg-gray-100")):(z.style.backgroundColor="",z.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let ie=W.borderWidth||"0px",ze=W.borderColor||"transparent";z.style.border=`${ie} solid ${ze}`,z.classList.remove("tvw-border-none")}else z.style.border="",z.classList.add("tvw-border-none");W.borderRadius?(z.style.borderRadius=W.borderRadius,z.classList.remove("tvw-rounded-full")):(z.style.borderRadius="",z.classList.add("tvw-rounded-full")),W.paddingX?(z.style.paddingLeft=W.paddingX,z.style.paddingRight=W.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),W.paddingY?(z.style.paddingTop=W.paddingY,z.style.paddingBottom=W.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let Ue=(gs=W.tooltipText)!=null?gs:"Clear chat",Ct=(ms=W.showTooltip)!=null?ms:!0;if(z.setAttribute("aria-label",Ue),ce&&(ce._cleanupTooltip&&(ce._cleanupTooltip(),delete ce._cleanupTooltip),Ct&&Ue)){let ie=null,ze=()=>{if(ie||!z)return;ie=h("div","tvw-clear-chat-tooltip"),ie.textContent=Ue;let nn=h("div");nn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(nn);let Ut=z.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Ut.left+Ut.width/2}px`,ie.style.top=`${Ut.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};ce.addEventListener("mouseenter",ze),ce.addEventListener("mouseleave",ct),z.addEventListener("focus",ze),z.addEventListener("blur",ct),ce._cleanupTooltip=()=>{ct(),ce&&(ce.removeEventListener("mouseenter",ze),ce.removeEventListener("mouseleave",ct)),z&&(z.removeEventListener("focus",ze),z.removeEventListener("blur",ct))}}}}let jt=e.actionParsers&&e.actionParsers.length?e.actionParsers:[En],qt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xt.message,Xt.messageAndClick];v=Mn({parsers:jt,handlers:qt,getMetadata:c,updateMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),y=dr(e,v),B.updateConfig(e),Dt(Q,B.getMessages(),y),at.render(e.suggestionChips,B,se,void 0,e.suggestionChipsConfig),L(),Jt(B.isStreaming());let It=((hs=e.voiceRecognition)==null?void 0:hs.enabled)===!0,$t=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),fn=It&&$t;if(Ze.classList.remove("tvw-gap-1","tvw-gap-3"),Ze.classList.add(fn?"tvw-gap-1":"tvw-gap-3"),It&&$t)if(!P||!Pe){let W=H(e.voiceRecognition,e.sendButton);W&&(P=W.micButton,Pe=W.micButtonWrapper,Ze.insertBefore(Pe,Ke),P.addEventListener("click",x),P.disabled=B.isStreaming())}else{let W=(fs=e.voiceRecognition)!=null?fs:{},he=(ws=e.sendButton)!=null?ws:{},Oe=(ys=W.iconName)!=null?ys:"mic",oe=(vs=he.size)!=null?vs:"40px",Me=(bs=W.iconSize)!=null?bs:oe,dt=parseFloat(Me)||24;P.style.width=Me,P.style.height=Me,P.style.minWidth=Me,P.style.minHeight=Me;let ot=(xs=(Cs=W.iconColor)!=null?Cs:he.textColor)!=null?xs:"currentColor";P.innerHTML="";let kt=we(Oe,dt,ot,2);kt?P.appendChild(kt):P.textContent="\u{1F3A4}";let ft=(Ss=W.backgroundColor)!=null?Ss:he.backgroundColor;ft?(P.style.backgroundColor=ft,P.classList.remove("tvw-bg-cw-primary")):(P.style.backgroundColor="",P.classList.add("tvw-bg-cw-primary")),ot?(P.style.color=ot,P.classList.remove("tvw-text-white")):!ot&&!he.textColor&&(P.style.color="",P.classList.add("tvw-text-white")),W.borderWidth?(P.style.borderWidth=W.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),W.borderColor?P.style.borderColor=W.borderColor:P.style.borderColor="",W.paddingX?(P.style.paddingLeft=W.paddingX,P.style.paddingRight=W.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),W.paddingY?(P.style.paddingTop=W.paddingY,P.style.paddingBottom=W.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let Ue=Pe==null?void 0:Pe.querySelector(".tvw-send-button-tooltip"),Ct=(As=W.tooltipText)!=null?As:"Start voice recognition";if(((Ts=W.showTooltip)!=null?Ts:!1)&&Ct)if(Ue)Ue.textContent=Ct,Ue.style.display="";else{let ze=document.createElement("div");ze.className="tvw-send-button-tooltip",ze.textContent=Ct,Pe==null||Pe.insertBefore(ze,P)}else Ue&&(Ue.style.display="none");Pe.style.display="",P.disabled=B.isStreaming()}else P&&Pe&&(Pe.style.display="none",xe&&V());let $e=(Es=e.sendButton)!=null?Es:{},wn=(Ms=$e.useIcon)!=null?Ms:!1,Qt=(ks=$e.iconText)!=null?ks:"\u2191",Zt=$e.iconName,Yt=(Ws=$e.tooltipText)!=null?Ws:"Send message",yn=(Ls=$e.showTooltip)!=null?Ls:!1,Et=(Bs=$e.size)!=null?Bs:"40px",Ft=$e.backgroundColor,Mt=$e.textColor;if(wn){if(D.style.width=Et,D.style.height=Et,D.style.minWidth=Et,D.style.minHeight=Et,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",Zt){let W=parseFloat(Et)||24,he=Mt&&typeof Mt=="string"&&Mt.trim()?Mt.trim():"currentColor",Oe=we(Zt,W,he,2);Oe?(D.appendChild(Oe),D.style.color=he):(D.textContent=Qt,Mt?D.style.color=Mt:D.classList.add("tvw-text-white"))}else D.textContent=Qt,Mt?D.style.color=Mt:D.classList.add("tvw-text-white");D.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Ft?(D.style.backgroundColor=Ft,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Rs=(Hs=e.copy)==null?void 0:Hs.sendButtonLabel)!=null?Rs:"Send",D.style.width="",D.style.height="",D.style.minWidth="",D.style.minHeight="",D.style.fontSize="",D.style.lineHeight="",D.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Ft?(D.style.backgroundColor=Ft,D.classList.remove("tvw-bg-cw-accent")):D.classList.add("tvw-bg-cw-accent"),Mt?D.style.color=Mt:D.classList.add("tvw-text-white");$e.borderWidth?(D.style.borderWidth=$e.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),$e.borderColor?D.style.borderColor=$e.borderColor:D.style.borderColor="",$e.paddingX?(D.style.paddingLeft=$e.paddingX,D.style.paddingRight=$e.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),$e.paddingY?(D.style.paddingTop=$e.paddingY,D.style.paddingBottom=$e.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let en=Ke==null?void 0:Ke.querySelector(".tvw-send-button-tooltip");if(yn&&Yt)if(en)en.textContent=Yt,en.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=Yt,Ke==null||Ke.insertBefore(W,D)}else en&&(en.style.display="none");let tn=(Ps=e.statusIndicator)!=null?Ps:{},gr=(Is=tn.visible)!=null?Is:!0;if(rt.style.display=gr?"":"none",B){let W=B.getStatus(),he=Oe=>{var oe,Me,dt,ot;return Oe==="idle"?(oe=tn.idleText)!=null?oe:Qe.idle:Oe==="connecting"?(Me=tn.connectingText)!=null?Me:Qe.connecting:Oe==="connected"?(dt=tn.connectedText)!=null?dt:Qe.connected:Oe==="error"?(ot=tn.errorText)!=null?ot:Qe.error:Qe[Oe]};rt.textContent=he(W)}},open(){g&&Ye(!0,"api")},close(){g&&Ye(!1,"api")},toggle(){g&&Ye(!C,"api")},clearChat(){B.clearMessages();try{localStorage.removeItem(Vt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vt}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Vt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},v.syncFromMetadata()},setMessage(a){return!se||B.isStreaming()?!1:(!C&&g&&Ye(!0,"system"),se.value=a,se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(B.isStreaming())return!1;let p=(a==null?void 0:a.trim())||se.value.trim();return p?(!C&&g&&Ye(!0,"system"),se.value="",B.sendMessage(p),!0):!1},startVoiceRecognition(){return xe||B.isStreaming()||!R()?!1:(!C&&g&&Ye(!0,"system"),ue.manuallyDeactivated=!1,mt(),nt("user"),!0)},stopVoiceRecognition(){return xe?(ue.manuallyDeactivated=!0,mt(),V("user"),!0):!1},injectTestMessage(a){!C&&g&&Ye(!0,"system"),B.injectTestEvent(a)},getMessages(){return B.getMessages()},getStatus(){return B.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){f(a)},on(a,p){return s.on(a,p)},off(a,p){s.off(a,p)},isOpen(){return g&&C},isVoiceActive(){return ue.active},getState(){return{open:g&&C,launcherEnabled:g,voiceActive:ue.active,streaming:B.isStreaming()}},showCSATFeedback(a){!C&&g&&Ye(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let E=so({onSubmit:async($,A)=>{var te;B.isClientTokenMode()&&await B.submitCSATFeedback($,A),(te=a==null?void 0:a.onSubmit)==null||te.call(a,$,A)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!C&&g&&Ye(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let E=ro({onSubmit:async($,A)=>{var te;B.isClientTokenMode()&&await B.submitNPSFeedback($,A),(te=a==null?void 0:a.onSubmit)==null||te.call(a,$,A)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,p){return B.submitCSATFeedback(a,p)},async submitNPSFeedback(a,p){return B.submitNPSFeedback(a,p)},destroy(){Ie.forEach(a=>a()),j.remove(),G==null||G.destroy(),le==null||le.remove(),Ee&&_.removeEventListener("click",Ee)}};if((((Co=o==null?void 0:o.debugTools)!=null?Co:!1)||!!e.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:re,getMessages:re.getMessages,getStatus:re.getStatus,getMetadata:re.getPersistentMetadata,updateMetadata:re.updatePersistentMetadata,clearHistory:()=>re.clearChat(),setVoiceActive:E=>E?re.startVoiceRecognition():re.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Ie.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return re};var lo={},Yr=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 t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},Kr=()=>{try{if(typeof lo!="undefined"&&lo.url)return new URL("../widget.css",lo.url).href}catch{}return null},cr=n=>{let t=Kr(),o=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let r=e.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-vanilla-agent","true"),n.insertBefore(e,n.firstChild)}else o();else if(!document.head.querySelector("link[data-vanilla-agent]")&&t){let r=document.createElement("link");r.rel="stylesheet",r.href=t,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},ur=n=>{var c,f,w,u;let t=Yr(n.target),o=document.createElement("div");o.className="vanilla-agent-host";let e=(w=(f=(c=n.config)==null?void 0:c.launcher)==null?void 0:f.enabled)!=null?w:!0;e||(o.style.height="100%"),t.appendChild(o);let r=n.useShadowDom===!0,s,i;if(r){let v=o.attachShadow({mode:"open"});i=v,s=document.createElement("div"),s.id="vanilla-agent-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),v.appendChild(s),cr(v)}else i=o,s=document.createElement("div"),s.id="vanilla-agent-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),o.appendChild(s),cr(o);let l=ao(s,n.config,{debugTools:n.debugTools});(u=n.onReady)==null||u.call(n);let d={...l,host:o,destroy(){l.destroy(),o.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=d),d};function Xr(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function kn(n){var t,o;return(o=(t=n.parserType)!=null?t:Xr(n.streamParser))!=null?o:"plain"}function Wn(n,t){let o=[];return n.toolCall&&(o.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,r])=>{typeof r=="string"&&o.push(`${t} ${e}: "${r}",`)}),o.push(`${t}},`)),o}function Ln(n,t){let o=[];return n.messageActions&&Object.entries(n.messageActions).some(([r,s])=>r!=="onFeedback"&&r!=="onCopy"&&s!==void 0)&&(o.push(`${t}messageActions: {`),Object.entries(n.messageActions).forEach(([r,s])=>{r==="onFeedback"||r==="onCopy"||(typeof s=="string"?o.push(`${t} ${r}: "${s}",`):typeof s=="boolean"&&o.push(`${t} ${r}: ${s},`))}),o.push(`${t}},`)),o}function Bn(n,t){let o=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,r=n.markdown.disableDefaultStyles!==void 0;(e||r)&&(o.push(`${t}markdown: {`),e&&(o.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([s,i])=>{typeof i=="string"?o.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${s}: ${i},`)}),o.push(`${t} },`)),r&&o.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),o.push(`${t}},`))}return o}function Hn(n,t){let o=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(s=>s!=="render"),r=n.layout.messages&&Object.keys(n.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||r)&&(o.push(`${t}layout: {`),e&&(o.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?o.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${s}: ${i},`))}),o.push(`${t} },`)),r&&(o.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(o.push(`${t} avatar: {`),Object.entries(i).forEach(([l,d])=>{typeof d=="string"?o.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&o.push(`${t} ${l}: ${d},`)}),o.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(o.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?o.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&o.push(`${t} ${d}: ${c},`))}),o.push(`${t} },`)):typeof i=="string"?o.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${s}: ${i},`))}),o.push(`${t} },`)),o.push(`${t}},`))}return o}function Vr(n,t="esm"){let o={...n};return delete o.postprocessMessage,delete o.initialMessages,t==="esm"?Gr(o):t==="script-installer"?ei(o):t==="script-advanced"?ni(o):t==="react-component"?Qr(o):t==="react-advanced"?Zr(o):ti(o)}function Gr(n){let t=kn(n),o=t!=="plain",e=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),o&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"?e.push(` ${r}: ${s},`):typeof s=="number"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{e.push(` ${r}: ${s},`)}),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(" },")),e.push(...Wn(n," ")),e.push(...Ln(n," ")),e.push(...Bn(n," ")),e.push(...Hn(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push("});"),e.join(`
61
- `)}function Qr(n){let t=kn(n),o=t!=="plain",e=["// 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&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),o&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"?e.push(` ${r}: ${s},`):typeof s=="number"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{e.push(` ${r}: ${s},`)}),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(" },")),e.push(...Wn(n," ")),e.push(...Ln(n," ")),e.push(...Bn(n," ")),e.push(...Hn(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),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 in your app:"),e.push("// import { ChatWidget } from './components/ChatWidget';"),e.push("//"),e.push("// export default function App() {"),e.push("// return ("),e.push("// <div>"),e.push("// {/* Your app content */}"),e.push("// <ChatWidget />"),e.push("// </div>"),e.push("// );"),e.push("// }"),e.join(`
62
- `)}function Zr(n){let t=["// 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&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,e])=>{t.push(` ${o}: "${e}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,e])=>{typeof e=="string"?t.push(` ${o}: "${e}",`):typeof e=="boolean"&&t.push(` ${o}: ${e},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,e])=>{t.push(` ${o}: "${e}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,e])=>{typeof e=="string"?t.push(` ${o}: "${e}",`):typeof e=="boolean"&&t.push(` ${o}: ${e},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,e])=>{typeof e=="string"?t.push(` ${o}: "${e}",`):typeof e=="boolean"?t.push(` ${o}: ${e},`):typeof e=="number"&&t.push(` ${o}: ${e},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,e])=>{typeof e=="string"?t.push(` ${o}: "${e}",`):typeof e=="boolean"&&t.push(` ${o}: ${e},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,e])=>{t.push(` ${o}: ${e},`)}),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(" },")),t.push(...Wn(n," ")),t.push(...Ln(n," ")),t.push(...Bn(n," ")),t.push(...Hn(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" initialMessages: loadSavedMessages(),"),t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),t.push(" if (!parsed || typeof parsed !== 'object') return null;"),t.push(" // Extract display text based on action type"),t.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),t.push(" if (parsed.action === 'message') return parsed.text || '';"),t.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),t.push(" return parsed.text || null;"),t.push(" }),"),t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Custom parser for markdown-wrapped JSON"),t.push(" ({ text, message }: any) => {"),t.push(" const jsonSource = (message as any).rawContent || text || message.content;"),t.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),t.push(" // Strip markdown code fences"),t.push(" let cleanJson = jsonSource"),t.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),t.push(" .replace(/\\n?```\\s*$/, '')"),t.push(" .trim();"),t.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),t.push(" try {"),t.push(" const parsed = JSON.parse(cleanJson);"),t.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),t.push(" } catch (e) { return null; }"),t.push(" return null;"),t.push(" }"),t.push(" ],"),t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(" (action: any, context: any) => {"),t.push(" if (action.type !== 'nav_then_click') return;"),t.push(" const payload = action.payload || action.raw || {};"),t.push(" const url = payload?.page;"),t.push(" const text = payload?.on_load_text || 'Navigating...';"),t.push(" if (!url) return { handled: true, displayText: text };"),t.push(" // Check if already processed"),t.push(" const messageId = context.message?.id;"),t.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),t.push(" const actionKey = `nav_${messageId}_${url}`;"),t.push(" if (processedActions.includes(actionKey)) {"),t.push(" return { handled: true, displayText: text };"),t.push(" }"),t.push(" processedActions.push(actionKey);"),t.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),t.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),t.push(" window.location.href = targetUrl;"),t.push(" return { handled: true, displayText: text };"),t.push(" }"),t.push(" ],"),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),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: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
63
- `)}function pr(n){var r;let t=kn(n),o=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.flowId&&(e.flowId=n.flowId),o&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((r=n.suggestionChips)==null?void 0:r.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let s={};Object.entries(n.toolCall).forEach(([i,l])=>{typeof l=="string"&&(s[i]=l)}),Object.keys(s).length>0&&(e.toolCall=s)}if(n.messageActions){let s={};Object.entries(n.messageActions).forEach(([i,l])=>{i!=="onFeedback"&&i!=="onCopy"&&l!==void 0&&(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(e.messageActions=s)}if(n.markdown){let s={};n.markdown.options&&(s.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(n.layout){let s={};if(n.layout.header){let i={};Object.entries(n.layout.header).forEach(([l,d])=>{l!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[l]=d)}),Object.keys(i).length>0&&(s.header=i)}if(n.layout.messages){let i={};Object.entries(n.layout.messages).forEach(([l,d])=>{if(l!=="renderUserMessage"&&l!=="renderAssistantMessage")if(l==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(l==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([f,w])=>{f!=="format"&&(typeof w=="string"||typeof w=="boolean")&&(c[f]=w)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(i[l]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function ei(n){let t=pr(n);return`<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js" data-config='${JSON.stringify(t,null,0).replace(/'/g,"&#39;")}'></script>`}function ti(n){let t=kn(n),o=t!=="plain",e=["<!-- 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&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),o&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"?e.push(` ${r}: ${s},`):typeof s=="number"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{e.push(` ${r}: ${s},`)}),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(" },")),e.push(...Wn(n," ")),e.push(...Ln(n," ")),e.push(...Bn(n," ")),e.push(...Hn(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),e.push(" }"),e.push(" });"),e.push("</script>"),e.join(`
64
- `)}function ni(n){let t=pr(n);return["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
60
+ `}if(!we){let $t="max-height: -moz-available !important; max-height: stretch !important;",on=a?"":"padding-top: 1.25em !important;";j.style.cssText+=$t+on}};Ct(),Mn(n,e);let Fe=[],et=null,xt=()=>{et&&(et(),et=null),e.colorScheme==="auto"&&(et=Gs(()=>{Mn(n,e)}))};xt(),Fe.push(()=>{et&&(et(),et=null)});let Me=dr(it),Le=null,b,Be=!1,Ee=!0,Ke=0,ot=0,st=null,gt=!1,mt=0,Mt=!1,Rt=125,zt=2e3,Nt=5,He=50,ht=new Map,pe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Pt=(So=(xo=e.voiceRecognition)==null?void 0:xo.autoResume)!=null?So:!1,Bt=a=>{s.emit("voice:state",{active:pe.active,source:a,timestamp:Date.now()})},Ht=()=>{w(a=>({...a,voiceState:{active:pe.active,timestamp:Date.now(),manuallyDeactivated:pe.manuallyDeactivated}}))},hn=()=>{var I,C;if(((I=e.voiceRecognition)==null?void 0:I.enabled)===!1)return;let a=lo(l.voiceState),u=!!a.active,T=Number((C=a.timestamp)!=null?C:0);pe.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-T<Zr&&setTimeout(()=>{pe.active||(pe.manuallyDeactivated=!1,te("restore"))},1e3)},fn=()=>b?hr(b.getMessages()).filter(a=>!a.__skipPersist):[];function Qt(a){if(!(i!=null&&i.save))return;let T={messages:a?hr(a):b?fn():[],metadata:l};try{let I=i.save(T);I instanceof Promise&&I.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)})}catch(I){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)}}let Ot=(a=!1)=>{if(!Ee)return;let u=Date.now();gt&&u<mt&&!a||(gt&&u>=mt&&(gt=!1),!(!a&&!Be)&&(u-ot<Rt||(ot=u,st&&cancelAnimationFrame(st),st=requestAnimationFrame(()=>{gt||!Ee||(Mt=!0,J.scrollTop=J.scrollHeight,Ke=J.scrollTop,requestAnimationFrame(()=>{Mt=!1}),st=null)}))))},It=null,wn=()=>j.querySelector("#vanilla-agent-scroll-container")||J,yn=(a,u=500)=>{let T=a.scrollTop,I=a.clientHeight,C=a.scrollHeight,G=C-T;if(T+I>=C-2||Math.abs(G)<5)return;It!==null&&(cancelAnimationFrame(It),It=null);let A=performance.now(),ee=me=>1-Math.pow(1-me,3),X=me=>{let $=a.scrollHeight;$!==C&&(C=$,G=C-T);let Pe=me-A,we=Math.min(Pe/u,1),le=ee(we),Ne=T+G*le;a.scrollTop=Ne,we<1?It=requestAnimationFrame(X):(a.scrollTop=a.scrollHeight,It=null)};It=requestAnimationFrame(X)},vn=a=>{let u=new Map;a.forEach(T=>{let I=ht.get(T.id);u.set(T.id,{streaming:T.streaming,role:T.role}),!I&&T.role==="assistant"&&s.emit("assistant:message",T),T.role==="assistant"&&(I!=null&&I.streaming)&&T.streaming===!1&&s.emit("assistant:complete",T)}),ht.clear(),u.forEach((T,I)=>{ht.set(I,T)})},Dt=(a,u,T)=>{let I=document.createElement("div");u.forEach(A=>{var Pe,we;let ee=null,X=r.find(le=>!!(A.variant==="reasoning"&&le.renderReasoning||A.variant==="tool"&&le.renderToolCall||!A.variant&&le.renderMessage)),me=(Pe=e.layout)==null?void 0:Pe.messages;if(X)if(A.variant==="reasoning"&&A.reasoning&&X.renderReasoning){if(!F)return;ee=X.renderReasoning({message:A,defaultRenderer:()=>Kn(A),config:e})}else if(A.variant==="tool"&&A.toolCall&&X.renderToolCall){if(!x)return;ee=X.renderToolCall({message:A,defaultRenderer:()=>Xn(A,e),config:e})}else X.renderMessage&&(ee=X.renderMessage({message:A,defaultRenderer:()=>{let le=gn(A,T,me,e.messageActions,k);return A.role!=="user"&&Vn(le,A,e,b),le},config:e}));if(!ee&&A.role==="assistant"&&!A.variant&&e.enableComponentStreaming!==!1&&so(A)){let Ne=ro(A);if(Ne){let Oe=oo(Ne,{config:e,message:A,transform:T});if(Oe){let Xe=document.createElement("div");if(Xe.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(" "),Xe.id=`bubble-${A.id}`,Xe.setAttribute("data-message-id",A.id),A.content&&A.content.trim()){let wt=document.createElement("div");wt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",wt.innerHTML=T({text:A.content,message:A,streaming:!!A.streaming,raw:A.rawContent}),Xe.appendChild(wt)}Xe.appendChild(Oe),ee=Xe}}}if(!ee)if(A.variant==="reasoning"&&A.reasoning){if(!F)return;ee=Kn(A)}else if(A.variant==="tool"&&A.toolCall){if(!x)return;ee=Xn(A,e)}else{let le=(we=e.layout)==null?void 0:we.messages;le!=null&&le.renderUserMessage&&A.role==="user"?ee=le.renderUserMessage({message:A,config:e,streaming:!!A.streaming}):le!=null&&le.renderAssistantMessage&&A.role==="assistant"?ee=le.renderAssistantMessage({message:A,config:e,streaming:!!A.streaming}):ee=gn(A,T,le,e.messageActions,k),A.role!=="user"&&ee&&Vn(ee,A,e,b)}let $=document.createElement("div");$.className="tvw-flex",$.id=`wrapper-${A.id}`,$.setAttribute("data-wrapper-id",A.id),A.role==="user"&&$.classList.add("tvw-justify-end"),$.appendChild(ee),I.appendChild($)});let C=u.some(A=>A.role==="assistant"&&A.streaming),G=u[u.length-1],ae=(G==null?void 0:G.role)==="assistant"&&!G.streaming;if(Be&&u.some(A=>A.role==="user")&&!C&&!ae){let A=kn(),ee=document.createElement("div");ee.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(" "),ee.setAttribute("data-typing-indicator","true"),ee.appendChild(A);let X=document.createElement("div");X.className="tvw-flex",X.id="wrapper-typing-indicator",X.setAttribute("data-wrapper-id","typing-indicator"),X.appendChild(ee),I.appendChild(X)}Qs(a,I),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let A=wn();yn(A)})})},_t=()=>{m&&(R?(j.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-95","tvw-opacity-0"),O.classList.add("tvw-scale-100","tvw-opacity-100"),ie?ie.element.style.display="none":Q&&(Q.style.display="none")):(j.classList.add("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-100","tvw-opacity-100"),O.classList.add("tvw-scale-95","tvw-opacity-0"),ie?ie.element.style.display="":Q&&(Q.style.display="")))},Ye=(a,u="user")=>{if(!m||R===a)return;let T=R;R=a,_t(),R&&(Re(),Ot(!0));let I={open:R,source:u,timestamp:Date.now()};R&&!T?s.emit("widget:opened",I):!R&&T&&s.emit("widget:closed",I),s.emit("widget:state",{open:R,launcherEnabled:m,voiceActive:pe.active,streaming:b.isStreaming()})},B=a=>{D.disabled=a,P&&(P.disabled=a),Me.buttons.forEach(u=>{u.disabled=a})},re=()=>{var C,G,ae,A,ee,X,me,$,Pe,we,le,Ne,Oe,Xe;Tt.textContent=(G=(C=e.copy)==null?void 0:C.welcomeTitle)!=null?G:"Hello \u{1F44B}",Et.textContent=(A=(ae=e.copy)==null?void 0:ae.welcomeSubtitle)!=null?A:"Ask anything about your account or products.",oe.placeholder=(X=(ee=e.copy)==null?void 0:ee.inputPlaceholder)!=null?X:"How can I help...",(($=(me=e.sendButton)==null?void 0:me.useIcon)!=null?$:!1)||(D.textContent=(we=(Pe=e.copy)==null?void 0:Pe.sendButtonLabel)!=null?we:"Send");let u=(Ne=(le=e.theme)==null?void 0:le.inputFontFamily)!=null?Ne:"sans-serif",T=(Xe=(Oe=e.theme)==null?void 0:Oe.inputFontWeight)!=null?Xe:"400",I=wt=>{switch(wt){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=I(u),oe.style.fontWeight=T};b=new dn(e,{onMessagesChanged(a){Dt(V,a,y),b&&(a.some(I=>I.role==="user")?Me.render([],b,oe,a):Me.render(e.suggestionChips,b,oe,a,e.suggestionChipsConfig)),Ot(!Be),vn(a);let u=[...a].reverse().find(T=>T.role==="user");pe.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Qt(a)},onStatusChanged(a){var I;let u=(I=e.statusIndicator)!=null?I:{},T=C=>{var G,ae,A,ee;return C==="idle"?(G=u.idleText)!=null?G:tt.idle:C==="connecting"?(ae=u.connectingText)!=null?ae:tt.connecting:C==="connected"?(A=u.connectedText)!=null?A:tt.connected:C==="error"?(ee=u.errorText)!=null?ee:tt.error:tt[C]};at.textContent=T(a)},onStreamingChanged(a){Be=a,B(a),b&&Dt(V,b.getMessages(),y),a||Ot(!0)}}),d&&d.then(a=>{var u;a&&(a.metadata&&(l=lo(a.metadata),v.syncFromMetadata()),(u=a.messages)!=null&&u.length&&b.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let he=a=>{a.preventDefault();let u=oe.value.trim();u&&(oe.value="",b.sendMessage(u))},Ie=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),D.click())},fe=null,Ae=!1,be=null,H=null,ft=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,te=(a="user")=>{var G,ae,A,ee;if(Ae||b.isStreaming())return;let u=ft();if(!u)return;fe=new u;let I=(ae=((G=e.voiceRecognition)!=null?G:{}).pauseDuration)!=null?ae:2e3;fe.continuous=!0,fe.interimResults=!0,fe.lang="en-US";let C=oe.value;fe.onresult=X=>{let me="",$="";for(let we=0;we<X.results.length;we++){let le=X.results[we],Ne=le[0].transcript;le.isFinal?me+=Ne+" ":$=Ne}let Pe=C+me+$;oe.value=Pe,be&&clearTimeout(be),(me||$)&&(be=window.setTimeout(()=>{let we=oe.value.trim();we&&fe&&Ae&&(W(),oe.value="",b.sendMessage(we,{viaVoice:!0}))},I))},fe.onerror=X=>{X.error!=="no-speech"&&W()},fe.onend=()=>{if(Ae){let X=oe.value.trim();X&&X!==C.trim()&&(oe.value="",b.sendMessage(X,{viaVoice:!0})),W()}};try{if(fe.start(),Ae=!0,pe.active=!0,a!=="system"&&(pe.manuallyDeactivated=!1),Bt(a),Ht(),P){H={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor};let X=(A=e.voiceRecognition)!=null?A:{},me=(ee=X.recordingBackgroundColor)!=null?ee:"#ef4444",$=X.recordingIconColor,Pe=X.recordingBorderColor;if(P.classList.add("tvw-voice-recording"),P.style.backgroundColor=me,$){P.style.color=$;let we=P.querySelector("svg");we&&we.setAttribute("stroke",$)}Pe&&(P.style.borderColor=Pe),P.setAttribute("aria-label","Stop voice recognition")}}catch{W("system")}},W=(a="user")=>{if(Ae){if(Ae=!1,be&&(clearTimeout(be),be=null),fe){try{fe.stop()}catch{}fe=null}if(pe.active=!1,Bt(a),Ht(),P){if(P.classList.remove("tvw-voice-recording"),H){P.style.backgroundColor=H.backgroundColor,P.style.color=H.color,P.style.borderColor=H.borderColor;let u=P.querySelector("svg");u&&u.setAttribute("stroke",H.color||"currentColor"),H=null}P.setAttribute("aria-label","Start voice recognition")}}},E=(a,u)=>{var Ne,Oe,Xe,wt,Z,Se,jt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let I=h("div","tvw-send-button-wrapper"),C=h("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");C.type="button",C.setAttribute("aria-label","Start voice recognition");let G=(Ne=a==null?void 0:a.iconName)!=null?Ne:"mic",ae=(Oe=u==null?void 0:u.size)!=null?Oe:"40px",A=(Xe=a==null?void 0:a.iconSize)!=null?Xe:ae,ee=parseFloat(A)||24,X=(wt=a==null?void 0:a.backgroundColor)!=null?wt:u==null?void 0:u.backgroundColor,me=(Z=a==null?void 0:a.iconColor)!=null?Z:u==null?void 0:u.textColor;C.style.width=A,C.style.height=A,C.style.minWidth=A,C.style.minHeight=A,C.style.fontSize="18px",C.style.lineHeight="1";let $=me||"currentColor",Pe=de(G,ee,$,1.5);Pe?(C.appendChild(Pe),C.style.color=$):(C.textContent="\u{1F3A4}",C.style.color=$),X?C.style.backgroundColor=X:C.classList.add("tvw-bg-cw-primary"),me?C.style.color=me:!me&&!(u!=null&&u.textColor)&&C.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(C.style.borderWidth=a.borderWidth,C.style.borderStyle="solid"),a!=null&&a.borderColor&&(C.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(C.style.paddingLeft=a.paddingX,C.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(C.style.paddingTop=a.paddingY,C.style.paddingBottom=a.paddingY),I.appendChild(C);let we=(Se=a==null?void 0:a.tooltipText)!=null?Se:"Start voice recognition";if(((jt=a==null?void 0:a.showTooltip)!=null?jt:!1)&&we){let qt=h("div","tvw-send-button-tooltip");qt.textContent=we,I.appendChild(qt)}return{micButton:C,micButtonWrapper:I}},K=()=>{if(Ae){let a=oe.value.trim();pe.manuallyDeactivated=!0,Ht(),W("user"),a&&(oe.value="",b.sendMessage(a))}else pe.manuallyDeactivated=!1,Ht(),te("user")};P&&(P.addEventListener("click",K),Fe.push(()=>{W("system"),P&&P.removeEventListener("click",K)}));let ke=s.on("assistant:complete",()=>{Pt&&(pe.active||pe.manuallyDeactivated||Pt==="assistant"&&!pe.lastUserMessageWasVoice||setTimeout(()=>{!pe.active&&!pe.manuallyDeactivated&&te("auto")},600))});Fe.push(ke);let ye=()=>{Ye(!R,"user")},ie=null,Q=null;if(m){let a=r.find(u=>u.renderLauncher);if(a!=null&&a.renderLauncher){let u=a.renderLauncher({config:e,defaultRenderer:()=>cn(e,ye).element,onToggle:ye});u&&(Q=u)}Q||(ie=cn(e,ye))}ie?n.appendChild(ie.element):Q&&n.appendChild(Q),_t(),Me.render(e.suggestionChips,b,oe,void 0,e.suggestionChipsConfig),re(),B(b.isStreaming()),Ot(!0),hn();let Re=()=>{var T,I,C,G,ae,A,ee,X;let a=(I=(T=e.launcher)==null?void 0:T.sidebarMode)!=null?I:!1,u=a||((G=(C=e.launcher)==null?void 0:C.fullHeight)!=null?G:!1);if(!m){O.style.height="",O.style.width="";return}if(!a){let me=(A=(ae=e==null?void 0:e.launcher)==null?void 0:ae.width)!=null?A:e==null?void 0:e.launcherWidth,$=me!=null?me:"min(400px, calc(100vw - 24px))";O.style.width=$,O.style.maxWidth=$}if(!u){let me=window.innerHeight,$=64,Pe=(X=(ee=e.launcher)==null?void 0:ee.heightOffset)!=null?X:0,we=Math.max(200,me-$),le=Math.min(640,we),Ne=Math.max(200,le-Pe);O.style.height=`${Ne}px`}};Re(),window.addEventListener("resize",Re),Fe.push(()=>window.removeEventListener("resize",Re)),Ke=J.scrollTop;let je=()=>{let a=J.scrollTop,u=J.scrollHeight,T=J.clientHeight,I=u-a-T,C=Math.abs(a-Ke);if(Ke=a,!Mt&&!(C<=Nt)){if(!Ee&&I<He){gt=!1,Ee=!0;return}Ee&&I>He&&(gt=!0,mt=Date.now()+zt,Ee=!1)}};J.addEventListener("scroll",je,{passive:!0}),Fe.push(()=>J.removeEventListener("scroll",je)),Fe.push(()=>{st&&cancelAnimationFrame(st)});let ge=()=>{_&&(Le&&(_.removeEventListener("click",Le),Le=null),m?(_.style.display="",Le=()=>{R=!1,_t()},_.addEventListener("click",Le)):_.style.display="none")};ge(),(()=>{let{clearChatButton:a}=q;a&&a.addEventListener("click",()=>{b.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let u=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",I)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}l={},v.syncFromMetadata()})})(),nt.addEventListener("submit",he),oe.addEventListener("keydown",Ie),Fe.push(()=>{nt.removeEventListener("submit",he),oe.removeEventListener("keydown",Ie)}),Fe.push(()=>{b.cancel()}),ie?Fe.push(()=>{ie==null||ie.destroy()}):Q&&Fe.push(()=>{Q==null||Q.remove()});let ve={update(a){var To,Eo,Mo,ko,Wo,Lo,Bo,Ho,Io,Ro,Po,$o,Fo,No,Oo,Do,_o,jo,qo,Uo,zo,Jo,Yo,Ko,Xo,Vo,Go,Qo,Zo,es,ts,ns,os,ss,rs,is,as,ls,ds,cs,us,ps,gs,ms,hs,fs,ws,ys,vs,bs,Cs,xs,Ss,As,Ts,Es,Ms,ks,Ws,Ls,Bs,Hs,Is,Rs,Ps,$s,Fs,Ns,Os,Ds;let u=e.toolCall,T=e.colorScheme;e={...e,...a},Ct(),Mn(n,e),e.colorScheme!==T&&xt();let I=Wn.getForInstance(e.plugins);if(r.length=0,r.push(...I),m=(Eo=(To=e.launcher)==null?void 0:To.enabled)!=null?Eo:!0,N=(ko=(Mo=e.launcher)==null?void 0:Mo.autoExpand)!=null?ko:!1,F=(Lo=(Wo=e.features)==null?void 0:Wo.showReasoning)!=null?Lo:!0,x=(Ho=(Bo=e.features)==null?void 0:Bo.showToolCalls)!=null?Ho:!0,((Io=e.launcher)==null?void 0:Io.enabled)===!1&&ie&&(ie.destroy(),ie=null),((Ro=e.launcher)==null?void 0:Ro.enabled)===!1&&Q&&(Q.remove(),Q=null),((Po=e.launcher)==null?void 0:Po.enabled)!==!1&&!ie&&!Q){let L=r.find(ce=>ce.renderLauncher);if(L!=null&&L.renderLauncher){let ce=L.renderLauncher({config:e,defaultRenderer:()=>cn(e,ye).element,onToggle:ye});ce&&(Q=ce,n.appendChild(Q))}Q||(ie=cn(e,ye),n.appendChild(ie.element))}ie&&ie.update(e),Ge&&(($o=e.launcher)==null?void 0:$o.title)!==void 0&&(Ge.textContent=e.launcher.title),Qe&&((Fo=e.launcher)==null?void 0:Fo.subtitle)!==void 0&&(Qe.textContent=e.launcher.subtitle);let C=(No=e.layout)==null?void 0:No.header;if((C==null?void 0:C.layout)!==S&&_e){let L=C?un(e,C,{showClose:m,onClose:()=>Ye(!1,"user")}):Ft({config:e,showClose:m,onClose:()=>Ye(!1,"user")});_e.replaceWith(L.header),_e=L.header,ue=L.iconHolder,Ge=L.headerTitle,Qe=L.headerSubtitle,_=L.closeButton,S=C==null?void 0:C.layout}else if(C&&(ue&&(ue.style.display=C.showIcon===!1?"none":""),Ge&&(Ge.style.display=C.showTitle===!1?"none":""),Qe&&(Qe.style.display=C.showSubtitle===!1?"none":""),_&&(_.style.display=C.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let L=C.showClearChat;if(L!==void 0){q.clearChatButtonWrapper.style.display=L?"":"none";let{closeButtonWrapper:ce}=q;ce&&!ce.classList.contains("tvw-absolute")&&(L?ce.classList.remove("tvw-ml-auto"):ce.classList.add("tvw-ml-auto"))}}let ae=((Oo=e.layout)==null?void 0:Oo.showHeader)!==!1;_e&&(_e.style.display=ae?"":"none");let A=((Do=e.layout)==null?void 0:Do.showFooter)!==!1;Ze&&(Ze.style.display=A?"":"none"),m!==f?m?Ye(N,"auto"):(R=!0,_t()):N!==M&&Ye(N,"auto"),M=N,f=m,Re(),ge(),JSON.stringify(a.toolCall)!==JSON.stringify(u)&&b&&Dt(V,b.getMessages(),y);let $=(_o=e.launcher)!=null?_o:{},Pe=(jo=$.headerIconHidden)!=null?jo:!1,we=(Uo=(qo=e.layout)==null?void 0:qo.header)==null?void 0:Uo.showIcon,le=Pe||we===!1,Ne=$.headerIconName,Oe=(zo=$.headerIconSize)!=null?zo:"48px";if(ue){let L=U.querySelector(".tvw-border-b-cw-divider"),ce=L==null?void 0:L.querySelector(".tvw-flex-col");if(le)ue.style.display="none",L&&ce&&!L.contains(ce)&&L.insertBefore(ce,L.firstChild);else{if(ue.style.display="",ue.style.height=Oe,ue.style.width=Oe,L&&ce&&(L.contains(ue)?ue.nextSibling!==ce&&(ue.remove(),L.insertBefore(ue,ce)):L.insertBefore(ue,ce)),Ne){let ne=parseFloat(Oe)||24,Te=de(Ne,ne*.6,"#ffffff",2);Te?ue.replaceChildren(Te):ue.textContent=(Jo=$.agentIconText)!=null?Jo:"\u{1F4AC}"}else if($.iconUrl){let ne=ue.querySelector("img");if(ne)ne.src=$.iconUrl,ne.style.height=Oe,ne.style.width=Oe;else{let Te=document.createElement("img");Te.src=$.iconUrl,Te.alt="",Te.className="tvw-rounded-xl tvw-object-cover",Te.style.height=Oe,Te.style.width=Oe,ue.replaceChildren(Te)}}else{let ne=ue.querySelector("svg"),Te=ue.querySelector("img");(ne||Te)&&ue.replaceChildren(),ue.textContent=(Yo=$.agentIconText)!=null?Yo:"\u{1F4AC}"}let qe=ue.querySelector("img");qe&&(qe.style.height=Oe,qe.style.width=Oe)}}let Xe=(Xo=(Ko=e.layout)==null?void 0:Ko.header)==null?void 0:Xo.showTitle,wt=(Go=(Vo=e.layout)==null?void 0:Vo.header)==null?void 0:Go.showSubtitle;if(Ge&&(Ge.style.display=Xe===!1?"none":""),Qe&&(Qe.style.display=wt===!1?"none":""),_){((Zo=(Qo=e.layout)==null?void 0:Qo.header)==null?void 0:Zo.showCloseButton)===!1?_.style.display="none":_.style.display="";let ce=(es=$.closeButtonSize)!=null?es:"32px",qe=(ts=$.closeButtonPlacement)!=null?ts:"inline";_.style.height=ce,_.style.width=ce;let{closeButtonWrapper:ne}=q,Te=qe==="top-right",dt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&Te!==dt)if(ne.remove(),Te)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",U.style.position="relative",U.appendChild(ne);else{let se=(os=(ns=$.clearChat)==null?void 0:ns.placement)!=null?os:"inline",Je=(rs=(ss=$.clearChat)==null?void 0:ss.enabled)!=null?rs:!0;ne.className=Je&&se==="inline"?"":"tvw-ml-auto";let ct=U.querySelector(".tvw-border-b-cw-divider");ct&&ct.appendChild(ne)}if($.closeButtonColor?(_.style.color=$.closeButtonColor,_.classList.remove("tvw-text-cw-muted")):(_.style.color="",_.classList.add("tvw-text-cw-muted")),$.closeButtonBackgroundColor?(_.style.backgroundColor=$.closeButtonBackgroundColor,_.classList.remove("hover:tvw-bg-gray-100")):(_.style.backgroundColor="",_.classList.add("hover:tvw-bg-gray-100")),$.closeButtonBorderWidth||$.closeButtonBorderColor){let se=$.closeButtonBorderWidth||"0px",Je=$.closeButtonBorderColor||"transparent";_.style.border=`${se} solid ${Je}`,_.classList.remove("tvw-border-none")}else _.style.border="",_.classList.add("tvw-border-none");$.closeButtonBorderRadius?(_.style.borderRadius=$.closeButtonBorderRadius,_.classList.remove("tvw-rounded-full")):(_.style.borderRadius="",_.classList.add("tvw-rounded-full")),$.closeButtonPaddingX?(_.style.paddingLeft=$.closeButtonPaddingX,_.style.paddingRight=$.closeButtonPaddingX):(_.style.paddingLeft="",_.style.paddingRight=""),$.closeButtonPaddingY?(_.style.paddingTop=$.closeButtonPaddingY,_.style.paddingBottom=$.closeButtonPaddingY):(_.style.paddingTop="",_.style.paddingBottom="");let rt=(is=$.closeButtonIconName)!=null?is:"x",Wt=(as=$.closeButtonIconText)!=null?as:"\xD7";_.innerHTML="";let yt=de(rt,"20px",$.closeButtonColor||"",2);yt?_.appendChild(yt):_.textContent=Wt;let ze=(ls=$.closeButtonTooltipText)!=null?ls:"Close chat",St=(ds=$.closeButtonShowTooltip)!=null?ds:!0;if(_.setAttribute("aria-label",ze),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),St&&ze)){let se=null,Je=()=>{if(se||!_)return;se=h("div","tvw-clear-chat-tooltip"),se.textContent=ze;let ln=h("div");ln.className="tvw-clear-chat-tooltip-arrow",se.appendChild(ln);let Ut=_.getBoundingClientRect();se.style.position="fixed",se.style.left=`${Ut.left+Ut.width/2}px`,se.style.top=`${Ut.top-8}px`,se.style.transform="translate(-50%, -100%)",document.body.appendChild(se)},ct=()=>{se&&se.parentNode&&(se.parentNode.removeChild(se),se=null)};ne.addEventListener("mouseenter",Je),ne.addEventListener("mouseleave",ct),_.addEventListener("focus",Je),_.addEventListener("blur",ct),ne._cleanupTooltip=()=>{ct(),ne&&(ne.removeEventListener("mouseenter",Je),ne.removeEventListener("mouseleave",ct)),_&&(_.removeEventListener("focus",Je),_.removeEventListener("blur",ct))}}}let{clearChatButton:Z,clearChatButtonWrapper:Se}=q;if(Z){let L=(cs=$.clearChat)!=null?cs:{},ce=(us=L.enabled)!=null?us:!0,qe=(gs=(ps=e.layout)==null?void 0:ps.header)==null?void 0:gs.showClearChat,ne=qe!==void 0?qe:ce,Te=(ms=L.placement)!=null?ms:"inline";if(Se){Se.style.display=ne?"":"none";let{closeButtonWrapper:dt}=q;dt&&!dt.classList.contains("tvw-absolute")&&(ne?dt.classList.remove("tvw-ml-auto"):dt.classList.add("tvw-ml-auto"));let rt=Te==="top-right",Wt=Se.classList.contains("tvw-absolute");if(rt!==Wt&&ne){if(Se.remove(),rt)Se.className="tvw-absolute tvw-top-4 tvw-z-50",Se.style.right="48px",U.style.position="relative",U.appendChild(Se);else{Se.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Se.style.right="";let ze=U.querySelector(".tvw-border-b-cw-divider"),St=q.closeButtonWrapper;ze&&St&&St.parentElement===ze?ze.insertBefore(Se,St):ze&&ze.appendChild(Se)}let yt=q.closeButtonWrapper;yt&&!yt.classList.contains("tvw-absolute")&&(rt?yt.classList.add("tvw-ml-auto"):yt.classList.remove("tvw-ml-auto"))}}if(ne){let dt=(hs=L.size)!=null?hs:"32px";Z.style.height=dt,Z.style.width=dt;let rt=(fs=L.iconName)!=null?fs:"refresh-cw",Wt=(ws=L.iconColor)!=null?ws:"";Z.innerHTML="";let yt=de(rt,"20px",Wt||"",2);if(yt&&Z.appendChild(yt),Wt?(Z.style.color=Wt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),L.backgroundColor?(Z.style.backgroundColor=L.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let se=L.borderWidth||"0px",Je=L.borderColor||"transparent";Z.style.border=`${se} solid ${Je}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");L.borderRadius?(Z.style.borderRadius=L.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),L.paddingX?(Z.style.paddingLeft=L.paddingX,Z.style.paddingRight=L.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),L.paddingY?(Z.style.paddingTop=L.paddingY,Z.style.paddingBottom=L.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let ze=(ys=L.tooltipText)!=null?ys:"Clear chat",St=(vs=L.showTooltip)!=null?vs:!0;if(Z.setAttribute("aria-label",ze),Se&&(Se._cleanupTooltip&&(Se._cleanupTooltip(),delete Se._cleanupTooltip),St&&ze)){let se=null,Je=()=>{if(se||!Z)return;se=h("div","tvw-clear-chat-tooltip"),se.textContent=ze;let ln=h("div");ln.className="tvw-clear-chat-tooltip-arrow",se.appendChild(ln);let Ut=Z.getBoundingClientRect();se.style.position="fixed",se.style.left=`${Ut.left+Ut.width/2}px`,se.style.top=`${Ut.top-8}px`,se.style.transform="translate(-50%, -100%)",document.body.appendChild(se)},ct=()=>{se&&se.parentNode&&(se.parentNode.removeChild(se),se=null)};Se.addEventListener("mouseenter",Je),Se.addEventListener("mouseleave",ct),Z.addEventListener("focus",Je),Z.addEventListener("blur",ct),Se._cleanupTooltip=()=>{ct(),Se&&(Se.removeEventListener("mouseenter",Je),Se.removeEventListener("mouseleave",ct)),Z&&(Z.removeEventListener("focus",Je),Z.removeEventListener("blur",ct))}}}}let jt=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ln],qt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Vt.message,Vt.messageAndClick];v=Bn({parsers:jt,handlers:qt,getMetadata:c,updateMetadata:w,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),y=fr(e,v),b.updateConfig(e),Dt(V,b.getMessages(),y),Me.render(e.suggestionChips,b,oe,void 0,e.suggestionChipsConfig),re(),B(b.isStreaming());let Zt=((bs=e.voiceRecognition)==null?void 0:bs.enabled)===!0,en=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),bn=Zt&&en;if(nt.classList.remove("tvw-gap-1","tvw-gap-3"),nt.classList.add(bn?"tvw-gap-1":"tvw-gap-3"),Zt&&en)if(!P||!$e){let L=E(e.voiceRecognition,e.sendButton);L&&(P=L.micButton,$e=L.micButtonWrapper,nt.insertBefore($e,Ve),P.addEventListener("click",K),P.disabled=b.isStreaming())}else{let L=(Cs=e.voiceRecognition)!=null?Cs:{},ce=(xs=e.sendButton)!=null?xs:{},qe=(Ss=L.iconName)!=null?Ss:"mic",ne=(As=ce.size)!=null?As:"40px",Te=(Ts=L.iconSize)!=null?Ts:ne,dt=parseFloat(Te)||24;P.style.width=Te,P.style.height=Te,P.style.minWidth=Te,P.style.minHeight=Te;let rt=(Ms=(Es=L.iconColor)!=null?Es:ce.textColor)!=null?Ms:"currentColor";P.innerHTML="";let Wt=de(qe,dt,rt,2);Wt?P.appendChild(Wt):P.textContent="\u{1F3A4}";let yt=(ks=L.backgroundColor)!=null?ks:ce.backgroundColor;yt?(P.style.backgroundColor=yt,P.classList.remove("tvw-bg-cw-primary")):(P.style.backgroundColor="",P.classList.add("tvw-bg-cw-primary")),rt?(P.style.color=rt,P.classList.remove("tvw-text-white")):!rt&&!ce.textColor&&(P.style.color="",P.classList.add("tvw-text-white")),L.borderWidth?(P.style.borderWidth=L.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),L.borderColor?P.style.borderColor=L.borderColor:P.style.borderColor="",L.paddingX?(P.style.paddingLeft=L.paddingX,P.style.paddingRight=L.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),L.paddingY?(P.style.paddingTop=L.paddingY,P.style.paddingBottom=L.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let ze=$e==null?void 0:$e.querySelector(".tvw-send-button-tooltip"),St=(Ws=L.tooltipText)!=null?Ws:"Start voice recognition";if(((Ls=L.showTooltip)!=null?Ls:!1)&&St)if(ze)ze.textContent=St,ze.style.display="";else{let Je=document.createElement("div");Je.className="tvw-send-button-tooltip",Je.textContent=St,$e==null||$e.insertBefore(Je,P)}else ze&&(ze.style.display="none");$e.style.display="",P.disabled=b.isStreaming()}else P&&$e&&($e.style.display="none",Ae&&W());let De=(Bs=e.sendButton)!=null?Bs:{},Cn=(Hs=De.useIcon)!=null?Hs:!1,tn=(Is=De.iconText)!=null?Is:"\u2191",nn=De.iconName,$t=(Rs=De.tooltipText)!=null?Rs:"Send message",on=(Ps=De.showTooltip)!=null?Ps:!1,sn=($s=De.size)!=null?$s:"40px",xn=De.backgroundColor,kt=De.textColor;if(Cn){if(D.style.width=sn,D.style.height=sn,D.style.minWidth=sn,D.style.minHeight=sn,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",nn){let L=parseFloat(sn)||24,ce=kt&&typeof kt=="string"&&kt.trim()?kt.trim():"currentColor",qe=de(nn,L,ce,2);qe?(D.appendChild(qe),D.style.color=ce):(D.textContent=tn,kt?D.style.color=kt:D.classList.add("tvw-text-white"))}else D.textContent=tn,kt?D.style.color=kt:D.classList.add("tvw-text-white");D.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",xn?(D.style.backgroundColor=xn,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Ns=(Fs=e.copy)==null?void 0:Fs.sendButtonLabel)!=null?Ns:"Send",D.style.width="",D.style.height="",D.style.minWidth="",D.style.minHeight="",D.style.fontSize="",D.style.lineHeight="",D.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",xn?(D.style.backgroundColor=xn,D.classList.remove("tvw-bg-cw-accent")):D.classList.add("tvw-bg-cw-accent"),kt?D.style.color=kt:D.classList.add("tvw-text-white");De.borderWidth?(D.style.borderWidth=De.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),De.borderColor?D.style.borderColor=De.borderColor:D.style.borderColor="",De.paddingX?(D.style.paddingLeft=De.paddingX,D.style.paddingRight=De.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),De.paddingY?(D.style.paddingTop=De.paddingY,D.style.paddingBottom=De.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let rn=Ve==null?void 0:Ve.querySelector(".tvw-send-button-tooltip");if(on&&$t)if(rn)rn.textContent=$t,rn.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=$t,Ve==null||Ve.insertBefore(L,D)}else rn&&(rn.style.display="none");let an=(Os=e.statusIndicator)!=null?Os:{},br=(Ds=an.visible)!=null?Ds:!0;if(at.style.display=br?"":"none",b){let L=b.getStatus(),ce=qe=>{var ne,Te,dt,rt;return qe==="idle"?(ne=an.idleText)!=null?ne:tt.idle:qe==="connecting"?(Te=an.connectingText)!=null?Te:tt.connecting:qe==="connected"?(dt=an.connectedText)!=null?dt:tt.connected:qe==="error"?(rt=an.errorText)!=null?rt:tt.error:tt[qe]};at.textContent=ce(L)}},open(){m&&Ye(!0,"api")},close(){m&&Ye(!1,"api")},toggle(){m&&Ye(!R,"api")},clearChat(){b.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.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(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}l={},v.syncFromMetadata()},setMessage(a){return!oe||b.isStreaming()?!1:(!R&&m&&Ye(!0,"system"),oe.value=a,oe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(b.isStreaming())return!1;let u=(a==null?void 0:a.trim())||oe.value.trim();return u?(!R&&m&&Ye(!0,"system"),oe.value="",b.sendMessage(u),!0):!1},startVoiceRecognition(){return Ae||b.isStreaming()||!ft()?!1:(!R&&m&&Ye(!0,"system"),pe.manuallyDeactivated=!1,Ht(),te("user"),!0)},stopVoiceRecognition(){return Ae?(pe.manuallyDeactivated=!0,Ht(),W("user"),!0):!1},injectTestMessage(a){!R&&m&&Ye(!0,"system"),b.injectTestEvent(a)},getMessages(){return b.getMessages()},getStatus(){return b.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){w(a)},on(a,u){return s.on(a,u)},off(a,u){s.off(a,u)},isOpen(){return m&&R},isVoiceActive(){return pe.active},getState(){return{open:m&&R,launcherEnabled:m,voiceActive:pe.active,streaming:b.isStreaming()}},showCSATFeedback(a){!R&&m&&Ye(!0,"system");let u=V.querySelector(".tvw-feedback-container");u&&u.remove();let T=io({onSubmit:async(I,C)=>{var G;b.isClientTokenMode()&&await b.submitCSATFeedback(I,C),(G=a==null?void 0:a.onSubmit)==null||G.call(a,I,C)},onDismiss:a==null?void 0:a.onDismiss,...a});V.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!R&&m&&Ye(!0,"system");let u=V.querySelector(".tvw-feedback-container");u&&u.remove();let T=ao({onSubmit:async(I,C)=>{var G;b.isClientTokenMode()&&await b.submitNPSFeedback(I,C),(G=a==null?void 0:a.onSubmit)==null||G.call(a,I,C)},onDismiss:a==null?void 0:a.onDismiss,...a});V.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return b.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return b.submitNPSFeedback(a,u)},destroy(){Fe.forEach(a=>a()),j.remove(),ie==null||ie.destroy(),Q==null||Q.remove(),Le&&_.removeEventListener("click",Le)}};if((((Ao=o==null?void 0:o.debugTools)!=null?Ao:!1)||!!e.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,u={controller:ve,getMessages:ve.getMessages,getStatus:ve.getStatus,getMetadata:ve.getPersistentMetadata,updateMetadata:ve.updatePersistentMetadata,clearHistory:()=>ve.clearChat(),setVoiceActive:T=>T?ve.startVoiceRecognition():ve.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Fe.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}return ve};var uo={},ei=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 t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},ti=()=>{try{if(typeof uo!="undefined"&&uo.url)return new URL("../widget.css",uo.url).href}catch{}return null},wr=n=>{let t=ti(),o=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let r=e.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-vanilla-agent","true"),n.insertBefore(e,n.firstChild)}else o();else if(!document.head.querySelector("link[data-vanilla-agent]")&&t){let r=document.createElement("link");r.rel="stylesheet",r.href=t,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},yr=n=>{var c,w,g,p;let t=ei(n.target),o=document.createElement("div");o.className="vanilla-agent-host";let e=(g=(w=(c=n.config)==null?void 0:c.launcher)==null?void 0:w.enabled)!=null?g:!0;e||(o.style.height="100%"),t.appendChild(o);let r=n.useShadowDom===!0,s,i;if(r){let v=o.attachShadow({mode:"open"});i=v,s=document.createElement("div"),s.id="vanilla-agent-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),v.appendChild(s),wr(v)}else i=o,s=document.createElement("div"),s.id="vanilla-agent-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),o.appendChild(s),wr(o);let l=co(s,n.config,{debugTools:n.debugTools});(p=n.onReady)==null||p.call(n);let d={...l,host:o,destroy(){l.destroy(),o.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=d),d};function ni(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Hn(n){var t,o;return(o=(t=n.parserType)!=null?t:ni(n.streamParser))!=null?o:"plain"}function In(n,t){let o=[];return n.toolCall&&(o.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,r])=>{typeof r=="string"&&o.push(`${t} ${e}: "${r}",`)}),o.push(`${t}},`)),o}function Rn(n,t){let o=[];return n.messageActions&&Object.entries(n.messageActions).some(([r,s])=>r!=="onFeedback"&&r!=="onCopy"&&s!==void 0)&&(o.push(`${t}messageActions: {`),Object.entries(n.messageActions).forEach(([r,s])=>{r==="onFeedback"||r==="onCopy"||(typeof s=="string"?o.push(`${t} ${r}: "${s}",`):typeof s=="boolean"&&o.push(`${t} ${r}: ${s},`))}),o.push(`${t}},`)),o}function Pn(n,t){let o=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,r=n.markdown.disableDefaultStyles!==void 0;(e||r)&&(o.push(`${t}markdown: {`),e&&(o.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([s,i])=>{typeof i=="string"?o.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${s}: ${i},`)}),o.push(`${t} },`)),r&&o.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),o.push(`${t}},`))}return o}function $n(n,t){let o=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(s=>s!=="render"),r=n.layout.messages&&Object.keys(n.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||r)&&(o.push(`${t}layout: {`),e&&(o.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?o.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${s}: ${i},`))}),o.push(`${t} },`)),r&&(o.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(o.push(`${t} avatar: {`),Object.entries(i).forEach(([l,d])=>{typeof d=="string"?o.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&o.push(`${t} ${l}: ${d},`)}),o.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(o.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?o.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&o.push(`${t} ${d}: ${c},`))}),o.push(`${t} },`)):typeof i=="string"?o.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${s}: ${i},`))}),o.push(`${t} },`)),o.push(`${t}},`))}return o}function oi(n,t="esm"){let o={...n};return delete o.postprocessMessage,delete o.initialMessages,t==="esm"?si(o):t==="script-installer"?ai(o):t==="script-advanced"?di(o):t==="react-component"?ri(o):t==="react-advanced"?ii(o):li(o)}function si(n){let t=Hn(n),o=t!=="plain",e=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),o&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"?e.push(` ${r}: ${s},`):typeof s=="number"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{e.push(` ${r}: ${s},`)}),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(" },")),e.push(...In(n," ")),e.push(...Rn(n," ")),e.push(...Pn(n," ")),e.push(...$n(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push("});"),e.join(`
61
+ `)}function ri(n){let t=Hn(n),o=t!=="plain",e=["// 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&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),o&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"?e.push(` ${r}: ${s},`):typeof s=="number"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{e.push(` ${r}: ${s},`)}),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(" },")),e.push(...In(n," ")),e.push(...Rn(n," ")),e.push(...Pn(n," ")),e.push(...$n(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),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 in your app:"),e.push("// import { ChatWidget } from './components/ChatWidget';"),e.push("//"),e.push("// export default function App() {"),e.push("// return ("),e.push("// <div>"),e.push("// {/* Your app content */}"),e.push("// <ChatWidget />"),e.push("// </div>"),e.push("// );"),e.push("// }"),e.join(`
62
+ `)}function ii(n){let t=["// 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&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,e])=>{t.push(` ${o}: "${e}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,e])=>{typeof e=="string"?t.push(` ${o}: "${e}",`):typeof e=="boolean"&&t.push(` ${o}: ${e},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,e])=>{t.push(` ${o}: "${e}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,e])=>{typeof e=="string"?t.push(` ${o}: "${e}",`):typeof e=="boolean"&&t.push(` ${o}: ${e},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,e])=>{typeof e=="string"?t.push(` ${o}: "${e}",`):typeof e=="boolean"?t.push(` ${o}: ${e},`):typeof e=="number"&&t.push(` ${o}: ${e},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,e])=>{typeof e=="string"?t.push(` ${o}: "${e}",`):typeof e=="boolean"&&t.push(` ${o}: ${e},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,e])=>{t.push(` ${o}: ${e},`)}),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(" },")),t.push(...In(n," ")),t.push(...Rn(n," ")),t.push(...Pn(n," ")),t.push(...$n(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" initialMessages: loadSavedMessages(),"),t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),t.push(" if (!parsed || typeof parsed !== 'object') return null;"),t.push(" // Extract display text based on action type"),t.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),t.push(" if (parsed.action === 'message') return parsed.text || '';"),t.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),t.push(" return parsed.text || null;"),t.push(" }),"),t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Custom parser for markdown-wrapped JSON"),t.push(" ({ text, message }: any) => {"),t.push(" const jsonSource = (message as any).rawContent || text || message.content;"),t.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),t.push(" // Strip markdown code fences"),t.push(" let cleanJson = jsonSource"),t.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),t.push(" .replace(/\\n?```\\s*$/, '')"),t.push(" .trim();"),t.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),t.push(" try {"),t.push(" const parsed = JSON.parse(cleanJson);"),t.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),t.push(" } catch (e) { return null; }"),t.push(" return null;"),t.push(" }"),t.push(" ],"),t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(" (action: any, context: any) => {"),t.push(" if (action.type !== 'nav_then_click') return;"),t.push(" const payload = action.payload || action.raw || {};"),t.push(" const url = payload?.page;"),t.push(" const text = payload?.on_load_text || 'Navigating...';"),t.push(" if (!url) return { handled: true, displayText: text };"),t.push(" // Check if already processed"),t.push(" const messageId = context.message?.id;"),t.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),t.push(" const actionKey = `nav_${messageId}_${url}`;"),t.push(" if (processedActions.includes(actionKey)) {"),t.push(" return { handled: true, displayText: text };"),t.push(" }"),t.push(" processedActions.push(actionKey);"),t.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),t.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),t.push(" window.location.href = targetUrl;"),t.push(" return { handled: true, displayText: text };"),t.push(" }"),t.push(" ],"),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),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: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
63
+ `)}function vr(n){var r;let t=Hn(n),o=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.flowId&&(e.flowId=n.flowId),o&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((r=n.suggestionChips)==null?void 0:r.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let s={};Object.entries(n.toolCall).forEach(([i,l])=>{typeof l=="string"&&(s[i]=l)}),Object.keys(s).length>0&&(e.toolCall=s)}if(n.messageActions){let s={};Object.entries(n.messageActions).forEach(([i,l])=>{i!=="onFeedback"&&i!=="onCopy"&&l!==void 0&&(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(e.messageActions=s)}if(n.markdown){let s={};n.markdown.options&&(s.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(n.layout){let s={};if(n.layout.header){let i={};Object.entries(n.layout.header).forEach(([l,d])=>{l!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[l]=d)}),Object.keys(i).length>0&&(s.header=i)}if(n.layout.messages){let i={};Object.entries(n.layout.messages).forEach(([l,d])=>{if(l!=="renderUserMessage"&&l!=="renderAssistantMessage")if(l==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(l==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([w,g])=>{w!=="format"&&(typeof g=="string"||typeof g=="boolean")&&(c[w]=g)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(i[l]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function ai(n){let t=vr(n);return`<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js" data-config='${JSON.stringify(t,null,0).replace(/'/g,"&#39;")}'></script>`}function li(n){let t=Hn(n),o=t!=="plain",e=["<!-- 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&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),o&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{e.push(` ${r}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"?e.push(` ${r}: ${s},`):typeof s=="number"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?e.push(` ${r}: "${s}",`):typeof s=="boolean"&&e.push(` ${r}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{e.push(` ${r}: ${s},`)}),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(" },")),e.push(...In(n," ")),e.push(...Rn(n," ")),e.push(...Pn(n," ")),e.push(...$n(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),e.push(" }"),e.push(" });"),e.push("</script>"),e.join(`
64
+ `)}function di(n){let t=vr(n);return["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
65
65
  `).map((r,s)=>s===0?r:" "+r).join(`
66
66
  `)};`,""," // Constants"," var CDN_BASE = 'https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist';"," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-vanilla-agent]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-vanilla-agent', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""," // Flexible JSON stream parser for handling structured actions"," widgetConfig.streamParser = function() {"," return agentWidget.createFlexibleJsonStreamParser(function(parsed) {"," if (!parsed || typeof parsed !== 'object') return null;"," if (parsed.action === 'nav_then_click') return 'Navigating...';"," if (parsed.action === 'message') return parsed.text || '';"," if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"," return parsed.text || null;"," });"," };",""," // Action parsers to detect JSON actions in responses"," widgetConfig.actionParsers = ["," agentWidget.defaultJsonActionParser,"," function(ctx) {"," var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;"," if (!jsonSource || typeof jsonSource !== 'string') return null;"," var cleanJson = jsonSource"," .replace(/^```(?:json)?\\s*\\n?/, '')"," .replace(/\\n?```\\s*$/, '')"," .trim();"," if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"," try {"," var parsed = JSON.parse(cleanJson);"," if (parsed.action) return { type: parsed.action, payload: parsed };"," } catch (e) { return null; }"," return null;"," }"," ];",""," // Action handlers for navigation and other actions"," widgetConfig.actionHandlers = ["," agentWidget.defaultActionHandlers.message,"," agentWidget.defaultActionHandlers.messageAndClick,"," function(action, context) {"," if (action.type !== 'nav_then_click') return;"," var payload = action.payload || action.raw || {};"," var url = payload.page;"," var text = payload.on_load_text || 'Navigating...';"," if (!url) return { handled: true, displayText: text };"," var messageId = context.message ? context.message.id : null;"," var processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"," var actionKey = 'nav_' + messageId + '_' + url;"," if (processedActions.includes(actionKey)) {"," return { handled: true, displayText: text };"," }"," processedActions.push(actionKey);"," localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"," var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"," window.location.href = targetUrl;"," return { handled: true, displayText: text };"," }"," ];",""," // Send DOM context with each request"," widgetConfig.requestMiddleware = function(ctx) {"," return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"," };",""," // Markdown postprocessor"," widgetConfig.postprocessMessage = function(ctx) {"," return agentWidget.markdownPostprocessor(ctx.text);"," };",""," return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('vanilla-agent:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('vanilla-agent:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"].join(`
67
- `)}var Va=ur;export{Kt as AgentWidgetClient,on as AgentWidgetSession,rr as DEFAULT_DARK_THEME,sr as DEFAULT_LIGHT_THEME,Le as DEFAULT_WIDGET_CONFIG,rn as attachHeaderToContainer,ln as buildComposer,Ks as buildDefaultHeader,Vs as buildExpandedHeader,Nt as buildHeader,an as buildHeaderWithLayout,Xs as buildMinimalHeader,cn as componentRegistry,Mn as createActionManager,ao as createAgentExperience,Rr as createBubbleWithLayout,so as createCSATFeedback,Ur as createComponentMiddleware,eo as createComponentStreamParser,wr as createDirectivePostprocessor,xr as createFlexibleJsonStreamParser,Nn as createJsonStreamParser,Qn as createLocalStorageAdapter,vn as createMarkdownProcessor,bn as createMarkdownProcessorFromConfig,tr as createMessageActions,ro as createNPSFeedback,$n as createPlainTextParser,Fn as createRegexJsonParser,dn as createStandardBubble,An as createTypingIndicator,On as createXmlParser,Va as default,Xt as defaultActionHandlers,En as defaultJsonActionParser,yr as directivePostprocessor,Pn as escapeHtml,oo as extractComponentDirectiveFromMessage,_n as generateAssistantMessageId,Vr as generateCodeSnippet,Tr as generateMessageId,Dn as generateUserMessageId,Gs as getHeaderLayout,no as hasComponentDirective,qn as headerLayouts,ur as initAgentWidget,qr as isComponentDirectiveType,Fs as markdownPostprocessor,Vn as mergeWithDefaults,Tn as pluginRegistry,to as renderComponentDirective};
67
+ `)}var ol=yr;export{Jt as AgentWidgetClient,dn as AgentWidgetSession,pr as DEFAULT_DARK_THEME,ur as DEFAULT_LIGHT_THEME,We as DEFAULT_WIDGET_CONFIG,Yt as attachHeaderToContainer,pn as buildComposer,Zs as buildDefaultHeader,tr as buildExpandedHeader,Ft as buildHeader,un as buildHeaderWithLayout,er as buildMinimalHeader,mn as componentRegistry,Bn as createActionManager,co as createAgentExperience,Dr as createBubbleWithLayout,io as createCSATFeedback,Gr as createComponentMiddleware,no as createComponentStreamParser,Ar as createDirectivePostprocessor,Wr as createFlexibleJsonStreamParser,jn as createJsonStreamParser,eo as createLocalStorageAdapter,Sn as createMarkdownProcessor,An as createMarkdownProcessorFromConfig,ir as createMessageActions,ao as createNPSFeedback,Dn as createPlainTextParser,_n as createRegexJsonParser,gn as createStandardBubble,kn as createTypingIndicator,qn as createXmlParser,ol as default,Vt as defaultActionHandlers,Ln as defaultJsonActionParser,Tr as directivePostprocessor,Nn as escapeHtml,ro as extractComponentDirectiveFromMessage,zn as generateAssistantMessageId,oi as generateCodeSnippet,Hr as generateMessageId,Un as generateUserMessageId,nr as getHeaderLayout,so as hasComponentDirective,Yn as headerLayouts,yr as initAgentWidget,Vr as isComponentDirectiveType,js as markdownPostprocessor,Qn as mergeWithDefaults,Wn as pluginRegistry,oo as renderComponentDirective};
68
68
  //# sourceMappingURL=index.js.map