vanilla-agent 1.21.0 → 1.23.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.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var Po=Object.create;var bn=Object.defineProperty;var Oo=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var Fo=Object.getPrototypeOf,Do=Object.prototype.hasOwnProperty;var jo=(n,e)=>{for(var r in e)bn(n,r,{get:e[r],enumerable:!0})},uo=(n,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of No(e))!Do.call(n,o)&&o!==r&&bn(n,o,{get:()=>e[o],enumerable:!(t=Oo(e,o))||t.enumerable});return n};var _o=(n,e,r)=>(r=n!=null?Po(Fo(n)):{},uo(e||!n||!n.__esModule?bn(r,"default",{value:n,enumerable:!0}):r,n)),qo=n=>uo(bn({},"__esModule",{value:!0}),n);var vr={};jo(vr,{AgentWidgetClient:()=>Yt,AgentWidgetSession:()=>Gt,DEFAULT_WIDGET_CONFIG:()=>Le,attachHeaderToContainer:()=>Zt,buildComposer:()=>Qt,buildDefaultHeader:()=>qn,buildExpandedHeader:()=>zn,buildHeader:()=>Ft,buildHeaderWithLayout:()=>Ln,buildMinimalHeader:()=>Un,componentRegistry:()=>tn,createActionManager:()=>mn,createAgentExperience:()=>Pn,createBubbleWithLayout:()=>To,createComponentMiddleware:()=>ko,createComponentStreamParser:()=>Hn,createDirectivePostprocessor:()=>wo,createFlexibleJsonStreamParser:()=>xo,createJsonStreamParser:()=>En,createLocalStorageAdapter:()=>kn,createMarkdownProcessor:()=>dn,createMarkdownProcessorFromConfig:()=>cn,createPlainTextParser:()=>An,createRegexJsonParser:()=>Tn,createStandardBubble:()=>en,createTypingIndicator:()=>un,createXmlParser:()=>Wn,default:()=>yr,defaultActionHandlers:()=>Jt,defaultJsonActionParser:()=>hn,directivePostprocessor:()=>yo,escapeHtml:()=>xn,extractComponentDirectiveFromMessage:()=>$n,generateCodeSnippet:()=>$o,getHeaderLayout:()=>Yn,hasComponentDirective:()=>In,headerLayouts:()=>Mn,initAgentWidget:()=>ss,isComponentDirectiveType:()=>Bo,markdownPostprocessor:()=>Dn,mergeWithDefaults:()=>Bn,pluginRegistry:()=>gn,renderComponentDirective:()=>Rn});module.exports=qo(vr);var ho=require("marked"),Uo=n=>{if(n)return n},dn=n=>{var o,s;let e=n==null?void 0:n.markedOptions,r=new ho.Marked({gfm:(o=e==null?void 0:e.gfm)!=null?o:!0,breaks:(s=e==null?void 0:e.breaks)!=null?s:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),t=Uo(n==null?void 0:n.renderer);return t&&r.use({renderer:t}),i=>r.parse(i)},cn=n=>n?dn({markedOptions:n.options,renderer:n.renderer}):dn(),zo=dn(),Dn=n=>zo(n),xn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),mo=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),go=n=>`%%FORM_PLACEHOLDER_${n}%%`,fo=(n,e)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=go(e.length);return e.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=go(e.length);return e.push({token:s,type:o}),s}),r},wo=n=>{let e=cn(n);return r=>{let t=[],o=fo(r,t),s=e(o);return t.forEach(({token:i,type:l})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${mo(l)}"></div>`;s=s.replace(c,d)}),s}},yo=n=>{let e=[],r=fo(n,e),t=Dn(r);return e.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="tvw-form-directive" data-tv-form="${mo(s)}"></div>`;t=t.replace(i,c)}),t};var Lt=require("partial-json"),Cn=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),jn=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)}},Yo=n=>{var i,l;let e=(i=n.completedAt)!=null?i:Date.now(),r=(l=n.startedAt)!=null?l:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},vo=n=>n.status==="complete"?Yo(n):n.status==="pending"?"Waiting":"",Jo=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var bo=n=>n.status==="complete"?Jo(n):"Using tool...",Ko=()=>{let n=null,e=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=t.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},Sn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},An=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Tn=()=>{var e;let n=Ko();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},En=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=(0,Lt.parse)(r,Lt.STR|Lt.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?Cn(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=Cn(o.text)))}catch{}return e=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},xo=n=>{let e=null,r=0,o=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:()=>e,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let l=(0,Lt.parse)(s,Lt.STR|Lt.OBJ),c=o(l);c!==null&&(e=c)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Wn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Xo="https://api.travrse.ai/v1/dispatch";function Vo(n){switch(n){case"json":return En;case"regex-json":return Tn;case"xml":return Wn;case"plain":default:return An}}var Yt=class{constructor(e={}){this.config=e;var r,t,o;this.apiUrl=(r=e.apiUrl)!=null?r:Xo,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:Vo(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}async dispatch(e,r){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw r({type:"error",error:c}),c}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:l}),l}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(o=>({role:o.role,content:o.rawContent||o.content,createdAt:o.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(e,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let c={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=c,o(c),c};if(i.text!==void 0){let c=l();c.content+=i.text,o(c)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r){var Z,$,Ne,Ye,Qe,xt,Ct,D,me,mt,ft,Je,et,M,Be,it,at,Et,wt,$e,tt,qe,j,lt,Ke,We,_e,J,Se,ke,Ue,nt,St,Bt,gt,At,de,Dt,kt,be,yt,Tt,Ht,vt,Wt,fn,wn,yn,Nn,jt,_t,st,Kt,on,rn,an;let t=e.getReader(),o=new TextDecoder,s="",i=Date.now(),l=0,c=()=>i+l++,g=y=>{let K=y.reasoning?{...y.reasoning,chunks:[...y.reasoning.chunks]}:void 0,oe=y.toolCall?{...y.toolCall,chunks:y.toolCall.chunks?[...y.toolCall.chunks]:void 0}:void 0,we=y.tools?y.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...y,reasoning:K,toolCall:oe,tools:we}},d=y=>{r({type:"message",message:g(y)})},A=null,f={current:null},b=new Map,w=new Map,q={lastId:null,byStep:new Map},F={lastId:null,byCall:new Map},m=y=>{if(y==null)return null;try{return String(y)}catch{return null}},x=y=>{var K,oe,we,Pe,Oe;return m((Oe=(Pe=(we=(oe=(K=y.stepId)!=null?K:y.step_id)!=null?oe:y.step)!=null?we:y.parentId)!=null?Pe:y.flowStepId)!=null?Oe:y.flow_step_id)},I=y=>{var K,oe,we,Pe,Oe,ce,L;return m((L=(ce=(Oe=(Pe=(we=(oe=(K=y.callId)!=null?K:y.call_id)!=null?oe:y.requestId)!=null?we:y.request_id)!=null?Pe:y.toolCallId)!=null?Oe:y.tool_call_id)!=null?ce:y.stepId)!=null?L:y.step_id)},S=()=>A||(A={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(A),A),Y=(y,K)=>{q.lastId=K,y&&q.byStep.set(y,K)},P=(y,K)=>{var Oe;let oe=(Oe=y.reasoningId)!=null?Oe:y.id,we=x(y);if(oe){let ce=String(oe);return Y(we,ce),ce}if(we){let ce=q.byStep.get(we);if(ce)return q.lastId=ce,ce}if(q.lastId&&!K)return q.lastId;if(!K)return null;let Pe=`reason-${c()}`;return Y(we,Pe),Pe},V=y=>{let K=b.get(y);if(K)return K;let oe={id:`reason-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:y,status:"streaming",chunks:[]}};return b.set(y,oe),d(oe),oe},Q=(y,K)=>{F.lastId=K,y&&F.byCall.set(y,K)},W=(y,K)=>{var Oe;let oe=(Oe=y.toolId)!=null?Oe:y.id,we=I(y);if(oe){let ce=String(oe);return Q(we,ce),ce}if(we){let ce=F.byCall.get(we);if(ce)return F.lastId=ce,ce}if(F.lastId&&!K)return F.lastId;if(!K)return null;let Pe=`tool-${c()}`;return Q(we,Pe),Pe},le=y=>{let K=w.get(y);if(K)return K;let oe={id:`tool-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:y,status:"pending"}};return w.set(y,oe),d(oe),oe},G=y=>{if(typeof y=="number"&&Number.isFinite(y))return y;if(typeof y=="string"){let K=Number(y);if(!Number.isNaN(K)&&Number.isFinite(K))return K;let oe=Date.parse(y);if(!Number.isNaN(oe))return oe}return Date.now()},U=y=>{if(typeof y=="string")return y;if(y==null)return"";try{return JSON.stringify(y)}catch{return String(y)}},z=new Map,ne=new Map;for(;;){let{done:y,value:K}=await t.read();if(y)break;s+=o.decode(K,{stream:!0});let oe=s.split(`
1
+ "use strict";var Uo=Object.create;var Cn=Object.defineProperty;var zo=Object.getOwnPropertyDescriptor;var Jo=Object.getOwnPropertyNames;var Yo=Object.getPrototypeOf,Ko=Object.prototype.hasOwnProperty;var Xo=(n,e)=>{for(var s in e)Cn(n,s,{get:e[s],enumerable:!0})},yo=(n,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jo(e))!Ko.call(n,r)&&r!==s&&Cn(n,r,{get:()=>e[r],enumerable:!(t=zo(e,r))||t.enumerable});return n};var Vo=(n,e,s)=>(s=n!=null?Uo(Yo(n)):{},yo(e||!n||!n.__esModule?Cn(s,"default",{value:n,enumerable:!0}):s,n)),Go=n=>yo(Cn({},"__esModule",{value:!0}),n);var Wr={};Xo(Wr,{AgentWidgetClient:()=>Yt,AgentWidgetSession:()=>Zt,DEFAULT_WIDGET_CONFIG:()=>ke,attachHeaderToContainer:()=>Qt,buildComposer:()=>en,buildDefaultHeader:()=>Kn,buildExpandedHeader:()=>Vn,buildHeader:()=>Ot,buildHeaderWithLayout:()=>Hn,buildMinimalHeader:()=>Xn,componentRegistry:()=>nn,createActionManager:()=>fn,createAgentExperience:()=>_n,createBubbleWithLayout:()=>Po,createCSATFeedback:()=>On,createComponentMiddleware:()=>Oo,createComponentStreamParser:()=>In,createDirectivePostprocessor:()=>So,createFlexibleJsonStreamParser:()=>Mo,createJsonStreamParser:()=>Mn,createLocalStorageAdapter:()=>Rn,createMarkdownProcessor:()=>cn,createMarkdownProcessorFromConfig:()=>un,createMessageActions:()=>Zn,createNPSFeedback:()=>Dn,createPlainTextParser:()=>Tn,createRegexJsonParser:()=>En,createStandardBubble:()=>tn,createTypingIndicator:()=>gn,createXmlParser:()=>Wn,default:()=>Mr,defaultActionHandlers:()=>Kt,defaultJsonActionParser:()=>mn,directivePostprocessor:()=>Ao,escapeHtml:()=>xn,extractComponentDirectiveFromMessage:()=>Nn,generateAssistantMessageId:()=>Ln,generateCodeSnippet:()=>qo,generateMessageId:()=>ko,generateUserMessageId:()=>kn,getHeaderLayout:()=>Gn,hasComponentDirective:()=>Fn,headerLayouts:()=>Bn,initAgentWidget:()=>ds,isComponentDirectiveType:()=>No,markdownPostprocessor:()=>zn,mergeWithDefaults:()=>Pn,pluginRegistry:()=>hn,renderComponentDirective:()=>$n});module.exports=Go(Wr);var bo=require("marked"),Zo=n=>{if(n)return n},cn=n=>{var r,o;let e=n==null?void 0:n.markedOptions,s=new bo.Marked({gfm:(r=e==null?void 0:e.gfm)!=null?r:!0,breaks:(o=e==null?void 0:e.breaks)!=null?o:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),t=Zo(n==null?void 0:n.renderer);return t&&s.use({renderer:t}),a=>s.parse(a)},un=n=>n?cn({markedOptions:n.options,renderer:n.renderer}):cn(),Qo=cn(),zn=n=>Qo(n),xn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Co=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vo=n=>`%%FORM_PLACEHOLDER_${n}%%`,xo=(n,e)=>{let s=n;return s=s.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let o=JSON.parse(r.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=vo(e.length);return e.push({token:a,type:String(o.type)}),a}}catch{return t}return t}),s=s.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let o=vo(e.length);return e.push({token:o,type:r}),o}),s},So=n=>{let e=un(n);return s=>{let t=[],r=xo(s,t),o=e(r);return t.forEach(({token:a,type:l})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${Co(l)}"></div>`;o=o.replace(p,f)}),o}},Ao=n=>{let e=[],s=xo(n,e),t=zn(s);return e.forEach(({token:r,type:o})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="tvw-form-directive" data-tv-form="${Co(o)}"></div>`;t=t.replace(a,p)}),t};var Lt=require("partial-json"),Sn=n=>n.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Jn=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 a,l;let e=(a=n.completedAt)!=null?a:Date.now(),s=(l=n.startedAt)!=null?l:e,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-s))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},To=n=>n.status==="complete"?er(n):n.status==="pending"?"Waiting":"",tr=n=>{var r,o,a;let s=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((r=n.completedAt)!=null?r:Date.now())-((a=(o=n.startedAt)!=null?o:n.completedAt)!=null?a:Date.now())))/1e3;return s<.1?"Used tool for <0.1 seconds":`Used tool for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`};var Eo=n=>n.status==="complete"?tr(n):"Using tool...",nr=()=>{let n=null,e=0,s=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=t.match(r);if(o&&o[1])try{return o[1].replace(/\\n/g,`
3
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=t.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let o=s(t);return o!==null&&(n=o),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},An=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Tn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},En=()=>{var e;let n=nr();return{processChunk:async s=>{let t=s.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(s)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Mn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:s=>{let t=s.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(s.length<=e)return n!==null||n===""?{text:n||"",raw:s}:null;try{let r=(0,Lt.parse)(s,Lt.STR|Lt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?Sn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=Sn(r.text)))}catch{}return e=s.length,n!==null?{text:n,raw:s}:null},close:()=>{}}},Mo=n=>{let e=null,s=0,r=n||(o=>{if(!o||typeof o!="object")return null;let a=l=>typeof l=="string"?Sn(l):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Sn(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>e,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=s)return e!==null?{text:e,raw:o}:null;try{let l=(0,Lt.parse)(o,Lt.STR|Lt.OBJ),p=r(l);p!==null&&(e=p)}catch{}return s=o.length,{text:e||"",raw:o}},close:()=>{}}},Wn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var sr="https://api.travrse.ai/v1/dispatch",Wo="https://api.travrse.ai";function or(n){switch(n){case"json":return Mn;case"regex-json":return En;case"xml":return Wn;case"plain":default:return Tn}}var Yt=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;var s,t,r;this.apiUrl=(s=e.apiUrl)!=null?s:sr,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:or(e.parserType),this.contextProviders=(r=e.contextProviders)!=null?r:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(e){var t;let s=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wo;return e==="init"?`${s}/v1/client/init`:`${s}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var e,s;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 t=await this.sessionInitPromise;return this.clientSession=t,(s=(e=this.config).onSessionInit)==null||s.call(e,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=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(!e.ok){let t=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${t.hint||t.error}`):e.status===403?new Error(`Origin not allowed: ${t.hint||t.error}`):new Error(t.error||"Failed to initialize session")}let s=await e.json();return{sessionId:s.session_id,expiresAt:new Date(s.expires_at),flow:s.flow,config:{welcomeMessage:s.config.welcome_message,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var s;return`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wo}/v1/client/feedback`}async sendFeedback(e){var o,a;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(e.type)&&!e.message_id)throw new Error(`message_id is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:e,type:s})}async submitCSATFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:e,comment:s})}async submitNPSFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:e,comment:s})}async dispatch(e,s){return this.isClientTokenMode()?this.dispatchClientToken(e,s):this.dispatchProxy(e,s)}async dispatchClientToken(e,s){var r,o,a,l;let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),s({type:"status",status:"connecting"});try{let p=await this.initSession();if(new Date>=new Date(p.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(r=this.config).onSessionExpired)==null||o.call(r);let d=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:d}),d}let c=await this.buildPayload(e.messages),f={session_id:p.sessionId,messages:e.messages.map(d=>({id:d.id,role:d.role,content:d.rawContent||d.content})),...e.assistantMessageId&&{assistant_message_id:e.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:t.signal});if(!w.ok){let d=await w.json().catch(()=>({error:"Chat request failed"}));if(w.status===401){this.clientSession=null,(l=(a=this.config).onSessionExpired)==null||l.call(a);let g=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:g}),g}if(w.status===429){let g=new Error(d.hint||"Message limit reached for this session.");throw s({type:"error",error:g}),g}let C=new Error(d.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!w.body){let d=new Error("No response body received");throw s({type:"error",error:d}),d}s({type:"status",status:"connected"});try{await this.streamResponse(w.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(p){let c=p instanceof Error?p:new Error(String(p));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&s({type:"error",error:c}),c}}async dispatchProxy(e,s){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),s({type:"status",status:"connecting"});let r=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();o={...o,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal},r)}catch(l){let p=l instanceof Error?l:new Error(String(l));throw s({type:"error",error:p}),p}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal});if(!a.ok||!a.body){let l=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw s({type:"error",error:l}),l}s({type:"status",status:"connected"});try{await this.streamResponse(a.body,s)}finally{s({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((r,o)=>{let a=new Date(r.createdAt).getTime(),l=new Date(o.createdAt).getTime();return a-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 o=>{try{let a=await o({messages:e,config:this.config});a&&typeof a=="object"&&Object.assign(r,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(e,s,t,r,o){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(e);if(a===null)return!1;let l=()=>{if(t.current)return t.current;let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return t.current=p,r(p),p};if(a.text!==void 0){let p=l();p.content+=a.text,r(p)}return a.done&&(t.current&&(t.current.streaming=!1,r(t.current)),s({type:"status",status:"idle"})),a.error&&s({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(e,s,t){var re,q,qe,Ve,nt,bt,Ct,J,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,$e,ot,Ue,I,dt,Se,Oe,te,Ae,Te,ze,Je,xt,Bt,yt,Et,St,ye,Ht,Le,Ye,At,Dt,Mt,_t,Wt,wn,yn,vn,qn,jt,qt,Ke,Xt,rn,an,ln;let r=e.getReader(),o=new TextDecoder,a="",l=Date.now(),p=0,c=()=>l+p++,f=A=>{let V=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,ie=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,ve=A.tools?A.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...A,reasoning:V,toolCall:ie,tools:ve}},w=A=>{s({type:"message",message:f(A)})},d=null,C={current:null},g=new Map,U=new Map,$={lastId:null,byStep:new Map},h={lastId:null,byCall:new Map},b=A=>{if(A==null)return null;try{return String(A)}catch{return null}},W=A=>{var V,ie,ve,Fe,Ne;return b((Ne=(Fe=(ve=(ie=(V=A.stepId)!=null?V:A.step_id)!=null?ie:A.step)!=null?ve:A.parentId)!=null?Fe:A.flowStepId)!=null?Ne:A.flow_step_id)},v=A=>{var V,ie,ve,Fe,Ne,ue,P;return b((P=(ue=(Ne=(Fe=(ve=(ie=(V=A.callId)!=null?V:A.call_id)!=null?ie:A.requestId)!=null?ve:A.request_id)!=null?Fe:A.toolCallId)!=null?Ne:A.tool_call_id)!=null?ue:A.stepId)!=null?P:A.step_id)},D=()=>d||(d={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},w(d),d),x=(A,V)=>{$.lastId=V,A&&$.byStep.set(A,V)},S=(A,V)=>{var Ne;let ie=(Ne=A.reasoningId)!=null?Ne:A.id,ve=W(A);if(ie){let ue=String(ie);return x(ve,ue),ue}if(ve){let ue=$.byStep.get(ve);if(ue)return $.lastId=ue,ue}if($.lastId&&!V)return $.lastId;if(!V)return null;let Fe=`reason-${c()}`;return x(ve,Fe),Fe},X=A=>{let V=g.get(A);if(V)return V;let ie={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:A,status:"streaming",chunks:[]}};return g.set(A,ie),w(ie),ie},B=(A,V)=>{h.lastId=V,A&&h.byCall.set(A,V)},_=(A,V)=>{var Ne;let ie=(Ne=A.toolId)!=null?Ne:A.id,ve=v(A);if(ie){let ue=String(ie);return B(ve,ue),ue}if(ve){let ue=h.byCall.get(ve);if(ue)return h.lastId=ue,ue}if(h.lastId&&!V)return h.lastId;if(!V)return null;let Fe=`tool-${c()}`;return B(ve,Fe),Fe},Z=A=>{let V=U.get(A);if(V)return V;let ie={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:A,status:"pending"}};return U.set(A,ie),w(ie),ie},j=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let V=Number(A);if(!Number.isNaN(V)&&Number.isFinite(V))return V;let ie=Date.parse(A);if(!Number.isNaN(ie))return ie}return Date.now()},K=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},Q=new Map,ne=new Map;for(;;){let{done:A,value:V}=await r.read();if(A)break;a+=o.decode(V,{stream:!0});let ie=a.split(`
5
5
 
6
- `);s=(Z=oe.pop())!=null?Z:"";for(let we of oe){let Pe=we.split(`
7
- `),Oe="message",ce="";for(let ee of Pe)ee.startsWith("event:")?Oe=ee.replace("event:","").trim():ee.startsWith("data:")&&(ce+=ee.replace("data:","").trim());if(!ce)continue;let L;try{L=JSON.parse(ce)}catch(ee){r({type:"error",error:ee instanceof Error?ee:new Error("Failed to parse chat stream payload")});continue}let ot=Oe!=="message"?Oe:($=L.type)!=null?$:"message";if(this.parseSSEEvent){f.current=A;let ee=await this.handleCustomSSEEvent(L,r,f,d,c);if(f.current&&!A&&(A=f.current),ee)continue}if(ot==="reason_start"){let ee=(Ne=P(L,!0))!=null?Ne:`reason-${c()}`,C=V(ee);C.reasoning=(Ye=C.reasoning)!=null?Ye:{id:ee,status:"streaming",chunks:[]},C.reasoning.startedAt=(xt=C.reasoning.startedAt)!=null?xt:G((Qe=L.startedAt)!=null?Qe:L.timestamp),C.reasoning.completedAt=void 0,C.reasoning.durationMs=void 0,C.streaming=!0,C.reasoning.status="streaming",d(C)}else if(ot==="reason_chunk"){let ee=(D=(Ct=P(L,!1))!=null?Ct:P(L,!0))!=null?D:`reason-${c()}`,C=V(ee);C.reasoning=(me=C.reasoning)!=null?me:{id:ee,status:"streaming",chunks:[]},C.reasoning.startedAt=(ft=C.reasoning.startedAt)!=null?ft:G((mt=L.startedAt)!=null?mt:L.timestamp);let h=(M=(et=(Je=L.reasoningText)!=null?Je:L.text)!=null?et:L.delta)!=null?M:"";if(h&&L.hidden!==!0&&C.reasoning.chunks.push(String(h)),C.reasoning.status=L.done?"complete":"streaming",L.done){C.reasoning.completedAt=G((Be=L.completedAt)!=null?Be:L.timestamp);let k=(it=C.reasoning.startedAt)!=null?it:Date.now();C.reasoning.durationMs=Math.max(0,((at=C.reasoning.completedAt)!=null?at:Date.now())-k)}C.streaming=C.reasoning.status!=="complete",d(C)}else if(ot==="reason_complete"){let ee=(wt=(Et=P(L,!1))!=null?Et:P(L,!0))!=null?wt:`reason-${c()}`,C=b.get(ee);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=G(($e=L.completedAt)!=null?$e:L.timestamp);let k=(tt=C.reasoning.startedAt)!=null?tt:Date.now();C.reasoning.durationMs=Math.max(0,((qe=C.reasoning.completedAt)!=null?qe:Date.now())-k),C.streaming=!1,d(C)}let h=x(L);h&&q.byStep.delete(h)}else if(ot==="tool_start"){let ee=(j=W(L,!0))!=null?j:`tool-${c()}`,C=le(ee),h=(lt=C.toolCall)!=null?lt:{id:ee,status:"pending"};h.name=(Ke=L.toolName)!=null?Ke:h.name,h.status="running",L.args!==void 0&&(h.args=L.args),h.startedAt=(_e=h.startedAt)!=null?_e:G((We=L.startedAt)!=null?We:L.timestamp),h.completedAt=void 0,h.durationMs=void 0,C.toolCall=h,C.streaming=!0,d(C)}else if(ot==="tool_chunk"){let ee=(Se=(J=W(L,!1))!=null?J:W(L,!0))!=null?Se:`tool-${c()}`,C=le(ee),h=(ke=C.toolCall)!=null?ke:{id:ee,status:"running"};h.startedAt=(nt=h.startedAt)!=null?nt:G((Ue=L.startedAt)!=null?Ue:L.timestamp);let k=(gt=(Bt=(St=L.text)!=null?St:L.delta)!=null?Bt:L.message)!=null?gt:"";k&&(h.chunks=(At=h.chunks)!=null?At:[],h.chunks.push(String(k))),h.status="running",C.toolCall=h,C.streaming=!0,d(C)}else if(ot==="tool_complete"){let ee=(Dt=(de=W(L,!1))!=null?de:W(L,!0))!=null?Dt:`tool-${c()}`,C=le(ee),h=(kt=C.toolCall)!=null?kt:{id:ee,status:"running"};if(h.status="complete",L.result!==void 0&&(h.result=L.result),typeof L.duration=="number"&&(h.duration=L.duration),h.completedAt=G((be=L.completedAt)!=null?be:L.timestamp),typeof L.duration=="number")h.durationMs=L.duration;else{let ye=(yt=h.startedAt)!=null?yt:Date.now();h.durationMs=Math.max(0,((Tt=h.completedAt)!=null?Tt:Date.now())-ye)}C.toolCall=h,C.streaming=!1,d(C);let k=I(L);k&&F.byCall.delete(k)}else if(ot==="step_chunk"){let ee=L.stepType,C=L.executionType;if(ee==="tool"||C==="context")continue;let h=S(),k=(fn=(Wt=(vt=(Ht=L.text)!=null?Ht:L.delta)!=null?vt:L.content)!=null?Wt:L.chunk)!=null?fn:"";if(k){let Ae=((wn=ne.get(h.id))!=null?wn:"")+k;h.rawContent=Ae,z.has(h.id)||z.set(h.id,this.createStreamParser());let Xe=z.get(h.id),He=Ae.trim().startsWith("{")||Ae.trim().startsWith("[");if(He&&ne.set(h.id,Ae),Xe.__isPlainTextParser===!0){h.content+=k,ne.delete(h.id),z.delete(h.id),h.rawContent=void 0,d(h);continue}let De=Xe.processChunk(Ae);if(De instanceof Promise)De.then(ae=>{var Re;let pe=typeof ae=="string"?ae:(Re=ae==null?void 0:ae.text)!=null?Re:null;if(pe!==null&&pe.trim()!==""){let ue=A;ue&&ue.id===h.id&&(ue.content=pe,d(ue))}else if(!He&&!Ae.trim().startsWith("<")){let ue=A;ue&&ue.id===h.id&&(ue.content+=k,ne.delete(ue.id),z.delete(ue.id),ue.rawContent=void 0,d(ue))}}).catch(()=>{h.content+=k,ne.delete(h.id),z.delete(h.id),h.rawContent=void 0,d(h)});else{let ae=typeof De=="string"?De:(yn=De==null?void 0:De.text)!=null?yn:null;ae!==null&&ae.trim()!==""?(h.content=ae,d(h)):!He&&!Ae.trim().startsWith("<")&&(h.content+=k,ne.delete(h.id),z.delete(h.id),h.rawContent=void 0,d(h))}}if(L.isComplete){let ye=(jt=(Nn=L.result)==null?void 0:Nn.response)!=null?jt:h.content;if(ye){let Ae=ne.get(h.id),Xe=Ae!=null?Ae:U(ye);h.rawContent=Xe;let He=z.get(h.id),xe=null,De=!1;if(He&&(xe=He.getExtractedText(),xe===null&&(xe=Sn(Xe)),xe===null)){let ae=He.processChunk(Xe);ae instanceof Promise?(De=!0,ae.then(pe=>{var ue;let Re=typeof pe=="string"?pe:(ue=pe==null?void 0:pe.text)!=null?ue:null;if(Re!==null){let Fe=A;Fe&&Fe.id===h.id&&(Fe.content=Re,Fe.streaming=!1,z.delete(Fe.id),ne.delete(Fe.id),d(Fe))}})):xe=typeof ae=="string"?ae:(_t=ae==null?void 0:ae.text)!=null?_t:null}if(!De){xe!==null&&xe.trim()!==""?h.content=xe:ne.has(h.id)||(h.content=U(ye));let ae=z.get(h.id);if(ae){let pe=(st=ae.close)==null?void 0:st.call(ae);pe instanceof Promise&&pe.catch(()=>{}),z.delete(h.id)}ne.delete(h.id),h.streaming=!1,d(h)}}}}else if(ot==="step_complete"){let ee=L.stepType,C=L.executionType;if(ee==="tool"||C==="context")continue;let h=(Kt=L.result)==null?void 0:Kt.response,k=S();if(h!=null){let ye=z.get(k.id),Ae=!1,Xe=!1;if(ye){let He=ye.getExtractedText(),xe=ne.get(k.id),De=xe!=null?xe:U(h);if(k.rawContent=De,He!==null&&He.trim()!=="")k.content=He,Ae=!0;else{let ae=Sn(De);if(ae!==null)k.content=ae,Ae=!0;else{let pe=ye.processChunk(De);if(pe instanceof Promise)Xe=!0,pe.then(Re=>{var Fe;let ue=typeof Re=="string"?Re:(Fe=Re==null?void 0:Re.text)!=null?Fe:null;if(ue!==null&&ue.trim()!==""){let rt=A;rt&&rt.id===k.id&&(rt.content=ue,rt.streaming=!1,z.delete(rt.id),ne.delete(rt.id),d(rt))}else{let rt=ye.getExtractedText(),ht=A;ht&&ht.id===k.id&&(rt!==null&&rt.trim()!==""?ht.content=rt:ne.has(ht.id)||(ht.content=U(h)),ht.streaming=!1,z.delete(ht.id),ne.delete(ht.id),d(ht))}});else{let Re=typeof pe=="string"?pe:(on=pe==null?void 0:pe.text)!=null?on:null;if(Re!==null&&Re.trim()!=="")k.content=Re,Ae=!0;else{let ue=ye.getExtractedText();ue!==null&&ue.trim()!==""&&(k.content=ue,Ae=!0)}}}}}if(!Xe){if(!k.rawContent){let He=ne.get(k.id);k.rawContent=He!=null?He:U(h)}if(!Ae&&!ne.has(k.id)&&(k.content=U(h)),ye){let He=(rn=ye.close)==null?void 0:rn.call(ye);He instanceof Promise&&He.catch(()=>{})}z.delete(k.id),ne.delete(k.id),k.streaming=!1,d(k)}}else z.delete(k.id),ne.delete(k.id),k.streaming=!1,d(k)}else if(ot==="flow_complete"){let ee=(an=L.result)==null?void 0:an.response;if(ee!=null){let C=S(),h=ne.get(C.id),k=h!=null?h:U(ee);C.rawContent=k;let ye=U(ee),Ae=z.get(C.id);if(Ae){let xe=Sn(k);if(xe!==null)ye=xe;else{let De=Ae.processChunk(k);De instanceof Promise&&De.then(pe=>{var ue;let Re=typeof pe=="string"?pe:(ue=pe==null?void 0:pe.text)!=null?ue:null;if(Re!==null){let Fe=A;Fe&&Fe.id===C.id&&(Fe.content=Re,Fe.streaming=!1,d(Fe))}});let ae=Ae.getExtractedText();ae!==null&&(ye=ae)}}z.delete(C.id),ne.delete(C.id);let Xe=ye!==C.content,He=C.streaming!==!1;Xe&&(C.content=ye),C.streaming=!1,(Xe||He)&&d(C)}else if(A!==null){let C=A;z.delete(C.id),ne.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}r({type:"status",status:"idle"})}else ot==="error"&&L.error&&r({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};var Gt=class{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=e=>{var r,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(r=this.callbacks).onError)==null||t.call(r,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(e){this.config={...this.config,...e},this.client=new Yt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,r){var l,c,g,d,A;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let o={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1};this.appendMessage(o),this.setStreaming(!0);let s=new AbortController;this.abortController=s;let i=[...this.messages];try{await this.client.dispatch({messages:i,signal:s.signal},this.handleEvent)}catch(f){let b={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f instanceof Error?(g=(c=this.callbacks).onError)==null||g.call(c,f):(A=(d=this.callbacks).onError)==null||A.call(d,new Error(String(f)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,t)=>{var c,g;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(c=r.sequence)!=null?c:0,l=(g=t.sequence)!=null?g:0;return i!==l?i-l:r.id.localeCompare(t.id)})}};var _n=(n,e)=>{var t;let r=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let i=o.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(s))})};var Go=_o(require("lucide"),1),ve=(n,e=24,r="currentColor",t=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Go[o];return s?Zo(s,e,r,t):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function Zo(n,e,r,t){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([g,d])=>{g!=="stroke"&&c.setAttribute(g,String(d))}),o.appendChild(c)}}}),o}var p=(n,e)=>{let r=document.createElement(n);return e&&(r.className=e),r};var ze={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var bt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var pn=(n,e)=>{let r=p("button");r.type="button",r.innerHTML=`
6
+ `);a=(re=ie.pop())!=null?re:"";for(let ve of ie){let Fe=ve.split(`
7
+ `),Ne="message",ue="";for(let se of Fe)se.startsWith("event:")?Ne=se.replace("event:","").trim():se.startsWith("data:")&&(ue+=se.replace("data:","").trim());if(!ue)continue;let P;try{P=JSON.parse(ue)}catch(se){s({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let rt=Ne!=="message"?Ne:(q=P.type)!=null?q:"message";if(this.parseSSEEvent){C.current=d;let se=await this.handleCustomSSEEvent(P,s,C,w,c);if(C.current&&!d&&(d=C.current),se)continue}if(rt==="reason_start"){let se=(qe=S(P,!0))!=null?qe:`reason-${c()}`,M=X(se);M.reasoning=(Ve=M.reasoning)!=null?Ve:{id:se,status:"streaming",chunks:[]},M.reasoning.startedAt=(bt=M.reasoning.startedAt)!=null?bt:j((nt=P.startedAt)!=null?nt:P.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",w(M)}else if(rt==="reason_chunk"){let se=(J=(Ct=S(P,!1))!=null?Ct:S(P,!0))!=null?J:`reason-${c()}`,M=X(se);M.reasoning=(fe=M.reasoning)!=null?fe:{id:se,status:"streaming",chunks:[]},M.reasoning.startedAt=(ft=M.reasoning.startedAt)!=null?ft:j((mt=P.startedAt)!=null?mt:P.timestamp);let y=(H=(st=(Ge=P.reasoningText)!=null?Ge:P.text)!=null?st:P.delta)!=null?H:"";if(y&&P.hidden!==!0&&M.reasoning.chunks.push(String(y)),M.reasoning.status=P.done?"complete":"streaming",P.done){M.reasoning.completedAt=j((He=P.completedAt)!=null?He:P.timestamp);let F=(at=M.reasoning.startedAt)!=null?at:Date.now();M.reasoning.durationMs=Math.max(0,((lt=M.reasoning.completedAt)!=null?lt:Date.now())-F)}M.streaming=M.reasoning.status!=="complete",w(M)}else if(rt==="reason_complete"){let se=(wt=(Tt=S(P,!1))!=null?Tt:S(P,!0))!=null?wt:`reason-${c()}`,M=g.get(se);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=j(($e=P.completedAt)!=null?$e:P.timestamp);let F=(ot=M.reasoning.startedAt)!=null?ot:Date.now();M.reasoning.durationMs=Math.max(0,((Ue=M.reasoning.completedAt)!=null?Ue:Date.now())-F),M.streaming=!1,w(M)}let y=W(P);y&&$.byStep.delete(y)}else if(rt==="tool_start"){let se=(I=_(P,!0))!=null?I:`tool-${c()}`,M=Z(se),y=(dt=M.toolCall)!=null?dt:{id:se,status:"pending"};y.name=(Se=P.toolName)!=null?Se:y.name,y.status="running",P.args!==void 0&&(y.args=P.args),y.startedAt=(te=y.startedAt)!=null?te:j((Oe=P.startedAt)!=null?Oe:P.timestamp),y.completedAt=void 0,y.durationMs=void 0,M.toolCall=y,M.streaming=!0,w(M)}else if(rt==="tool_chunk"){let se=(Te=(Ae=_(P,!1))!=null?Ae:_(P,!0))!=null?Te:`tool-${c()}`,M=Z(se),y=(ze=M.toolCall)!=null?ze:{id:se,status:"running"};y.startedAt=(xt=y.startedAt)!=null?xt:j((Je=P.startedAt)!=null?Je:P.timestamp);let F=(Et=(yt=(Bt=P.text)!=null?Bt:P.delta)!=null?yt:P.message)!=null?Et:"";F&&(y.chunks=(St=y.chunks)!=null?St:[],y.chunks.push(String(F))),y.status="running",M.toolCall=y,M.streaming=!0,w(M)}else if(rt==="tool_complete"){let se=(Ht=(ye=_(P,!1))!=null?ye:_(P,!0))!=null?Ht:`tool-${c()}`,M=Z(se),y=(Le=M.toolCall)!=null?Le:{id:se,status:"running"};if(y.status="complete",P.result!==void 0&&(y.result=P.result),typeof P.duration=="number"&&(y.duration=P.duration),y.completedAt=j((Ye=P.completedAt)!=null?Ye:P.timestamp),typeof P.duration=="number")y.durationMs=P.duration;else{let be=(At=y.startedAt)!=null?At:Date.now();y.durationMs=Math.max(0,((Dt=y.completedAt)!=null?Dt:Date.now())-be)}M.toolCall=y,M.streaming=!1,w(M);let F=v(P);F&&h.byCall.delete(F)}else if(rt==="step_chunk"){let se=P.stepType,M=P.executionType;if(se==="tool"||M==="context")continue;let y=D(),F=(wn=(Wt=(_t=(Mt=P.text)!=null?Mt:P.delta)!=null?_t:P.content)!=null?Wt:P.chunk)!=null?wn:"";if(F){let Ee=((yn=ne.get(y.id))!=null?yn:"")+F;y.rawContent=Ee,Q.has(y.id)||Q.set(y.id,this.createStreamParser());let Ze=Q.get(y.id),Pe=Ee.trim().startsWith("{")||Ee.trim().startsWith("[");if(Pe&&ne.set(y.id,Ee),Ze.__isPlainTextParser===!0){y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y);continue}let _e=Ze.processChunk(Ee);if(_e instanceof Promise)_e.then(de=>{var Re;let pe=typeof de=="string"?de:(Re=de==null?void 0:de.text)!=null?Re:null;if(pe!==null&&pe.trim()!==""){let ge=d;ge&&ge.id===y.id&&(ge.content=pe,w(ge))}else if(!Pe&&!Ee.trim().startsWith("<")){let ge=d;ge&&ge.id===y.id&&(ge.content+=F,ne.delete(ge.id),Q.delete(ge.id),ge.rawContent=void 0,w(ge))}}).catch(()=>{y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y)});else{let de=typeof _e=="string"?_e:(vn=_e==null?void 0:_e.text)!=null?vn:null;de!==null&&de.trim()!==""?(y.content=de,w(y)):!Pe&&!Ee.trim().startsWith("<")&&(y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y))}}if(P.isComplete){let be=(jt=(qn=P.result)==null?void 0:qn.response)!=null?jt:y.content;if(be){let Ee=ne.get(y.id),Ze=Ee!=null?Ee:K(be);y.rawContent=Ze;let Pe=Q.get(y.id),Ce=null,_e=!1;if(Pe&&(Ce=Pe.getExtractedText(),Ce===null&&(Ce=An(Ze)),Ce===null)){let de=Pe.processChunk(Ze);de instanceof Promise?(_e=!0,de.then(pe=>{var ge;let Re=typeof pe=="string"?pe:(ge=pe==null?void 0:pe.text)!=null?ge:null;if(Re!==null){let De=d;De&&De.id===y.id&&(De.content=Re,De.streaming=!1,Q.delete(De.id),ne.delete(De.id),w(De))}})):Ce=typeof de=="string"?de:(qt=de==null?void 0:de.text)!=null?qt:null}if(!_e){Ce!==null&&Ce.trim()!==""?y.content=Ce:ne.has(y.id)||(y.content=K(be));let de=Q.get(y.id);if(de){let pe=(Ke=de.close)==null?void 0:Ke.call(de);pe instanceof Promise&&pe.catch(()=>{}),Q.delete(y.id)}ne.delete(y.id),y.streaming=!1,w(y)}}}}else if(rt==="step_complete"){let se=P.stepType,M=P.executionType;if(se==="tool"||M==="context")continue;let y=(Xt=P.result)==null?void 0:Xt.response,F=D();if(y!=null){let be=Q.get(F.id),Ee=!1,Ze=!1;if(be){let Pe=be.getExtractedText(),Ce=ne.get(F.id),_e=Ce!=null?Ce:K(y);if(F.rawContent=_e,Pe!==null&&Pe.trim()!=="")F.content=Pe,Ee=!0;else{let de=An(_e);if(de!==null)F.content=de,Ee=!0;else{let pe=be.processChunk(_e);if(pe instanceof Promise)Ze=!0,pe.then(Re=>{var De;let ge=typeof Re=="string"?Re:(De=Re==null?void 0:Re.text)!=null?De:null;if(ge!==null&&ge.trim()!==""){let it=d;it&&it.id===F.id&&(it.content=ge,it.streaming=!1,Q.delete(it.id),ne.delete(it.id),w(it))}else{let it=be.getExtractedText(),ht=d;ht&&ht.id===F.id&&(it!==null&&it.trim()!==""?ht.content=it:ne.has(ht.id)||(ht.content=K(y)),ht.streaming=!1,Q.delete(ht.id),ne.delete(ht.id),w(ht))}});else{let Re=typeof pe=="string"?pe:(rn=pe==null?void 0:pe.text)!=null?rn:null;if(Re!==null&&Re.trim()!=="")F.content=Re,Ee=!0;else{let ge=be.getExtractedText();ge!==null&&ge.trim()!==""&&(F.content=ge,Ee=!0)}}}}}if(!Ze){if(!F.rawContent){let Pe=ne.get(F.id);F.rawContent=Pe!=null?Pe:K(y)}if(!Ee&&!ne.has(F.id)&&(F.content=K(y)),be){let Pe=(an=be.close)==null?void 0:an.call(be);Pe instanceof Promise&&Pe.catch(()=>{})}Q.delete(F.id),ne.delete(F.id),F.streaming=!1,w(F)}}else Q.delete(F.id),ne.delete(F.id),F.streaming=!1,w(F)}else if(rt==="flow_complete"){let se=(ln=P.result)==null?void 0:ln.response;if(se!=null){let M=D(),y=ne.get(M.id),F=y!=null?y:K(se);M.rawContent=F;let be=K(se),Ee=Q.get(M.id);if(Ee){let Ce=An(F);if(Ce!==null)be=Ce;else{let _e=Ee.processChunk(F);_e instanceof Promise&&_e.then(pe=>{var ge;let Re=typeof pe=="string"?pe:(ge=pe==null?void 0:pe.text)!=null?ge:null;if(Re!==null){let De=d;De&&De.id===M.id&&(De.content=Re,De.streaming=!1,w(De))}});let de=Ee.getExtractedText();de!==null&&(be=de)}}Q.delete(M.id),ne.delete(M.id);let Ze=be!==M.content,Pe=M.streaming!==!1;Ze&&(M.content=be),M.streaming=!1,(Ze||Pe)&&w(M)}else if(d!==null){let M=d;Q.delete(M.id),ne.delete(M.id),M.streaming!==!1&&(M.streaming=!1,w(M))}s({type:"status",status:"idle"})}else rt==="error"&&P.error&&s({type:"error",error:P.error instanceof Error?P.error:new Error(String(P.error))})}}}};function ko(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${n}_${e}`}function kn(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Ln(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Zt=class{constructor(e={},s){this.config=e;this.callbacks=s;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=e=>{var s,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(s=this.callbacks).onError)==null||t.call(s,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(r=>{var o;return{...r,sequence:(o=r.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var e,s;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(s=(e=this.callbacks).onError)==null||s.call(e,t instanceof Error?t:new Error(String(t))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(s)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,s){return this.client.submitMessageFeedback(e,s)}async submitCSATFeedback(e,s){return this.client.submitCSATFeedback(e,s)}async submitNPSFeedback(e,s){return this.client.submitNPSFeedback(e,s)}updateConfig(e){this.config={...this.config,...e},this.client=new Yt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,s){var c,f,w,d,C;let t=e.trim();if(!t)return;(c=this.abortController)==null||c.abort();let r=kn(),o=Ln(),a={id:r,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(s==null?void 0:s.viaVoice)||!1};this.appendMessage(a),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:l.signal,assistantMessageId:o},this.handleEvent)}catch(g){let U={id:o,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(U),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(w=(f=this.callbacks).onError)==null||w.call(f,g):(C=(d=this.callbacks).onError)==null||C.call(d,new Error(String(g)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let s=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,s]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let s=this.ensureSequence(e),t=this.messages.findIndex(r=>r.id===s.id);if(t===-1){this.appendMessage(s);return}this.messages=this.messages.map((r,o)=>o===t?{...r,...s}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((s,t)=>{var p,c;let r=new Date(s.createdAt).getTime(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let a=(p=s.sequence)!=null?p:0,l=(c=t.sequence)!=null?c:0;return a!==l?a-l:s.id.localeCompare(t.id)})}};var Yn=(n,e)=>{var t;let s=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(s).forEach(([r,o])=>{if(o==null||o==="")return;let a=r.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${a}`,String(o))})};var rr=Vo(require("lucide"),1),ce=(n,e=24,s="currentColor",t=2)=>{try{let r=n.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=rr[r];return o?ir(o,e,s,t):(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 ir(n,e,s,t){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",s),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],l=o[1];if(l){let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([c,f])=>{c!=="stroke"&&p.setAttribute(c,String(f))}),r.appendChild(p)}}}),r}var m=(n,e)=>{let s=document.createElement(n);return e&&(s.className=e),s};var Xe={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var vt={"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 pn=(n,e)=>{let s=m("button");s.type="button",s.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,20 +12,24 @@
12
12
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,r.addEventListener("click",e);let t=s=>{var m,x,I,S,Y,P,V,Q,W,le,G,U;let i=(m=s.launcher)!=null?m:{},l=r.querySelector("[data-role='launcher-title']");l&&(l.textContent=(x=i.title)!=null?x:"Chat Assistant");let c=r.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(I=i.subtitle)!=null?I:"Get answers fast");let g=r.querySelector(".tvw-flex-col");g&&(i.textHidden?g.style.display="none":g.style.display="");let d=r.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let z=(S=i.agentIconSize)!=null?S:"40px";if(d.style.height=z,d.style.width=z,d.innerHTML="",i.agentIconName){let ne=parseFloat(z)||24,Z=ve(i.agentIconName,ne*.6,"#ffffff",2);Z?(d.appendChild(Z),d.style.display=""):(d.textContent=(Y=i.agentIconText)!=null?Y:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(P=i.agentIconText)!=null?P:"\u{1F4AC}",d.style.display="")}let A=r.querySelector("[data-role='launcher-image']");if(A){let z=(V=i.agentIconSize)!=null?V:"40px";A.style.height=z,A.style.width=z,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(A.src=i.iconUrl,A.style.display="block"):A.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let z=(Q=i.callToActionIconSize)!=null?Q:"32px";f.style.height=z,f.style.width=z,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let ne=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,ne=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let Z=parseFloat(z)||24,$=Math.max(Z-ne,8),Ne=ve(i.callToActionIconName,$,"currentColor",2);Ne?f.appendChild(Ne):f.textContent=(W=i.callToActionIconText)!=null?W:"\u2197"}else f.textContent=(le=i.callToActionIconText)!=null?le:"\u2197"}let b=i.position&&bt[i.position]?bt[i.position]:bt["bottom-right"],w="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${w} ${b}`;let q="1px solid #e5e7eb",F="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(G=i.border)!=null?G:q,r.style.boxShadow=(U=i.shadow)!=null?U:F},o=()=>{r.removeEventListener("click",e),r.remove()};return n&&t(n),{element:r,update:t,destroy:o}};var Ft=n=>{var le,G,U,z,ne,Z,$,Ne,Ye,Qe,xt,Ct,D,me,mt,ft,Je,et,M,Be,it,at,Et,wt,$e,tt,qe,j,lt,Ke,We,_e;let{config:e,showClose:r=!0}=n,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(le=e==null?void 0:e.launcher)!=null?le:{},s=(G=o.headerIconSize)!=null?G:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",l=(z=o.closeButtonPlacement)!=null?z:"inline",c=(ne=o.headerIconHidden)!=null?ne:!1,g=o.headerIconName,d=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(d.style.height=s,d.style.width=s,!c)if(g){let J=parseFloat(s)||24,Se=ve(g,J*.6,"#ffffff",2);Se?d.replaceChildren(Se):d.textContent=($=(Z=e==null?void 0:e.launcher)==null?void 0:Z.agentIconText)!=null?$:"\u{1F4AC}"}else if((Ne=e==null?void 0:e.launcher)!=null&&Ne.iconUrl){let J=p("img");J.src=e.launcher.iconUrl,J.alt="",J.className="tvw-rounded-xl tvw-object-cover",J.style.height=s,J.style.width=s,d.replaceChildren(J)}else d.textContent=(Qe=(Ye=e==null?void 0:e.launcher)==null?void 0:Ye.agentIconText)!=null?Qe:"\u{1F4AC}";let A=p("div","tvw-flex tvw-flex-col"),f=p("span","tvw-text-base tvw-font-semibold");f.textContent=(Ct=(xt=e==null?void 0:e.launcher)==null?void 0:xt.title)!=null?Ct:"Chat Assistant";let b=p("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(me=(D=e==null?void 0:e.launcher)==null?void 0:D.subtitle)!=null?me:"Here to help you get answers fast",A.append(f,b),c?t.append(A):t.append(d,A);let w=(mt=o.clearChat)!=null?mt:{},q=(ft=w.enabled)!=null?ft:!0,F=(Je=w.placement)!=null?Je:"inline",m=null,x=null;if(q){let J=(et=w.size)!=null?et:"32px",Se=(M=w.iconName)!=null?M:"refresh-cw",ke=(Be=w.iconColor)!=null?Be:"",Ue=(it=w.backgroundColor)!=null?it:"",nt=(at=w.borderWidth)!=null?at:"",St=(Et=w.borderColor)!=null?Et:"",Bt=(wt=w.borderRadius)!=null?wt:"",gt=($e=w.paddingX)!=null?$e:"",At=(tt=w.paddingY)!=null?tt:"",de=(qe=w.tooltipText)!=null?qe:"Clear chat",Dt=(j=w.showTooltip)!=null?j:!0;x=p("div",F==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),F==="top-right"&&(x.style.right="48px"),m=p("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=J,m.style.width=J,m.type="button",m.setAttribute("aria-label",de);let kt=ve(Se,"20px",ke||"",2);if(kt&&m.appendChild(kt),ke&&(m.style.color=ke,m.classList.remove("tvw-text-cw-muted")),Ue&&(m.style.backgroundColor=Ue,m.classList.remove("hover:tvw-bg-gray-100")),nt||St){let be=nt||"0px",yt=St||"transparent";m.style.border=`${be} solid ${yt}`,m.classList.remove("tvw-border-none")}if(Bt&&(m.style.borderRadius=Bt,m.classList.remove("tvw-rounded-full")),gt?(m.style.paddingLeft=gt,m.style.paddingRight=gt):(m.style.paddingLeft="",m.style.paddingRight=""),At?(m.style.paddingTop=At,m.style.paddingBottom=At):(m.style.paddingTop="",m.style.paddingBottom=""),x.appendChild(m),Dt&&de&&m&&x){let be=null,yt=()=>{if(be||!m)return;be=p("div","tvw-clear-chat-tooltip"),be.textContent=de;let Ht=p("div");Ht.className="tvw-clear-chat-tooltip-arrow",be.appendChild(Ht);let vt=m.getBoundingClientRect();be.style.position="fixed",be.style.left=`${vt.left+vt.width/2}px`,be.style.top=`${vt.top-8}px`,be.style.transform="translate(-50%, -100%)",document.body.appendChild(be)},Tt=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};x.addEventListener("mouseenter",yt),x.addEventListener("mouseleave",Tt),m.addEventListener("focus",yt),m.addEventListener("blur",Tt),x._cleanupTooltip=()=>{Tt(),x&&(x.removeEventListener("mouseenter",yt),x.removeEventListener("mouseleave",Tt)),m&&(m.removeEventListener("focus",yt),m.removeEventListener("blur",Tt))}}F==="inline"&&t.appendChild(x)}let I=p("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":q&&F==="inline"?"":"tvw-ml-auto"),S=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");S.style.height=i,S.style.width=i,S.type="button";let Y=(lt=o.closeButtonTooltipText)!=null?lt:"Close chat",P=(Ke=o.closeButtonShowTooltip)!=null?Ke:!0;S.setAttribute("aria-label",Y),S.style.display=r?"":"none";let V=(We=o.closeButtonIconName)!=null?We:"x",Q=(_e=o.closeButtonIconText)!=null?_e:"\xD7",W=ve(V,"20px",o.closeButtonColor||"",2);if(W?S.appendChild(W):S.textContent=Q,o.closeButtonColor?(S.style.color=o.closeButtonColor,S.classList.remove("tvw-text-cw-muted")):(S.style.color="",S.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(S.style.backgroundColor=o.closeButtonBackgroundColor,S.classList.remove("hover:tvw-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let J=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";S.style.border=`${J} solid ${Se}`,S.classList.remove("tvw-border-none")}else S.style.border="",S.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(S.style.borderRadius=o.closeButtonBorderRadius,S.classList.remove("tvw-rounded-full")):(S.style.borderRadius="",S.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(S.style.paddingLeft=o.closeButtonPaddingX,S.style.paddingRight=o.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),o.closeButtonPaddingY?(S.style.paddingTop=o.closeButtonPaddingY,S.style.paddingBottom=o.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom=""),I.appendChild(S),P&&Y){let J=null,Se=()=>{if(J)return;J=p("div","tvw-clear-chat-tooltip"),J.textContent=Y;let Ue=p("div");Ue.className="tvw-clear-chat-tooltip-arrow",J.appendChild(Ue);let nt=S.getBoundingClientRect();J.style.position="fixed",J.style.left=`${nt.left+nt.width/2}px`,J.style.top=`${nt.top-8}px`,J.style.transform="translate(-50%, -100%)",document.body.appendChild(J)},ke=()=>{J&&J.parentNode&&(J.parentNode.removeChild(J),J=null)};I.addEventListener("mouseenter",Se),I.addEventListener("mouseleave",ke),S.addEventListener("focus",Se),S.addEventListener("blur",ke),I._cleanupTooltip=()=>{ke(),I.removeEventListener("mouseenter",Se),I.removeEventListener("mouseleave",ke),S.removeEventListener("focus",Se),S.removeEventListener("blur",ke)}}return l!=="top-right"&&t.appendChild(I),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:b,closeButton:S,closeButtonWrapper:I,clearChatButton:m,clearChatButtonWrapper:x}},Zt=(n,e,r)=>{var i,l,c,g;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(l=t.closeButtonPlacement)!=null?l:"inline",s=(g=(c=t.clearChat)==null?void 0:c.placement)!=null?g:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var qn=n=>Ft({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Un=n=>{var w,q,F,m;let{config:e,showClose:r=!0,onClose:t}=n,o=(w=e==null?void 0:e.launcher)!=null?w:{},s=p("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=p("span","tvw-text-base tvw-font-semibold");i.textContent=(q=o.title)!=null?q:"Chat Assistant",s.appendChild(i);let l=(F=o.closeButtonSize)!=null?F:"32px",c=p("div",""),g=p("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");g.style.height=l,g.style.width=l,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=r?"":"none";let d=(m=o.closeButtonIconName)!=null?m:"x",A=ve(d,"20px",o.closeButtonColor||"",2);A?g.appendChild(A):g.textContent="\xD7",t&&g.addEventListener("click",t),c.appendChild(g),s.appendChild(c);let f=p("div");f.style.display="none";let b=p("span");return b.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:b,closeButton:g,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}},zn=n=>{var S,Y,P,V,Q,W,le,G;let{config:e,showClose:r=!0,onClose:t,onClearChat:o}=n,s=(S=e==null?void 0:e.launcher)!=null?S:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=p("div","tvw-flex tvw-items-center tvw-gap-3"),c=(Y=s.headerIconSize)!=null?Y:"56px",g=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");g.style.height=c,g.style.width=c;let d=s.headerIconName;if(d){let U=parseFloat(c)||24,z=ve(d,U*.5,"#ffffff",2);z?g.replaceChildren(z):g.textContent=(P=s.agentIconText)!=null?P:"\u{1F4AC}"}else if(s.iconUrl){let U=p("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=c,U.style.width=c,g.replaceChildren(U)}else g.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let A=p("div","tvw-flex tvw-flex-col tvw-flex-1"),f=p("span","tvw-text-lg tvw-font-semibold");f.textContent=(Q=s.title)!=null?Q:"Chat Assistant";let b=p("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(W=s.subtitle)!=null?W:"Here to help you get answers fast",A.append(f,b),l.append(g,A);let w=(le=s.closeButtonSize)!=null?le:"32px",q=p("div",""),F=p("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=w,F.style.width=w,F.type="button",F.setAttribute("aria-label","Close chat"),F.style.display=r?"":"none";let m=(G=s.closeButtonIconName)!=null?G:"x",x=ve(m,"20px",s.closeButtonColor||"",2);x?F.appendChild(x):F.textContent="\xD7",t&&F.addEventListener("click",t),q.appendChild(F),l.appendChild(q),i.appendChild(l);let I=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return I.textContent="Online and ready to help",i.appendChild(I),{header:i,iconHolder:g,headerTitle:f,headerSubtitle:b,closeButton:F,closeButtonWrapper:q,clearChatButton:null,clearChatButtonWrapper:null}},Mn={default:qn,minimal:Un,expanded:zn},Yn=n=>{var e;return(e=Mn[n])!=null?e:Mn.default},Ln=(n,e,r)=>{var i,l,c;if(e!=null&&e.render){let g=e.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),d=p("div");d.style.display="none";let A=p("span"),f=p("span"),b=p("button");b.style.display="none";let w=p("div");return w.style.display="none",{header:g,iconHolder:d,headerTitle:A,headerSubtitle:f,closeButton:b,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=Yn(t)({config:n,showClose:(c=(l=e==null?void 0:e.showCloseButton)!=null?l:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Qo=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'}},Qt=n=>{var Z,$,Ne,Ye,Qe,xt,Ct,D,me,mt,ft,Je,et,M,Be,it,at,Et,wt,$e,tt,qe,j,lt,Ke;let{config:e}=n,r=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=((Z=e==null?void 0:e.voiceRecognition)==null?void 0:Z.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),c=p("form",`tvw-widget-composer tvw-flex tvw-items-end ${o&&s?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);c.style.outline="none";let g=p("textarea");g.placeholder=(Ne=($=e==null?void 0:e.copy)==null?void 0:$.inputPlaceholder)!=null?Ne:"Type your message\u2026",g.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",g.rows=1;let d=(Qe=(Ye=e==null?void 0:e.theme)==null?void 0:Ye.inputFontFamily)!=null?Qe:"sans-serif",A=(Ct=(xt=e==null?void 0:e.theme)==null?void 0:xt.inputFontWeight)!=null?Ct:"400";g.style.fontFamily=Qo(d),g.style.fontWeight=A,g.style.border="none",g.style.outline="none",g.style.borderWidth="0",g.style.borderStyle="none",g.style.borderColor="transparent",g.addEventListener("focus",()=>{g.style.border="none",g.style.outline="none",g.style.borderWidth="0",g.style.borderStyle="none",g.style.borderColor="transparent",g.style.boxShadow="none"}),g.addEventListener("blur",()=>{g.style.border="none",g.style.outline="none"});let f=(D=e==null?void 0:e.sendButton)!=null?D:{},b=(me=f.useIcon)!=null?me:!1,w=(mt=f.iconText)!=null?mt:"\u2191",q=f.iconName,F=(ft=f.tooltipText)!=null?ft:"Send message",m=(Je=f.showTooltip)!=null?Je:!1,x=(et=f.size)!=null?et:"40px",I=f.backgroundColor,S=f.textColor,Y=p("div","tvw-send-button-wrapper"),P=p("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(P.type="submit",b){if(P.style.width=x,P.style.height=x,P.style.minWidth=x,P.style.minHeight=x,P.style.fontSize="18px",P.style.lineHeight="1",P.innerHTML="",q){let We=parseFloat(x)||24,_e=S&&typeof S=="string"&&S.trim()?S.trim():"currentColor",J=ve(q,We,_e,2);J?(P.appendChild(J),P.style.color=_e):(P.textContent=w,S?P.style.color=S:P.classList.add("tvw-text-white"))}else P.textContent=w,S?P.style.color=S:P.classList.add("tvw-text-white");I?P.style.backgroundColor=I:P.classList.add("tvw-bg-cw-primary")}else P.textContent=(Be=(M=e==null?void 0:e.copy)==null?void 0:M.sendButtonLabel)!=null?Be:"Send",S?P.style.color=S:P.classList.add("tvw-text-white");if(f.borderWidth&&(P.style.borderWidth=f.borderWidth,P.style.borderStyle="solid"),f.borderColor&&(P.style.borderColor=f.borderColor),f.paddingX?(P.style.paddingLeft=f.paddingX,P.style.paddingRight=f.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),f.paddingY?(P.style.paddingTop=f.paddingY,P.style.paddingBottom=f.paddingY):(P.style.paddingTop="",P.style.paddingBottom=""),m&&F){let We=p("div","tvw-send-button-tooltip");We.textContent=F,Y.appendChild(We)}Y.appendChild(P);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},Q=V.enabled===!0,W=null,le=null,G=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Q&&G){le=p("div","tvw-send-button-wrapper"),W=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),W.type="button",W.setAttribute("aria-label","Start voice recognition");let We=(at=V.iconName)!=null?at:"mic",_e=(Et=V.iconSize)!=null?Et:x,J=parseFloat(_e)||24,Se=(wt=V.backgroundColor)!=null?wt:I,ke=($e=V.iconColor)!=null?$e:S;W.style.width=_e,W.style.height=_e,W.style.minWidth=_e,W.style.minHeight=_e,W.style.fontSize="18px",W.style.lineHeight="1";let Ue=ke||"currentColor",nt=ve(We,J,Ue,1.5);nt?(W.appendChild(nt),W.style.color=Ue):(W.textContent="\u{1F3A4}",W.style.color=Ue),Se?W.style.backgroundColor=Se:W.classList.add("tvw-bg-cw-primary"),ke?W.style.color=ke:!ke&&!S&&W.classList.add("tvw-text-white"),V.borderWidth&&(W.style.borderWidth=V.borderWidth,W.style.borderStyle="solid"),V.borderColor&&(W.style.borderColor=V.borderColor),V.paddingX&&(W.style.paddingLeft=V.paddingX,W.style.paddingRight=V.paddingX),V.paddingY&&(W.style.paddingTop=V.paddingY,W.style.paddingBottom=V.paddingY),le.appendChild(W);let St=(tt=V.tooltipText)!=null?tt:"Start voice recognition";if(((qe=V.showTooltip)!=null?qe:!1)&&St){let gt=p("div","tvw-send-button-tooltip");gt.textContent=St,le.appendChild(gt)}}c.addEventListener("click",We=>{We.target!==P&&We.target!==Y&&We.target!==W&&We.target!==le&&g.focus()}),c.append(g),le&&c.append(le),c.append(Y);let U=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),z=(j=e==null?void 0:e.statusIndicator)!=null?j:{},ne=(lt=z.visible)!=null?lt:!0;return U.style.display=ne?"":"none",U.textContent=(Ke=z.idleText)!=null?Ke:"Online",r.append(t,c,U),{footer:r,suggestions:t,composerForm:c,textarea:g,sendButton:P,sendButtonWrapper:Y,micButton:W,micButtonWrapper:le,statusText:U}};var Co=n=>{var c,g,d,A,f,b,w;if(!((g=(c=n==null?void 0:n.launcher)==null?void 0:c.enabled)!=null?g:!0)){let q=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),F=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),m=(A=(d=n==null?void 0:n.launcher)==null?void 0:d.width)!=null?A:"100%";return q.style.width=m,F.style.width="100%",q.appendChild(F),{wrapper:q,panel:F}}let r=(f=n==null?void 0:n.launcher)!=null?f:{},t=r.position&&bt[r.position]?bt[r.position]:bt["bottom-right"],o=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(w=(b=n==null?void 0:n.launcher)==null?void 0:b.width)!=null?w:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,o.appendChild(s),{wrapper:o,panel:s}},So=(n,e=!0)=>{var A,f,b,w,q;let r=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(A=n==null?void 0:n.layout)==null?void 0:A.header,o=t?Ln(n,t,{showClose:e}):Ft({config:n,showClose:e}),s=p("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=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}";let c=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(q=(w=n==null?void 0:n.copy)==null?void 0:w.welcomeSubtitle)!=null?q:"Ask anything about your account or products.",i.append(l,c);let g=p("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,g);let d=Qt({config:n});return Zt(r,o,n),r.append(s,d.footer),{container:r,body:s,messagesWrapper:g,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:l,introSubtitle:c,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:d.footer}};var un=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(r),n.appendChild(t),n.appendChild(o),n},er=(n,e)=>{let r=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=p("img");o.src=t,o.alt=e==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Ao=(n,e)=>{let r=p("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?r.textContent=e.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},tr=(n,e="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},en=(n,e,r)=>{var F,m,x,I,S;let t=r!=null?r:{},o=(F=t.layout)!=null?F:"bubble",s=t.avatar,i=t.timestamp,l=(m=s==null?void 0:s.show)!=null?m:!1,c=(x=i==null?void 0:i.show)!=null?x:!1,g=(I=s==null?void 0:s.position)!=null?I:"left",d=(S=i==null?void 0:i.position)!=null?S:"below",A=tr(n.role,o),f=p("div",A.join(" ")),b=document.createElement("div");if(b.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),c&&d==="inline"&&n.createdAt){let Y=Ao(n,i);Y.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(Y)}if(f.appendChild(b),c&&d==="below"&&n.createdAt){let Y=Ao(n,i);Y.classList.add("tvw-mt-1"),f.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=un();f.appendChild(Y)}if(!l||n.role==="system")return f;let w=p("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),q=er(s,n.role);return g==="right"||g==="left"&&n.role==="user"?w.append(f,q):w.append(q,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),w},To=(n,e,r)=>{let t=r!=null?r:{};return n.role==="user"&&t.renderUserMessage?t.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&t.renderAssistantMessage?t.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):en(n,e,r)};var Jn=new Set,Kn=n=>{let e=n.reasoning,r=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return r;let t=Jn.has(n.id),o=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=p("span","tvw-text-xs tvw-text-cw-primary");l.textContent=vo(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let c=p("div","tvw-flex tvw-items-center"),d=ve(t?"chevron-up":"chevron-down",16,"currentColor",2);d?c.appendChild(d):c.textContent=t?"Hide":"Show";let A=p("div","tvw-flex tvw-items-center tvw-ml-auto");A.append(c),o.append(s,A);let f=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let b=e.chunks.join(""),w=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");w.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(w);let q=()=>{o.setAttribute("aria-expanded",t?"true":"false"),c.innerHTML="";let x=ve(t?"chevron-up":"chevron-down",16,"currentColor",2);x?c.appendChild(x):c.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},F=()=>{t=!t,t?Jn.add(n.id):Jn.delete(n.id),q()};return o.addEventListener("pointerdown",m=>{m.preventDefault(),F()}),o.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),F())}),q(),r.append(o,f),r};var Xn=new Set,Vn=(n,e)=>{var F;let r=n.toolCall,t=(F=e==null?void 0:e.toolCall)!=null?F:{},o=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=Xn.has(n.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=p("div","tvw-flex tvw-flex-col tvw-text-left"),c=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(c.style.color=t.headerTextColor),c.textContent=bo(r),l.appendChild(c);let g=p("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",A=ve(s?"chevron-up":"chevron-down",16,d,2);A?g.appendChild(A):g.textContent=s?"Hide":"Show";let f=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(g),i.append(l,f);let b=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=s?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),r.name){let m=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?m.style.color=t.contentTextColor:t.headerTextColor&&(m.style.color=t.headerTextColor),m.textContent=r.name,b.appendChild(m)}if(r.args!==void 0){let m=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Arguments";let I=p("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=jn(r.args),m.append(x,I),b.appendChild(m)}if(r.chunks&&r.chunks.length){let m=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Activity";let I=p("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=r.chunks.join(`
16
- `),m.append(x,I),b.appendChild(m)}if(r.status==="complete"&&r.result!==void 0){let m=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Result";let I=p("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=jn(r.result),m.append(x,I),b.appendChild(m)}if(r.status==="complete"&&typeof r.duration=="number"){let m=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${r.duration}ms`,b.appendChild(m)}let w=()=>{i.setAttribute("aria-expanded",s?"true":"false"),g.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",x=ve(s?"chevron-up":"chevron-down",16,m,2);x?g.appendChild(x):g.textContent=s?"Hide":"Show",b.style.display=s?"":"none"},q=()=>{s=!s,s?Xn.add(n.id):Xn.delete(n.id),w()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),q()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),q())}),w(),o.append(i,b),o};var Eo=n=>{let e=[];return{buttons:e,render:(t,o,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(b=>b.role==="user"))return;let d=document.createDocumentFragment(),A=o?o.isStreaming():!1,f=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let w=p("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");w.type="button",w.textContent=b,w.disabled=A,l!=null&&l.fontFamily&&(w.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(w.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(w.style.paddingLeft=l.paddingX,w.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(w.style.paddingTop=l.paddingY,w.style.paddingBottom=l.paddingY),w.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(b))}),d.appendChild(w),e.push(w)}),n.appendChild(d)}}};var Wo={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Gn=(n,e,r,t)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,q,F;if(s.dataset.enhanced==="true")return;let i=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let l=(q=Wo[i])!=null?q:Wo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let c=p("div","tvw-space-y-1"),g=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(g.textContent=l.title,c.appendChild(g),l.description){let m=p("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,c.appendChild(m)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var P,V;let x=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");x.htmlFor=`${e.id}-${i}-${m.name}`;let I=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=m.label,x.appendChild(I);let S=(P=m.type)!=null?P:"text",Y;S==="textarea"?(Y=document.createElement("textarea"),Y.rows=3):(Y=document.createElement("input"),Y.type=S),Y.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",Y.id=`${e.id}-${i}-${m.name}`,Y.name=m.name,Y.placeholder=(V=m.placeholder)!=null?V:"",m.required&&(Y.required=!0),x.appendChild(Y),d.appendChild(x)});let A=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(F=l.submitLabel)!=null?F:"Submit",A.appendChild(f),A.appendChild(b),d.appendChild(A),s.replaceChildren(c,d),d.addEventListener("submit",async m=>{var Y,P;m.preventDefault();let x=(Y=r.formEndpoint)!=null?Y:"/form",I=new FormData(d),S={};I.forEach((V,Q)=>{S[Q]=V}),S.type=i,b.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let Q=await V.json();f.textContent=(P=Q.message)!=null?P:"Thanks! We'll be in touch soon.",Q.success&&Q.nextPrompt&&await t.sendMessage(String(Q.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var Zn=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var t;let r=this.plugins.get(e);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let t=new Set(e.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,c;return((l=i.priority)!=null?l:0)-((c=s.priority)!=null?c:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},gn=new Zn;var Le={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,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},debug:!1};function Bn(n){var e,r,t,o,s,i,l,c,g,d,A,f,b,w,q,F,m,x,I;return n?{...Le,...n,theme:{...Le.theme,...n.theme},launcher:{...Le.launcher,...n.launcher,clearChat:{...(e=Le.launcher)==null?void 0:e.clearChat,...(r=n.launcher)==null?void 0:r.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:(t=n.suggestionChips)!=null?t:Le.suggestionChips,suggestionChipsConfig:{...Le.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Le.layout,...n.layout,header:{...(o=Le.layout)==null?void 0:o.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:{...(g=(c=Le.layout)==null?void 0:c.messages)==null?void 0:g.avatar,...(A=(d=n.layout)==null?void 0:d.messages)==null?void 0:A.avatar},timestamp:{...(b=(f=Le.layout)==null?void 0:f.messages)==null?void 0:b.timestamp,...(q=(w=n.layout)==null?void 0:w.messages)==null?void 0:q.timestamp}},slots:{...(F=Le.layout)==null?void 0:F.slots,...(m=n.layout)==null?void 0:m.slots}},markdown:{...Le.markdown,...n.markdown,options:{...(x=Le.markdown)==null?void 0:x.options,...(I=n.markdown)==null?void 0:I.options}}}:Le}var Mo=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:e,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(l=>{try{l(s)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var nr=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},sr=n=>{let e=n.trim(),r=e.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(r,o+1)}return null},hn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=nr(n),r=sr(e);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},Qn=n=>typeof n=="string"?n:n==null?"":String(n),Jt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Qn(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,t=Qn(r.element);if(t&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Qn(r.text)}}},Lo=n=>Array.isArray(n)?n.map(e=>String(e)):[],mn=n=>{let e=new Set(Lo(n.getMetadata().processedActionMessageIds)),r=()=>{e=new Set(Lo(n.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((g,d)=>g||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let c={action:l,message:s.message};n.emit("action:detected",c);for(let g of n.handlers)if(g)try{let d=g(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let A=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:A}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:r}};var or=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},rr=n=>n.map(e=>({...e,streaming:!1})),kn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?or(r.getItem(n)):null},save:r=>{let t=e();if(t)try{let o={...r,messages:r.messages?rr(r.messages):void 0};t.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var es=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,t])=>{this.register(r,t)})}},tn=new es;var nn=require("partial-json");function ir(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function ar(n,e){if(!ir(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:e}}function Hn(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n;try{let o=(0,nn.parse)(r,nn.STR|nn.OBJ),s=ar(o,r);s&&(n=s)}catch{}return e=r.length,n},reset:()=>{n=null,e=0}}}function Bo(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Rn(n,e){let{config:r,message:t,onPropsUpdate:o}=e,s=tn.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:l=>{o&&o(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function ko(){let n=Hn();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function In(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function $n(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var sn="vanilla-agent-chat-history",lr=30*1e3,ts=n=>!n||typeof n!="object"?{}:{...n},Ho=n=>n.map(e=>({...e,streaming:!1})),Ro=(n,e)=>{let r=n!=null&&n.markdown?cn(n.markdown):null;return t=>{var i,l,c;let o=(i=t.text)!=null?i:"",s=(l=t.message.rawContent)!=null?l:null;if(e){let g=e.process({text:o,raw:s!=null?s:o,message:t.message,streaming:t.streaming});g!==null&&(o=g.text,g.persist||(t.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...t,text:o,raw:(c=s!=null?s:t.text)!=null?c:""}):r?r(o):xn(o)}},Pn=(n,e,r)=>{var ae,pe,Re,ue,Fe,rt,ht,os,rs,is,as,ls,ds,cs;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Bn(e),o=gn.getForInstance(t.plugins);t.components&&tn.registerAll(t.components);let s=Mo(),i=(ae=t.storageAdapter)!=null?ae:kn(),l={},c=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")c=a;else if(a){let u=a;u.metadata&&(l=ts(u.metadata)),(pe=u.messages)!=null&&pe.length&&(t={...t,initialMessages:u.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let g=()=>l,d=a=>{var T;l=(T=a({...l}))!=null?T:{},Ht()},A=t.actionParsers&&t.actionParsers.length?t.actionParsers:[hn],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Jt.message,Jt.messageAndClick],b=mn({parsers:A,handlers:f,getMetadata:g,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let w=(ue=(Re=t.launcher)==null?void 0:Re.enabled)!=null?ue:!0,q=(rt=(Fe=t.launcher)==null?void 0:Fe.autoExpand)!=null?rt:!1,F=q,m=w,x=w?q:!0,I=Ro(t,b),S=(os=(ht=t.features)==null?void 0:ht.showReasoning)!=null?os:!0,Y=(is=(rs=t.features)==null?void 0:rs.showToolCalls)!=null?is:!0,P=(as=t.statusIndicator)!=null?as:{},V=a=>{var u,T,O,R;return a==="idle"?(u=P.idleText)!=null?u:ze.idle:a==="connecting"?(T=P.connectingText)!=null?T:ze.connecting:a==="connected"?(O=P.connectedText)!=null?O:ze.connected:a==="error"?(R=P.errorText)!=null?R:ze.error:ze[a]},{wrapper:Q,panel:W}=Co(t),le=So(t,w),{container:G,body:U,messagesWrapper:z,suggestions:ne,textarea:Z,sendButton:$,sendButtonWrapper:Ne,composerForm:Ye,statusText:Qe,introTitle:xt,introSubtitle:Ct,closeButton:D,iconHolder:me,headerTitle:mt,headerSubtitle:ft,header:Je,footer:et}=le,M=le.micButton,Be=le.micButtonWrapper,it=o.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let u=Ft({config:t,showClose:w});return Zt(G,u,t),u.header},onClose:()=>st(!1,"user")});if(a){let u=G.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(a),Je=a)}}let at=o.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>Qt({config:t}).footer,onSubmit:u=>{j&&!j.isStreaming()&&j.sendMessage(u)},disabled:!1});a&&(et.replaceWith(a),et=a)}(()=>{var O,R;let a=(R=(O=t.layout)==null?void 0:O.slots)!=null?R:{},u=se=>{switch(se){case"body-top":return G.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return z;case"footer-top":return ne;case"composer":return Ye;case"footer-bottom":return Qe;default:return null}},T=(se,H)=>{var v;switch(se){case"header-left":case"header-center":case"header-right":if(se==="header-left")Je.insertBefore(H,Je.firstChild);else if(se==="header-right")Je.appendChild(H);else{let N=Je.querySelector(".tvw-flex-col");N?(v=N.parentNode)==null||v.insertBefore(H,N.nextSibling):Je.appendChild(H)}break;case"body-top":let X=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");X?X.replaceWith(H):U.insertBefore(H,U.firstChild);break;case"body-bottom":U.appendChild(H);break;case"footer-top":ne.replaceWith(H);break;case"footer-bottom":Qe.replaceWith(H);break;default:break}};for(let[se,H]of Object.entries(a))if(H)try{let v=H({config:t,defaultContent:()=>u(se)});v&&T(se,v)}catch(v){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${se}":`,v)}})(),W.appendChild(G),n.appendChild(Q);let wt=()=>{var re,Ie,dt,ie,ct,Rt,It,Mt,qt,$t,Ut,pt,Pt,Ot,vn,ln;let a=(Ie=(re=t.launcher)==null?void 0:re.sidebarMode)!=null?Ie:!1,u=a||((ie=(dt=t.launcher)==null?void 0:dt.fullHeight)!=null?ie:!1),T=(ct=t.theme)!=null?ct:{},O=(It=(Rt=t.launcher)==null?void 0:Rt.position)!=null?It:"bottom-left",R=O==="bottom-left"||O==="top-left",se=a?"none":"1px solid var(--tvw-cw-border)",H=a?R?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",v=a?"0":"16px",X=(Mt=T.panelBorder)!=null?Mt:se,N=(qt=T.panelShadow)!=null?qt:H,B=($t=T.panelBorderRadius)!=null?$t:v;n.style.cssText="",Q.style.cssText="",W.style.cssText="",G.style.cssText="",U.style.cssText="",et.style.cssText="";let _=(pt=(Ut=t==null?void 0:t.launcher)==null?void 0:Ut.width)!=null?pt:t==null?void 0:t.launcherWidth,Me=_!=null?_:"min(400px, calc(100vw - 24px))";a||(W.style.width=Me,W.style.maxWidth=Me),W.style.boxShadow=N,W.style.borderRadius=B,G.style.border=X,G.style.borderRadius=B;let ge=((Pt=t.launcher)==null?void 0:Pt.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",Q.style.display="flex",Q.style.flexDirection="column",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.maxHeight="100%",Q.style.height="100%",ge&&(Q.style.overflow="hidden"),W.style.display="flex",W.style.flexDirection="column",W.style.flex="1 1 0%",W.style.minHeight="0",W.style.maxHeight="100%",W.style.height="100%",W.style.overflow="hidden",G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",et.style.flexShrink="0"),Q.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!a&&!ge&&((Ot=bt[O])!=null?Ot:bt["bottom-right"]).split(" ").forEach(Xt=>Q.classList.add(Xt)),a){let zt=(ln=(vn=t.launcher)==null?void 0:vn.sidebarWidth)!=null?ln:"420px";Q.style.cssText=`
15
+ `,s.addEventListener("click",e);let t=o=>{var h,b,W,v,D,x,S,X,B,_,Z,j;let a=(h=o.launcher)!=null?h:{},l=s.querySelector("[data-role='launcher-title']");l&&(l.textContent=(b=a.title)!=null?b:"Chat Assistant");let p=s.querySelector("[data-role='launcher-subtitle']");p&&(p.textContent=(W=a.subtitle)!=null?W:"Get answers fast");let c=s.querySelector(".tvw-flex-col");c&&(a.textHidden?c.style.display="none":c.style.display="");let f=s.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let K=(v=a.agentIconSize)!=null?v:"40px";if(f.style.height=K,f.style.width=K,f.innerHTML="",a.agentIconName){let Q=parseFloat(K)||24,ne=ce(a.agentIconName,Q*.6,"#ffffff",2);ne?(f.appendChild(ne),f.style.display=""):(f.textContent=(D=a.agentIconText)!=null?D:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",f.style.display="")}let w=s.querySelector("[data-role='launcher-image']");if(w){let K=(S=a.agentIconSize)!=null?S:"40px";w.style.height=K,w.style.width=K,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let d=s.querySelector("[data-role='launcher-call-to-action-icon']");if(d){let K=(X=a.callToActionIconSize)!=null?X:"32px";d.style.height=K,d.style.width=K,a.callToActionIconBackgroundColor?(d.style.backgroundColor=a.callToActionIconBackgroundColor,d.classList.remove("tvw-bg-cw-primary")):(d.style.backgroundColor="",d.classList.add("tvw-bg-cw-primary"));let Q=0;if(a.callToActionIconPadding?(d.style.boxSizing="border-box",d.style.padding=a.callToActionIconPadding,Q=(parseFloat(a.callToActionIconPadding)||0)*2):(d.style.boxSizing="",d.style.padding=""),a.callToActionIconHidden)d.style.display="none";else if(d.style.display="",d.innerHTML="",a.callToActionIconName){let ne=parseFloat(K)||24,re=Math.max(ne-Q,8),q=ce(a.callToActionIconName,re,"currentColor",2);q?d.appendChild(q):d.textContent=(B=a.callToActionIconText)!=null?B:"\u2197"}else d.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}let C=a.position&&vt[a.position]?vt[a.position]:vt["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";s.className=`${g} ${C}`;let U="1px solid #e5e7eb",$="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";s.style.border=(Z=a.border)!=null?Z:U,s.style.boxShadow=(j=a.shadow)!=null?j:$},r=()=>{s.removeEventListener("click",e),s.remove()};return n&&t(n),{element:s,update:t,destroy:r}};var Ot=n=>{var _,Z,j,K,Q,ne,re,q,qe,Ve,nt,bt,Ct,J,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,$e,ot,Ue,I,dt,Se,Oe;let{config:e,showClose:s=!0}=n,t=m("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=(_=e==null?void 0:e.launcher)!=null?_:{},o=(Z=r.headerIconSize)!=null?Z:"48px",a=(j=r.closeButtonSize)!=null?j:"32px",l=(K=r.closeButtonPlacement)!=null?K:"inline",p=(Q=r.headerIconHidden)!=null?Q:!1,c=r.headerIconName,f=m("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=o,f.style.width=o,!p)if(c){let te=parseFloat(o)||24,Ae=ce(c,te*.6,"#ffffff",2);Ae?f.replaceChildren(Ae):f.textContent=(re=(ne=e==null?void 0:e.launcher)==null?void 0:ne.agentIconText)!=null?re:"\u{1F4AC}"}else if((q=e==null?void 0:e.launcher)!=null&&q.iconUrl){let te=m("img");te.src=e.launcher.iconUrl,te.alt="",te.className="tvw-rounded-xl tvw-object-cover",te.style.height=o,te.style.width=o,f.replaceChildren(te)}else f.textContent=(Ve=(qe=e==null?void 0:e.launcher)==null?void 0:qe.agentIconText)!=null?Ve:"\u{1F4AC}";let w=m("div","tvw-flex tvw-flex-col"),d=m("span","tvw-text-base tvw-font-semibold");d.textContent=(bt=(nt=e==null?void 0:e.launcher)==null?void 0:nt.title)!=null?bt:"Chat Assistant";let C=m("span","tvw-text-xs tvw-text-cw-muted");C.textContent=(J=(Ct=e==null?void 0:e.launcher)==null?void 0:Ct.subtitle)!=null?J:"Here to help you get answers fast",w.append(d,C),p?t.append(w):t.append(f,w);let g=(fe=r.clearChat)!=null?fe:{},U=(mt=g.enabled)!=null?mt:!0,$=(ft=g.placement)!=null?ft:"inline",h=null,b=null;if(U){let te=(Ge=g.size)!=null?Ge:"32px",Ae=(st=g.iconName)!=null?st:"refresh-cw",Te=(H=g.iconColor)!=null?H:"",ze=(He=g.backgroundColor)!=null?He:"",Je=(at=g.borderWidth)!=null?at:"",xt=(lt=g.borderColor)!=null?lt:"",Bt=(Tt=g.borderRadius)!=null?Tt:"",yt=(wt=g.paddingX)!=null?wt:"",Et=($e=g.paddingY)!=null?$e:"",St=(ot=g.tooltipText)!=null?ot:"Clear chat",ye=(Ue=g.showTooltip)!=null?Ue:!0;b=m("div",$==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),$==="top-right"&&(b.style.right="48px"),h=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),h.style.height=te,h.style.width=te,h.type="button",h.setAttribute("aria-label",St);let Ht=ce(Ae,"20px",Te||"",2);if(Ht&&h.appendChild(Ht),Te&&(h.style.color=Te,h.classList.remove("tvw-text-cw-muted")),ze&&(h.style.backgroundColor=ze,h.classList.remove("hover:tvw-bg-gray-100")),Je||xt){let Le=Je||"0px",Ye=xt||"transparent";h.style.border=`${Le} solid ${Ye}`,h.classList.remove("tvw-border-none")}if(Bt&&(h.style.borderRadius=Bt,h.classList.remove("tvw-rounded-full")),yt?(h.style.paddingLeft=yt,h.style.paddingRight=yt):(h.style.paddingLeft="",h.style.paddingRight=""),Et?(h.style.paddingTop=Et,h.style.paddingBottom=Et):(h.style.paddingTop="",h.style.paddingBottom=""),b.appendChild(h),ye&&St&&h&&b){let Le=null,Ye=()=>{if(Le||!h)return;Le=m("div","tvw-clear-chat-tooltip"),Le.textContent=St;let Dt=m("div");Dt.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(Dt);let Mt=h.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Mt.left+Mt.width/2}px`,Le.style.top=`${Mt.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},At=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};b.addEventListener("mouseenter",Ye),b.addEventListener("mouseleave",At),h.addEventListener("focus",Ye),h.addEventListener("blur",At),b._cleanupTooltip=()=>{At(),b&&(b.removeEventListener("mouseenter",Ye),b.removeEventListener("mouseleave",At)),h&&(h.removeEventListener("focus",Ye),h.removeEventListener("blur",At))}}$==="inline"&&t.appendChild(b)}let W=m("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":U&&$==="inline"?"":"tvw-ml-auto"),v=m("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");v.style.height=a,v.style.width=a,v.type="button";let D=(I=r.closeButtonTooltipText)!=null?I:"Close chat",x=(dt=r.closeButtonShowTooltip)!=null?dt:!0;v.setAttribute("aria-label",D),v.style.display=s?"":"none";let S=(Se=r.closeButtonIconName)!=null?Se:"x",X=(Oe=r.closeButtonIconText)!=null?Oe:"\xD7",B=ce(S,"20px",r.closeButtonColor||"",2);if(B?v.appendChild(B):v.textContent=X,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let te=r.closeButtonBorderWidth||"0px",Ae=r.closeButtonBorderColor||"transparent";v.style.border=`${te} solid ${Ae}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),W.appendChild(v),x&&D){let te=null,Ae=()=>{if(te)return;te=m("div","tvw-clear-chat-tooltip"),te.textContent=D;let ze=m("div");ze.className="tvw-clear-chat-tooltip-arrow",te.appendChild(ze);let Je=v.getBoundingClientRect();te.style.position="fixed",te.style.left=`${Je.left+Je.width/2}px`,te.style.top=`${Je.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Te=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};W.addEventListener("mouseenter",Ae),W.addEventListener("mouseleave",Te),v.addEventListener("focus",Ae),v.addEventListener("blur",Te),W._cleanupTooltip=()=>{Te(),W.removeEventListener("mouseenter",Ae),W.removeEventListener("mouseleave",Te),v.removeEventListener("focus",Ae),v.removeEventListener("blur",Te)}}return l!=="top-right"&&t.appendChild(W),{header:t,iconHolder:f,headerTitle:d,headerSubtitle:C,closeButton:v,closeButtonWrapper:W,clearChatButton:h,clearChatButtonWrapper:b}},Qt=(n,e,s)=>{var a,l,p,c;let t=(a=s==null?void 0:s.launcher)!=null?a:{},r=(l=t.closeButtonPlacement)!=null?l:"inline",o=(c=(p=t.clearChat)==null?void 0:p.placement)!=null?c:"inline";n.appendChild(e.header),r==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&o==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var Kn=n=>Ot({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Xn=n=>{var g,U,$,h;let{config:e,showClose:s=!0,onClose:t}=n,r=(g=e==null?void 0:e.launcher)!=null?g:{},o=m("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),a=m("span","tvw-text-base tvw-font-semibold");a.textContent=(U=r.title)!=null?U:"Chat Assistant",o.appendChild(a);let l=($=r.closeButtonSize)!=null?$:"32px",p=m("div",""),c=m("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=s?"":"none";let f=(h=r.closeButtonIconName)!=null?h:"x",w=ce(f,"20px",r.closeButtonColor||"",2);w?c.appendChild(w):c.textContent="\xD7",t&&c.addEventListener("click",t),p.appendChild(c),o.appendChild(p);let d=m("div");d.style.display="none";let C=m("span");return C.style.display="none",{header:o,iconHolder:d,headerTitle:a,headerSubtitle:C,closeButton:c,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},Vn=n=>{var v,D,x,S,X,B,_,Z;let{config:e,showClose:s=!0,onClose:t,onClearChat:r}=n,o=(v=e==null?void 0:e.launcher)!=null?v:{},a=m("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=m("div","tvw-flex tvw-items-center tvw-gap-3"),p=(D=o.headerIconSize)!=null?D:"56px",c=m("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=p,c.style.width=p;let f=o.headerIconName;if(f){let j=parseFloat(p)||24,K=ce(f,j*.5,"#ffffff",2);K?c.replaceChildren(K):c.textContent=(x=o.agentIconText)!=null?x:"\u{1F4AC}"}else if(o.iconUrl){let j=m("img");j.src=o.iconUrl,j.alt="",j.className="tvw-rounded-xl tvw-object-cover",j.style.height=p,j.style.width=p,c.replaceChildren(j)}else c.textContent=(S=o.agentIconText)!=null?S:"\u{1F4AC}";let w=m("div","tvw-flex tvw-flex-col tvw-flex-1"),d=m("span","tvw-text-lg tvw-font-semibold");d.textContent=(X=o.title)!=null?X:"Chat Assistant";let C=m("span","tvw-text-sm tvw-text-cw-muted");C.textContent=(B=o.subtitle)!=null?B:"Here to help you get answers fast",w.append(d,C),l.append(c,w);let g=(_=o.closeButtonSize)!=null?_:"32px",U=m("div",""),$=m("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");$.style.height=g,$.style.width=g,$.type="button",$.setAttribute("aria-label","Close chat"),$.style.display=s?"":"none";let h=(Z=o.closeButtonIconName)!=null?Z:"x",b=ce(h,"20px",o.closeButtonColor||"",2);b?$.appendChild(b):$.textContent="\xD7",t&&$.addEventListener("click",t),U.appendChild($),l.appendChild(U),a.appendChild(l);let W=m("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return W.textContent="Online and ready to help",a.appendChild(W),{header:a,iconHolder:c,headerTitle:d,headerSubtitle:C,closeButton:$,closeButtonWrapper:U,clearChatButton:null,clearChatButtonWrapper:null}},Bn={default:Kn,minimal:Xn,expanded:Vn},Gn=n=>{var e;return(e=Bn[n])!=null?e:Bn.default},Hn=(n,e,s)=>{var a,l,p;if(e!=null&&e.render){let c=e.render({config:n,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat}),f=m("div");f.style.display="none";let w=m("span"),d=m("span"),C=m("button");C.style.display="none";let g=m("div");return g.style.display="none",{header:c,iconHolder:f,headerTitle:w,headerSubtitle:d,closeButton:C,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let t=(a=e==null?void 0:e.layout)!=null?a:"default",o=Gn(t)({config:n,showClose:(p=(l=e==null?void 0:e.showCloseButton)!=null?l:s==null?void 0:s.showClose)!=null?p:!0,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat});return e&&(e.showIcon===!1&&(o.iconHolder.style.display="none"),e.showTitle===!1&&(o.headerTitle.style.display="none"),e.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(o.closeButton.style.display="none"),e.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var ar=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},en=n=>{var ne,re,q,qe,Ve,nt,bt,Ct,J,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,$e,ot,Ue,I,dt;let{config:e}=n,s=m("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=m("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((ne=e==null?void 0:e.voiceRecognition)==null?void 0:ne.enabled)===!0,o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),p=m("form",`tvw-widget-composer tvw-flex tvw-items-end ${r&&o?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);p.style.outline="none";let c=m("textarea");c.placeholder=(q=(re=e==null?void 0:e.copy)==null?void 0:re.inputPlaceholder)!=null?q:"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=(Ve=(qe=e==null?void 0:e.theme)==null?void 0:qe.inputFontFamily)!=null?Ve:"sans-serif",w=(bt=(nt=e==null?void 0:e.theme)==null?void 0:nt.inputFontWeight)!=null?bt:"400";c.style.fontFamily=ar(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 d=(Ct=e==null?void 0:e.sendButton)!=null?Ct:{},C=(J=d.useIcon)!=null?J:!1,g=(fe=d.iconText)!=null?fe:"\u2191",U=d.iconName,$=(mt=d.tooltipText)!=null?mt:"Send message",h=(ft=d.showTooltip)!=null?ft:!1,b=(Ge=d.size)!=null?Ge:"40px",W=d.backgroundColor,v=d.textColor,D=m("div","tvw-send-button-wrapper"),x=m("button",C?"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",C){if(x.style.width=b,x.style.height=b,x.style.minWidth=b,x.style.minHeight=b,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",U){let Se=parseFloat(b)||24,Oe=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",te=ce(U,Se,Oe,2);te?(x.appendChild(te),x.style.color=Oe):(x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white"))}else x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white");W?x.style.backgroundColor=W:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(H=(st=e==null?void 0:e.copy)==null?void 0:st.sendButtonLabel)!=null?H:"Send",v?x.style.color=v:x.classList.add("tvw-text-white");if(d.borderWidth&&(x.style.borderWidth=d.borderWidth,x.style.borderStyle="solid"),d.borderColor&&(x.style.borderColor=d.borderColor),d.paddingX?(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),d.paddingY?(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),h&&$){let Se=m("div","tvw-send-button-tooltip");Se.textContent=$,D.appendChild(Se)}D.appendChild(x);let S=(He=e==null?void 0:e.voiceRecognition)!=null?He:{},X=S.enabled===!0,B=null,_=null,Z=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(X&&Z){_=m("div","tvw-send-button-wrapper"),B=m("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),B.type="button",B.setAttribute("aria-label","Start voice recognition");let Se=(at=S.iconName)!=null?at:"mic",Oe=(lt=S.iconSize)!=null?lt:b,te=parseFloat(Oe)||24,Ae=(Tt=S.backgroundColor)!=null?Tt:W,Te=(wt=S.iconColor)!=null?wt:v;B.style.width=Oe,B.style.height=Oe,B.style.minWidth=Oe,B.style.minHeight=Oe,B.style.fontSize="18px",B.style.lineHeight="1";let ze=Te||"currentColor",Je=ce(Se,te,ze,1.5);Je?(B.appendChild(Je),B.style.color=ze):(B.textContent="\u{1F3A4}",B.style.color=ze),Ae?B.style.backgroundColor=Ae:B.classList.add("tvw-bg-cw-primary"),Te?B.style.color=Te:!Te&&!v&&B.classList.add("tvw-text-white"),S.borderWidth&&(B.style.borderWidth=S.borderWidth,B.style.borderStyle="solid"),S.borderColor&&(B.style.borderColor=S.borderColor),S.paddingX&&(B.style.paddingLeft=S.paddingX,B.style.paddingRight=S.paddingX),S.paddingY&&(B.style.paddingTop=S.paddingY,B.style.paddingBottom=S.paddingY),_.appendChild(B);let xt=($e=S.tooltipText)!=null?$e:"Start voice recognition";if(((ot=S.showTooltip)!=null?ot:!1)&&xt){let yt=m("div","tvw-send-button-tooltip");yt.textContent=xt,_.appendChild(yt)}}p.addEventListener("click",Se=>{Se.target!==x&&Se.target!==D&&Se.target!==B&&Se.target!==_&&c.focus()}),p.append(c),_&&p.append(_),p.append(D);let j=m("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),K=(Ue=e==null?void 0:e.statusIndicator)!=null?Ue:{},Q=(I=K.visible)!=null?I:!0;return j.style.display=Q?"":"none",j.textContent=(dt=K.idleText)!=null?dt:"Online",s.append(t,p,j),{footer:s,suggestions:t,composerForm:p,textarea:c,sendButton:x,sendButtonWrapper:D,micButton:B,micButtonWrapper:_,statusText:j}};var Lo=n=>{var p,c,f,w,d,C,g;if(!((c=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)!=null?c:!0)){let U=m("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),$=m("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),h=(w=(f=n==null?void 0:n.launcher)==null?void 0:f.width)!=null?w:"100%";return U.style.width=h,$.style.width="100%",U.appendChild($),{wrapper:U,panel:$}}let s=(d=n==null?void 0:n.launcher)!=null?d:{},t=s.position&&vt[s.position]?vt[s.position]:vt["bottom-right"],r=m("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),o=m("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),a=(g=(C=n==null?void 0:n.launcher)==null?void 0:C.width)!=null?g:n==null?void 0:n.launcherWidth,l=a!=null?a:"min(400px, calc(100vw - 24px))";return o.style.width=l,o.style.maxWidth=l,r.appendChild(o),{wrapper:r,panel:o}},Bo=(n,e=!0)=>{var w,d,C,g,U;let s=m("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=n==null?void 0:n.layout)==null?void 0:w.header,r=t?Hn(n,t,{showClose:e}):Ot({config:n,showClose:e}),o=m("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");o.id="vanilla-agent-scroll-container";let a=m("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=m("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(C=(d=n==null?void 0:n.copy)==null?void 0:d.welcomeTitle)!=null?C:"Hello \u{1F44B}";let p=m("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");p.textContent=(U=(g=n==null?void 0:n.copy)==null?void 0:g.welcomeSubtitle)!=null?U:"Ask anything about your account or products.",a.append(l,p);let c=m("div","tvw-flex tvw-flex-col tvw-gap-3");o.append(a,c);let f=en({config:n});return Qt(s,r,n),s.append(o,f.footer),{container:s,body:o,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:p,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 gn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let s=document.createElement("div");s.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",s.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(e),n.appendChild(s),n.appendChild(t),n.appendChild(r),n},lr=(n,e)=>{let s=m("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=m("img");r.src=t,r.alt=e==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",s.appendChild(r)}else s.textContent=t,s.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else s.textContent=e==="user"?"U":"A",s.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return s},Ho=(n,e)=>{let s=m("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?s.textContent=e.format(t):s.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s},dr=(n,e="bubble")=>{let s=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):s.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":s.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):s.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:s.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):s.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 s},Zn=(n,e,s)=>{var g,U,$,h,b,W;let t=(g=e.showCopy)!=null?g:!0,r=(U=e.showUpvote)!=null?U:!0,o=($=e.showDownvote)!=null?$:!0,a=(h=e.visibility)!=null?h:"hover",l=(b=e.align)!=null?b:"right",p=(W=e.layout)!=null?W:"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"}[p],w=m("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${f} ${a==="hover"?"tvw-message-actions-hover":""}`),d=null,C=(v,D,x,S)=>{let X=document.createElement("button");X.className="tvw-message-action-btn",X.setAttribute("aria-label",D),X.setAttribute("title",D),S&&X.setAttribute("data-action",S);let B=ce(v,14,"currentColor",2);return B&&X.appendChild(B),X.addEventListener("click",_=>{_.preventDefault(),_.stopPropagation(),x()}),X};if(t){let v=C("copy","Copy message",()=>{let D=n.content||"";navigator.clipboard.writeText(D).then(()=>{v.classList.add("tvw-message-action-success");let x=ce("check",14,"currentColor",2);x&&(v.innerHTML="",v.appendChild(x)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let S=ce("copy",14,"currentColor",2);S&&(v.innerHTML="",v.appendChild(S))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),s!=null&&s.onCopy&&s.onCopy(n),e.onCopy&&e.onCopy(n)},"copy");w.appendChild(v)}if(r){let v=C("thumbs-up","Upvote",()=>{if(d==="upvote")d=null,v.classList.remove("tvw-message-action-active");else{let x=w.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),d="upvote",v.classList.add("tvw-message-action-active");let S={type:"upvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),e.onFeedback&&e.onFeedback(S)}},"upvote");w.appendChild(v)}if(o){let v=C("thumbs-down","Downvote",()=>{if(d==="downvote")d=null,v.classList.remove("tvw-message-action-active");else{let x=w.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),d="downvote",v.classList.add("tvw-message-action-active");let S={type:"downvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),e.onFeedback&&e.onFeedback(S)}},"downvote");w.appendChild(v)}return w},tn=(n,e,s,t,r)=>{var W,v,D,x,S;let o=s!=null?s:{},a=(W=o.layout)!=null?W:"bubble",l=o.avatar,p=o.timestamp,c=(v=l==null?void 0:l.show)!=null?v:!1,f=(D=p==null?void 0:p.show)!=null?D:!1,w=(x=l==null?void 0:l.position)!=null?x:"left",d=(S=p==null?void 0:p.position)!=null?S:"below",C=dr(n.role,a),g=m("div",C.join(" ")),U=document.createElement("div");if(U.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),f&&d==="inline"&&n.createdAt){let X=Ho(n,p);X.classList.add("tvw-ml-2","tvw-inline"),U.appendChild(X)}if(g.appendChild(U),f&&d==="below"&&n.createdAt){let X=Ho(n,p);X.classList.add("tvw-mt-1"),g.appendChild(X)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let X=gn();g.appendChild(X)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let X=Zn(n,t,r);g.appendChild(X)}if(!c||n.role==="system")return g;let h=m("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),b=lr(l,n.role);return w==="right"||w==="left"&&n.role==="user"?h.append(g,b):h.append(b,g),g.classList.remove("tvw-max-w-[85%]"),g.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),h},Po=(n,e,s,t,r)=>{let o=s!=null?s:{};return n.role==="user"&&o.renderUserMessage?o.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&o.renderAssistantMessage?o.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):tn(n,e,s,t,r)};var Qn=new Set,es=n=>{let e=n.reasoning,s=m("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return s;let t=Qn.has(n.id),r=m("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",t?"true":"false");let o=m("div","tvw-flex tvw-flex-col tvw-text-left"),a=m("span","tvw-text-xs tvw-text-cw-primary");a.textContent="Thinking...",o.appendChild(a);let l=m("span","tvw-text-xs tvw-text-cw-primary");l.textContent=To(e),o.appendChild(l),e.status==="complete"?a.style.display="none":a.style.display="";let p=m("div","tvw-flex tvw-items-center"),f=ce(t?"chevron-up":"chevron-down",16,"currentColor",2);f?p.appendChild(f):p.textContent=t?"Hide":"Show";let w=m("div","tvw-flex tvw-items-center tvw-ml-auto");w.append(p),r.append(o,w);let d=m("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");d.style.display=t?"":"none";let C=e.chunks.join(""),g=m("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");g.textContent=C||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),d.appendChild(g);let U=()=>{r.setAttribute("aria-expanded",t?"true":"false"),p.innerHTML="";let b=ce(t?"chevron-up":"chevron-down",16,"currentColor",2);b?p.appendChild(b):p.textContent=t?"Hide":"Show",d.style.display=t?"":"none"},$=()=>{t=!t,t?Qn.add(n.id):Qn.delete(n.id),U()};return r.addEventListener("pointerdown",h=>{h.preventDefault(),$()}),r.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),$())}),U(),s.append(r,d),s};var ts=new Set,ns=(n,e)=>{var $;let s=n.toolCall,t=($=e==null?void 0:e.toolCall)!=null?$:{},r=m("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!s)return r;let o=ts.has(n.id),a=m("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),t.headerBackgroundColor&&(a.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(a.style.paddingLeft=t.headerPaddingX,a.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(a.style.paddingTop=t.headerPaddingY,a.style.paddingBottom=t.headerPaddingY);let l=m("div","tvw-flex tvw-flex-col tvw-text-left"),p=m("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(p.style.color=t.headerTextColor),p.textContent=Eo(s),l.appendChild(p);let c=m("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",w=ce(o?"chevron-up":"chevron-down",16,f,2);w?c.appendChild(w):c.textContent=o?"Hide":"Show";let d=m("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");d.append(c),a.append(l,d);let C=m("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(C.style.display=o?"":"none",t.contentBackgroundColor&&(C.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(C.style.color=t.contentTextColor),t.contentPaddingX&&(C.style.paddingLeft=t.contentPaddingX,C.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(C.style.paddingTop=t.contentPaddingY,C.style.paddingBottom=t.contentPaddingY),s.name){let h=m("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?h.style.color=t.contentTextColor:t.headerTextColor&&(h.style.color=t.headerTextColor),h.textContent=s.name,C.appendChild(h)}if(s.args!==void 0){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Arguments";let W=m("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Jn(s.args),h.append(b,W),C.appendChild(h)}if(s.chunks&&s.chunks.length){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Activity";let W=m("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=s.chunks.join(`
16
+ `),h.append(b,W),C.appendChild(h)}if(s.status==="complete"&&s.result!==void 0){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Result";let W=m("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Jn(s.result),h.append(b,W),C.appendChild(h)}if(s.status==="complete"&&typeof s.duration=="number"){let h=m("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(h.style.color=t.contentTextColor),h.textContent=`Duration: ${s.duration}ms`,C.appendChild(h)}let g=()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let h=t.toggleTextColor||t.headerTextColor||"currentColor",b=ce(o?"chevron-up":"chevron-down",16,h,2);b?c.appendChild(b):c.textContent=o?"Hide":"Show",C.style.display=o?"":"none"},U=()=>{o=!o,o?ts.add(n.id):ts.delete(n.id),g()};return a.addEventListener("pointerdown",h=>{h.preventDefault(),U()}),a.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),U())}),g(),r.append(a,C),r};var Ro=n=>{let e=[];return{buttons:e,render:(t,r,o,a,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(a!=null?a:r?r.getMessages():[]).some(C=>C.role==="user"))return;let f=document.createDocumentFragment(),w=r?r.isStreaming():!1,d=C=>{switch(C){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(C=>{let g=m("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=C,g.disabled=w,l!=null&&l.fontFamily&&(g.style.fontFamily=d(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()||(o.value="",r.sendMessage(C))}),f.appendChild(g),e.push(g)}),n.appendChild(f)}}};var Io={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"}},ss=(n,e,s,t)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(o=>{var g,U,$;if(o.dataset.enhanced==="true")return;let a=(g=o.dataset.tvForm)!=null?g:"init";o.dataset.enhanced="true";let l=(U=Io[a])!=null?U:Io.init;o.classList.add("tvw-form-card","tvw-space-y-4");let p=m("div","tvw-space-y-1"),c=m("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=m("p","tvw-text-sm tvw-text-cw-muted");h.textContent=l.description,p.appendChild(h)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(h=>{var x,S;let b=m("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");b.htmlFor=`${e.id}-${a}-${h.name}`;let W=m("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");W.textContent=h.label,b.appendChild(W);let v=(x=h.type)!=null?x:"text",D;v==="textarea"?(D=document.createElement("textarea"),D.rows=3):(D=document.createElement("input"),D.type=v),D.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",D.id=`${e.id}-${a}-${h.name}`,D.name=h.name,D.placeholder=(S=h.placeholder)!=null?S:"",h.required&&(D.required=!0),b.appendChild(D),f.appendChild(b)});let w=m("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),d=m("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),C=m("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");C.type="submit",C.textContent=($=l.submitLabel)!=null?$:"Submit",w.appendChild(d),w.appendChild(C),f.appendChild(w),o.replaceChildren(p,f),f.addEventListener("submit",async h=>{var D,x;h.preventDefault();let b=(D=s.formEndpoint)!=null?D:"/form",W=new FormData(f),v={};W.forEach((S,X)=>{v[X]=S}),v.type=a,C.disabled=!0,d.textContent="Submitting\u2026";try{let S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let X=await S.json();d.textContent=(x=X.message)!=null?x:"Thanks! We'll be in touch soon.",X.success&&X.nextPrompt&&await t.sendMessage(String(X.nextPrompt))}catch(S){d.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{C.disabled=!1}})})};var os=class{constructor(){this.plugins=new Map}register(e){var s;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(s=e.onRegister)==null||s.call(e)}unregister(e){var t;let s=this.plugins.get(e);s&&((t=s.onUnregister)==null||t.call(s),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,s)=>{var t,r;return((t=s.priority)!=null?t:0)-((r=e.priority)!=null?r:0)})}getForInstance(e){let s=this.getAll();if(!e||e.length===0)return s;let t=new Set(e.map(o=>o.id));return[...s.filter(o=>!t.has(o.id)),...e].sort((o,a)=>{var l,p;return((l=a.priority)!=null?l:0)-((p=o.priority)!=null?p:0)})}clear(){this.plugins.forEach(e=>{var s;return(s=e.onUnregister)==null?void 0:s.call(e)}),this.plugins.clear()}},hn=new os;var ke={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,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 Pn(n){var e,s,t,r,o,a,l,p,c,f,w,d,C,g,U,$,h,b,W;return n?{...ke,...n,theme:{...ke.theme,...n.theme},launcher:{...ke.launcher,...n.launcher,clearChat:{...(e=ke.launcher)==null?void 0:e.clearChat,...(s=n.launcher)==null?void 0:s.clearChat}},copy:{...ke.copy,...n.copy},sendButton:{...ke.sendButton,...n.sendButton},statusIndicator:{...ke.statusIndicator,...n.statusIndicator},voiceRecognition:{...ke.voiceRecognition,...n.voiceRecognition},features:{...ke.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:ke.suggestionChips,suggestionChipsConfig:{...ke.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...ke.layout,...n.layout,header:{...(r=ke.layout)==null?void 0:r.header,...(o=n.layout)==null?void 0:o.header},messages:{...(a=ke.layout)==null?void 0:a.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(c=(p=ke.layout)==null?void 0:p.messages)==null?void 0:c.avatar,...(w=(f=n.layout)==null?void 0:f.messages)==null?void 0:w.avatar},timestamp:{...(C=(d=ke.layout)==null?void 0:d.messages)==null?void 0:C.timestamp,...(U=(g=n.layout)==null?void 0:g.messages)==null?void 0:U.timestamp}},slots:{...($=ke.layout)==null?void 0:$.slots,...(h=n.layout)==null?void 0:h.slots}},markdown:{...ke.markdown,...n.markdown,options:{...(b=ke.markdown)==null?void 0:b.options,...(W=n.markdown)==null?void 0:W.options}},messageActions:{...ke.messageActions,...n.messageActions}}:ke}var $o=()=>{let n=new Map,e=(r,o)=>(n.has(r)||n.set(r,new Set),n.get(r).add(o),()=>s(r,o)),s=(r,o)=>{var a;(a=n.get(r))==null||a.delete(o)};return{on:e,off:s,emit:(r,o)=>{var a;(a=n.get(r))==null||a.forEach(l=>{try{l(o)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var cr=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},ur=n=>{let e=n.trim(),s=e.indexOf("{");if(s===-1)return null;let t=0;for(let r=s;r<e.length;r+=1){let o=e[r];if(o==="{"&&(t+=1),o==="}"&&(t-=1,t===0))return e.slice(s,r+1)}return null},mn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=cr(n),s=ur(e);if(!s)return null;let t=JSON.parse(s);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...o}=t;return{type:String(r),payload:o,raw:t}}catch{return null}},rs=n=>typeof n=="string"?n:n==null?"":String(n),Kt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:rs(n.payload.text)},messageAndClick:(n,e)=>{var r;if(n.type!=="message_and_click")return;let s=n.payload,t=rs(s.element);if(t&&((r=e.document)!=null&&r.querySelector)){let o=e.document.querySelector(t);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:rs(s.text)}}},Fo=n=>Array.isArray(n)?n.map(e=>String(e)):[],fn=n=>{let e=new Set(Fo(n.getMetadata().processedActionMessageIds)),s=()=>{e=new Set(Fo(n.getMetadata().processedActionMessageIds))},t=()=>{let o=Array.from(e);n.updateMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||e.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?n.parsers.reduce((c,f)=>c||(f==null?void 0:f({text:a,message:o.message}))||null,null):null;if(!l)return null;e.add(o.message.id),t();let p={action:l,message:o.message};n.emit("action:detected",p);for(let c of n.handlers)if(c)try{let f=c(l,{message:o.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:s}};var pr=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},gr=n=>n.map(e=>({...e,streaming:!1})),Rn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let s=e();return s?pr(s.getItem(n)):null},save:s=>{let t=e();if(t)try{let r={...s,messages:s.messages?gr(s.messages):void 0};t.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let s=e();if(s)try{s.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var is=class{constructor(){this.components=new Map}register(e,s){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,s)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([s,t])=>{this.register(s,t)})}},nn=new is;var sn=require("partial-json");function hr(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function mr(n,e){if(!hr(n))return null;let s=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:s,raw:e}}function In(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:s=>{let t=s.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(s.length<=e)return n;try{let r=(0,sn.parse)(s,sn.STR|sn.OBJ),o=mr(r,s);o&&(n=o)}catch{}return e=s.length,n},reset:()=>{n=null,e=0}}}function No(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function $n(n,e){let{config:s,message:t,onPropsUpdate:r}=e,o=nn.get(n.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:t,config:s,updateProps:l=>{r&&r(l)}};try{return o(n.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Oo(){let n=In();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Fn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Nn(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var fr=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function On(n){let{onSubmit:e,onDismiss:s,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:c=fr}=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,d=document.createElement("div");d.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let g=document.createElement("h3");g.className="tvw-feedback-title",g.textContent=t,C.appendChild(g);let U=document.createElement("p");U.className="tvw-feedback-subtitle",U.textContent=r,C.appendChild(U),d.appendChild(C);let $=document.createElement("div");$.className="tvw-feedback-rating tvw-feedback-rating-csat",$.setAttribute("role","radiogroup"),$.setAttribute("aria-label","Satisfaction rating from 1 to 5");let h=[];for(let x=1;x<=5;x++){let S=document.createElement("button");S.type="button",S.className="tvw-feedback-rating-btn tvw-feedback-star-btn",S.setAttribute("role","radio"),S.setAttribute("aria-checked","false"),S.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${c[x-1]}`),S.title=c[x-1],S.dataset.rating=String(x),S.innerHTML=`
17
+ <svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
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
+ </svg>
20
+ `,S.addEventListener("click",()=>{w=x,h.forEach((X,B)=>{let _=B<x;X.classList.toggle("selected",_),X.setAttribute("aria-checked",B===x-1?"true":"false")})}),h.push(S),$.appendChild(S)}d.appendChild($);let b=null;if(p){let x=document.createElement("div");x.className="tvw-feedback-comment-container",b=document.createElement("textarea"),b.className="tvw-feedback-comment",b.placeholder=o,b.rows=3,b.setAttribute("aria-label","Additional comments"),x.appendChild(b),d.appendChild(x)}let W=document.createElement("div");W.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=l,v.addEventListener("click",()=>{s==null||s(),f.remove()});let D=document.createElement("button");return D.type="button",D.className="tvw-feedback-btn tvw-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(w===null){$.classList.add("tvw-feedback-shake"),setTimeout(()=>$.classList.remove("tvw-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let x=(b==null?void 0:b.value.trim())||void 0;await e(w,x),f.remove()}catch(x){D.disabled=!1,D.textContent=a,console.error("[CSAT Feedback] Failed to submit:",x)}}),W.appendChild(v),W.appendChild(D),d.appendChild(W),f.appendChild(d),f}function Dn(n){let{onSubmit:e,onDismiss:s,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!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 d=null,C=document.createElement("div");C.className="tvw-feedback-content";let g=document.createElement("div");g.className="tvw-feedback-header";let U=document.createElement("h3");U.className="tvw-feedback-title",U.textContent=t,g.appendChild(U);let $=document.createElement("p");$.className="tvw-feedback-subtitle",$.textContent=r,g.appendChild($),C.appendChild(g);let h=document.createElement("div");h.className="tvw-feedback-rating tvw-feedback-rating-nps",h.setAttribute("role","radiogroup"),h.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="tvw-feedback-labels";let W=document.createElement("span");W.className="tvw-feedback-label-low",W.textContent=c;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,b.appendChild(W),b.appendChild(v);let D=document.createElement("div");D.className="tvw-feedback-numbers";let x=[];for(let Z=0;Z<=10;Z++){let j=document.createElement("button");j.type="button",j.className="tvw-feedback-rating-btn tvw-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${Z} out of 10`),j.textContent=String(Z),j.dataset.rating=String(Z),Z<=6?j.classList.add("tvw-feedback-detractor"):Z<=8?j.classList.add("tvw-feedback-passive"):j.classList.add("tvw-feedback-promoter"),j.addEventListener("click",()=>{d=Z,x.forEach((K,Q)=>{K.classList.toggle("selected",Q===Z),K.setAttribute("aria-checked",Q===Z?"true":"false")})}),x.push(j),D.appendChild(j)}h.appendChild(b),h.appendChild(D),C.appendChild(h);let S=null;if(p){let Z=document.createElement("div");Z.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),Z.appendChild(S),C.appendChild(Z)}let X=document.createElement("div");X.className="tvw-feedback-actions";let B=document.createElement("button");B.type="button",B.className="tvw-feedback-btn tvw-feedback-btn-skip",B.textContent=l,B.addEventListener("click",()=>{s==null||s(),w.remove()});let _=document.createElement("button");return _.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-submit",_.textContent=a,_.addEventListener("click",async()=>{if(d===null){D.classList.add("tvw-feedback-shake"),setTimeout(()=>D.classList.remove("tvw-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let Z=(S==null?void 0:S.value.trim())||void 0;await e(d,Z),w.remove()}catch(Z){_.disabled=!1,_.textContent=a,console.error("[NPS Feedback] Failed to submit:",Z)}}),X.appendChild(B),X.appendChild(_),C.appendChild(X),w.appendChild(C),w}var on="vanilla-agent-chat-history",wr=30*1e3,as=n=>!n||typeof n!="object"?{}:{...n},Do=n=>n.map(e=>({...e,streaming:!1})),_o=(n,e)=>{let s=n!=null&&n.markdown?un(n.markdown):null;return t=>{var a,l,p;let r=(a=t.text)!=null?a:"",o=(l=t.message.rawContent)!=null?l:null;if(e){let c=e.process({text:r,raw:o!=null?o:r,message:t.message,streaming:t.streaming});c!==null&&(r=c.text,c.persist||(t.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...t,text:r,raw:(p=o!=null?o:t.text)!=null?p:""}):s?s(r):xn(r)}},_n=(n,e,s)=>{var de,pe,Re,ge,De,it,ht,cs,us,ps,gs,hs,ms,fs;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Pn(e),r=hn.getForInstance(t.plugins);t.components&&nn.registerAll(t.components);let o=$o(),a=(de=t.storageAdapter)!=null?de:Rn(),l={},p=null;if(a!=null&&a.load)try{let i=a.load();if(i&&typeof i.then=="function")p=i;else if(i){let u=i;u.metadata&&(l=as(u.metadata)),(pe=u.messages)!=null&&pe.length&&(t={...t,initialMessages:u.messages})}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",i)}let c=()=>l,f=i=>{var E;l=(E=i({...l}))!=null?E:{},Mt()},w=t.actionParsers&&t.actionParsers.length?t.actionParsers:[mn],d=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick],C=fn({parsers:w,handlers:d,getMetadata:c,updateMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let g=(ge=(Re=t.launcher)==null?void 0:Re.enabled)!=null?ge:!0,U=(it=(De=t.launcher)==null?void 0:De.autoExpand)!=null?it:!1,$=U,h=g,b=g?U:!0,W=_o(t,C),v=(cs=(ht=t.features)==null?void 0:ht.showReasoning)!=null?cs:!0,D=(ps=(us=t.features)==null?void 0:us.showToolCalls)!=null?ps:!0,x={onCopy:i=>{var u,E;o.emit("message:copy",i),I!=null&&I.isClientTokenMode()&&I.submitMessageFeedback(i.id,"copy").catch(O=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",O)}),(E=(u=t.messageActions)==null?void 0:u.onCopy)==null||E.call(u,i)},onFeedback:i=>{var u,E;o.emit("message:feedback",i),I!=null&&I.isClientTokenMode()&&I.submitMessageFeedback(i.messageId,i.type).catch(O=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",O)}),(E=(u=t.messageActions)==null?void 0:u.onFeedback)==null||E.call(u,i)}},S=(gs=t.statusIndicator)!=null?gs:{},X=i=>{var u,E,O,k;return i==="idle"?(u=S.idleText)!=null?u:Xe.idle:i==="connecting"?(E=S.connectingText)!=null?E:Xe.connecting:i==="connected"?(O=S.connectedText)!=null?O:Xe.connected:i==="error"?(k=S.errorText)!=null?k:Xe.error:Xe[i]},{wrapper:B,panel:_}=Lo(t),Z=Bo(t,g),{container:j,body:K,messagesWrapper:Q,suggestions:ne,textarea:re,sendButton:q,sendButtonWrapper:qe,composerForm:Ve,statusText:nt,introTitle:bt,introSubtitle:Ct,closeButton:J,iconHolder:fe,headerTitle:mt,headerSubtitle:ft,header:Ge,footer:st}=Z,H=Z.micButton,He=Z.micButtonWrapper,at=r.find(i=>i.renderHeader);if(at!=null&&at.renderHeader){let i=at.renderHeader({config:t,defaultRenderer:()=>{let u=Ot({config:t,showClose:g});return Qt(j,u,t),u.header},onClose:()=>Ke(!1,"user")});if(i){let u=j.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(i),Ge=i)}}let lt=r.find(i=>i.renderComposer);if(lt!=null&&lt.renderComposer){let i=lt.renderComposer({config:t,defaultRenderer:()=>en({config:t}).footer,onSubmit:u=>{I&&!I.isStreaming()&&I.sendMessage(u)},disabled:!1});i&&(st.replaceWith(i),st=i)}(()=>{var O,k;let i=(k=(O=t.layout)==null?void 0:O.slots)!=null?k:{},u=ee=>{switch(ee){case"body-top":return j.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Q;case"footer-top":return ne;case"composer":return Ve;case"footer-bottom":return nt;default:return null}},E=(ee,N)=>{var T;switch(ee){case"header-left":case"header-center":case"header-right":if(ee==="header-left")Ge.insertBefore(N,Ge.firstChild);else if(ee==="header-right")Ge.appendChild(N);else{let z=Ge.querySelector(".tvw-flex-col");z?(T=z.parentNode)==null||T.insertBefore(N,z.nextSibling):Ge.appendChild(N)}break;case"body-top":let G=K.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(N):K.insertBefore(N,K.firstChild);break;case"body-bottom":K.appendChild(N);break;case"footer-top":ne.replaceWith(N);break;case"footer-bottom":nt.replaceWith(N);break;default:break}};for(let[ee,N]of Object.entries(i))if(N)try{let T=N({config:t,defaultContent:()=>u(ee)});T&&E(ee,T)}catch(T){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ee}":`,T)}})(),_.appendChild(j),n.appendChild(B);let wt=()=>{var ae,Ie,ct,le,ut,Pt,Rt,kt,Ut,It,zt,pt,$t,Ft,bn,dn;let i=(Ie=(ae=t.launcher)==null?void 0:ae.sidebarMode)!=null?Ie:!1,u=i||((le=(ct=t.launcher)==null?void 0:ct.fullHeight)!=null?le:!1),E=(ut=t.theme)!=null?ut:{},O=(Rt=(Pt=t.launcher)==null?void 0:Pt.position)!=null?Rt:"bottom-left",k=O==="bottom-left"||O==="top-left",ee=i?"none":"1px solid var(--tvw-cw-border)",N=i?k?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",T=i?"0":"16px",G=(kt=E.panelBorder)!=null?kt:ee,z=(Ut=E.panelShadow)!=null?Ut:N,R=(It=E.panelBorderRadius)!=null?It:T;n.style.cssText="",B.style.cssText="",_.style.cssText="",j.style.cssText="",K.style.cssText="",st.style.cssText="";let Y=(pt=(zt=t==null?void 0:t.launcher)==null?void 0:zt.width)!=null?pt:t==null?void 0:t.launcherWidth,Be=Y!=null?Y:"min(400px, calc(100vw - 24px))";i||(_.style.width=Be,_.style.maxWidth=Be),_.style.boxShadow=z,_.style.borderRadius=R,j.style.border=G,j.style.borderRadius=R;let he=(($t=t.launcher)==null?void 0:$t.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",B.style.display="flex",B.style.flexDirection="column",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.maxHeight="100%",B.style.height="100%",he&&(B.style.overflow="hidden"),_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.height="100%",_.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",st.style.flexShrink="0"),B.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"),!i&&!he&&((Ft=vt[O])!=null?Ft:vt["bottom-right"]).split(" ").forEach(Vt=>B.classList.add(Vt)),i){let Jt=(dn=(bn=t.launcher)==null?void 0:bn.sidebarWidth)!=null?dn:"420px";B.style.cssText=`
17
21
  position: fixed !important;
18
22
  top: 0 !important;
19
23
  bottom: 0 !important;
20
- width: ${zt} !important;
24
+ width: ${Jt} !important;
21
25
  height: 100vh !important;
22
26
  max-height: 100vh !important;
23
27
  margin: 0 !important;
24
28
  padding: 0 !important;
25
29
  display: flex !important;
26
30
  flex-direction: column !important;
27
- ${R?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
28
- `,W.style.cssText=`
31
+ ${k?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
+ `,_.style.cssText=`
29
33
  position: relative !important;
30
34
  display: flex !important;
31
35
  flex-direction: column !important;
@@ -36,9 +40,9 @@
36
40
  min-height: 0 !important;
37
41
  margin: 0 !important;
38
42
  padding: 0 !important;
39
- box-shadow: ${N} !important;
40
- border-radius: ${B} !important;
41
- `,W.style.setProperty("width","100%","important"),W.style.setProperty("max-width","100%","important"),G.style.cssText=`
43
+ box-shadow: ${z} !important;
44
+ border-radius: ${R} !important;
45
+ `,_.style.setProperty("width","100%","important"),_.style.setProperty("max-width","100%","important"),j.style.cssText=`
42
46
  display: flex !important;
43
47
  flex-direction: column !important;
44
48
  flex: 1 1 0% !important;
@@ -47,17 +51,17 @@
47
51
  min-height: 0 !important;
48
52
  max-height: 100% !important;
49
53
  overflow: hidden !important;
50
- border-radius: ${B} !important;
51
- border: ${X} !important;
52
- `,et.style.cssText=`
54
+ border-radius: ${R} !important;
55
+ border: ${G} !important;
56
+ `,st.style.cssText=`
53
57
  flex-shrink: 0 !important;
54
58
  border-top: none !important;
55
59
  padding: 8px 16px 12px 16px !important;
56
- `}if(!ge){let zt="max-height: -moz-available !important; max-height: stretch !important;",Xt=a?"":"padding-top: 1.25em !important;";Q.style.cssText+=zt+Xt}};wt(),_n(n,t);let $e=[],tt=Eo(ne),qe=null,j,lt=!1,Ke=!0,We=0,_e=0,J=null,Se=!1,ke=0,Ue=!1,nt=125,St=2e3,Bt=5,gt=50,At=new Map,de={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Dt=(ds=(ls=t.voiceRecognition)==null?void 0:ls.autoResume)!=null?ds:!1,kt=a=>{s.emit("voice:state",{active:de.active,source:a,timestamp:Date.now()})},be=()=>{d(a=>({...a,voiceState:{active:de.active,timestamp:Date.now(),manuallyDeactivated:de.manuallyDeactivated}}))},yt=()=>{var O,R;if(((O=t.voiceRecognition)==null?void 0:O.enabled)===!1)return;let a=ts(l.voiceState),u=!!a.active,T=Number((R=a.timestamp)!=null?R:0);de.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-T<lr&&setTimeout(()=>{de.active||(de.manuallyDeactivated=!1,Oe("restore"))},1e3)},Tt=()=>j?Ho(j.getMessages()).filter(a=>!a.__skipPersist):[];function Ht(a){if(!(i!=null&&i.save))return;let T={messages:a?Ho(a):j?Tt():[],metadata:l};try{let O=i.save(T);O instanceof Promise&&O.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(O){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",O)}}let vt=(a=!1)=>{if(!Ke)return;let u=Date.now();Se&&u<ke&&!a||(Se&&u>=ke&&(Se=!1),!(!a&&!lt)&&(u-_e<nt||(_e=u,J&&cancelAnimationFrame(J),J=requestAnimationFrame(()=>{Se||!Ke||(Ue=!0,U.scrollTop=U.scrollHeight,We=U.scrollTop,requestAnimationFrame(()=>{Ue=!1}),J=null)}))))},Wt=null,fn=()=>Q.querySelector("#vanilla-agent-scroll-container")||U,wn=(a,u=500)=>{let T=a.scrollTop,O=a.clientHeight,R=a.scrollHeight,se=R-T;if(T+O>=R-2||Math.abs(se)<5)return;Wt!==null&&(cancelAnimationFrame(Wt),Wt=null);let v=performance.now(),X=B=>1-Math.pow(1-B,3),N=B=>{let _=a.scrollHeight;_!==R&&(R=_,se=R-T);let Me=B-v,ge=Math.min(Me/u,1),re=X(ge),Ie=T+se*re;a.scrollTop=Ie,ge<1?Wt=requestAnimationFrame(N):(a.scrollTop=a.scrollHeight,Wt=null)};Wt=requestAnimationFrame(N)},yn=a=>{let u=new Map;a.forEach(T=>{let O=At.get(T.id);u.set(T.id,{streaming:T.streaming,role:T.role}),!O&&T.role==="assistant"&&s.emit("assistant:message",T),T.role==="assistant"&&(O!=null&&O.streaming)&&T.streaming===!1&&s.emit("assistant:complete",T)}),At.clear(),u.forEach((T,O)=>{At.set(O,T)})},jt=(a,u,T)=>{a.innerHTML="";let O=document.createDocumentFragment();u.forEach(v=>{var Me,ge;let X=null,N=o.find(re=>!!(v.variant==="reasoning"&&re.renderReasoning||v.variant==="tool"&&re.renderToolCall||!v.variant&&re.renderMessage)),B=(Me=t.layout)==null?void 0:Me.messages;if(N)if(v.variant==="reasoning"&&v.reasoning&&N.renderReasoning){if(!S)return;X=N.renderReasoning({message:v,defaultRenderer:()=>Kn(v),config:t})}else if(v.variant==="tool"&&v.toolCall&&N.renderToolCall){if(!Y)return;X=N.renderToolCall({message:v,defaultRenderer:()=>Vn(v,t),config:t})}else N.renderMessage&&(X=N.renderMessage({message:v,defaultRenderer:()=>{let re=en(v,T,B);return v.role!=="user"&&Gn(re,v,t,j),re},config:t}));if(!X&&v.role==="assistant"&&!v.variant&&t.enableComponentStreaming!==!1&&In(v)){let Ie=$n(v);if(Ie){let dt=Rn(Ie,{config:t,message:v,transform:T});if(dt){let ie=document.createElement("div");if(ie.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(" "),ie.setAttribute("data-message-id",v.id),v.content&&v.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=T({text:v.content,message:v,streaming:!!v.streaming,raw:v.rawContent}),ie.appendChild(ct)}ie.appendChild(dt),X=ie}}}if(!X)if(v.variant==="reasoning"&&v.reasoning){if(!S)return;X=Kn(v)}else if(v.variant==="tool"&&v.toolCall){if(!Y)return;X=Vn(v,t)}else{let re=(ge=t.layout)==null?void 0:ge.messages;re!=null&&re.renderUserMessage&&v.role==="user"?X=re.renderUserMessage({message:v,config:t,streaming:!!v.streaming}):re!=null&&re.renderAssistantMessage&&v.role==="assistant"?X=re.renderAssistantMessage({message:v,config:t,streaming:!!v.streaming}):X=en(v,T,re),v.role!=="user"&&X&&Gn(X,v,t,j)}let _=document.createElement("div");_.className="tvw-flex",v.role==="user"&&_.classList.add("tvw-justify-end"),_.appendChild(X),O.appendChild(_)});let R=u.some(v=>v.role==="assistant"&&v.streaming),se=u[u.length-1],H=(se==null?void 0:se.role)==="assistant"&&!se.streaming;if(lt&&u.some(v=>v.role==="user")&&!R&&!H){let v=un(),X=document.createElement("div");X.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),X.appendChild(v);let N=document.createElement("div");N.className="tvw-flex",N.appendChild(X),O.appendChild(N)}a.appendChild(O),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let v=fn();wn(v)})})},_t=()=>{w&&(x?(Q.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),W.classList.remove("tvw-scale-95","tvw-opacity-0"),W.classList.add("tvw-scale-100","tvw-opacity-100"),h?h.element.style.display="none":k&&(k.style.display="none")):(Q.classList.add("tvw-pointer-events-none","tvw-opacity-0"),W.classList.remove("tvw-scale-100","tvw-opacity-100"),W.classList.add("tvw-scale-95","tvw-opacity-0"),h?h.element.style.display="":k&&(k.style.display="")))},st=(a,u="user")=>{if(!w||x===a)return;let T=x;x=a,_t(),x&&(ye(),vt(!0));let O={open:x,source:u,timestamp:Date.now()};x&&!T?s.emit("widget:opened",O):!x&&T&&s.emit("widget:closed",O),s.emit("widget:state",{open:x,launcherEnabled:w,voiceActive:de.active,streaming:j.isStreaming()})},Kt=a=>{$.disabled=a,M&&(M.disabled=a),tt.buttons.forEach(u=>{u.disabled=a})},on=()=>{var R,se,H,v,X,N,B,_,Me,ge,re,Ie,dt,ie;xt.textContent=(se=(R=t.copy)==null?void 0:R.welcomeTitle)!=null?se:"Hello \u{1F44B}",Ct.textContent=(v=(H=t.copy)==null?void 0:H.welcomeSubtitle)!=null?v:"Ask anything about your account or products.",Z.placeholder=(N=(X=t.copy)==null?void 0:X.inputPlaceholder)!=null?N:"How can I help...",((_=(B=t.sendButton)==null?void 0:B.useIcon)!=null?_:!1)||($.textContent=(ge=(Me=t.copy)==null?void 0:Me.sendButtonLabel)!=null?ge:"Send");let u=(Ie=(re=t.theme)==null?void 0:re.inputFontFamily)!=null?Ie:"sans-serif",T=(ie=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?ie:"400",O=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};Z.style.fontFamily=O(u),Z.style.fontWeight=T};j=new Gt(t,{onMessagesChanged(a){jt(z,a,I),j&&(a.some(O=>O.role==="user")?tt.render([],j,Z,a):tt.render(t.suggestionChips,j,Z,a,t.suggestionChipsConfig)),vt(!lt),yn(a);let u=[...a].reverse().find(T=>T.role==="user");de.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Ht(a)},onStatusChanged(a){var O;let u=(O=t.statusIndicator)!=null?O:{},T=R=>{var se,H,v,X;return R==="idle"?(se=u.idleText)!=null?se:ze.idle:R==="connecting"?(H=u.connectingText)!=null?H:ze.connecting:R==="connected"?(v=u.connectedText)!=null?v:ze.connected:R==="error"?(X=u.errorText)!=null?X:ze.error:ze[R]};Qe.textContent=T(a)},onStreamingChanged(a){lt=a,Kt(a),j&&jt(z,j.getMessages(),I),a||vt(!0)}}),c&&c.then(a=>{var u;a&&(a.metadata&&(l=ts(a.metadata),b.syncFromMetadata()),(u=a.messages)!=null&&u.length&&j.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let rn=a=>{a.preventDefault();let u=Z.value.trim();u&&(Z.value="",j.sendMessage(u))},an=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),$.click())},y=null,K=!1,oe=null,we=null,Pe=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Oe=(a="user")=>{var se,H,v,X;if(K||j.isStreaming())return;let u=Pe();if(!u)return;y=new u;let O=(H=((se=t.voiceRecognition)!=null?se:{}).pauseDuration)!=null?H:2e3;y.continuous=!0,y.interimResults=!0,y.lang="en-US";let R=Z.value;y.onresult=N=>{let B="",_="";for(let ge=0;ge<N.results.length;ge++){let re=N.results[ge],Ie=re[0].transcript;re.isFinal?B+=Ie+" ":_=Ie}let Me=R+B+_;Z.value=Me,oe&&clearTimeout(oe),(B||_)&&(oe=window.setTimeout(()=>{let ge=Z.value.trim();ge&&y&&K&&(ce(),Z.value="",j.sendMessage(ge,{viaVoice:!0}))},O))},y.onerror=N=>{N.error!=="no-speech"&&ce()},y.onend=()=>{if(K){let N=Z.value.trim();N&&N!==R.trim()&&(Z.value="",j.sendMessage(N,{viaVoice:!0})),ce()}};try{if(y.start(),K=!0,de.active=!0,a!=="system"&&(de.manuallyDeactivated=!1),kt(a),be(),M){we={backgroundColor:M.style.backgroundColor,color:M.style.color,borderColor:M.style.borderColor};let N=(v=t.voiceRecognition)!=null?v:{},B=(X=N.recordingBackgroundColor)!=null?X:"#ef4444",_=N.recordingIconColor,Me=N.recordingBorderColor;if(M.classList.add("tvw-voice-recording"),M.style.backgroundColor=B,_){M.style.color=_;let ge=M.querySelector("svg");ge&&ge.setAttribute("stroke",_)}Me&&(M.style.borderColor=Me),M.setAttribute("aria-label","Stop voice recognition")}}catch{ce("system")}},ce=(a="user")=>{if(K){if(K=!1,oe&&(clearTimeout(oe),oe=null),y){try{y.stop()}catch{}y=null}if(de.active=!1,kt(a),be(),M){if(M.classList.remove("tvw-voice-recording"),we){M.style.backgroundColor=we.backgroundColor,M.style.color=we.color,M.style.borderColor=we.borderColor;let u=M.querySelector("svg");u&&u.setAttribute("stroke",we.color||"currentColor"),we=null}M.setAttribute("aria-label","Start voice recognition")}}},L=(a,u)=>{var Ie,dt,ie,ct,Rt,It,Mt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let O=p("div","tvw-send-button-wrapper"),R=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");R.type="button",R.setAttribute("aria-label","Start voice recognition");let se=(Ie=a==null?void 0:a.iconName)!=null?Ie:"mic",H=(dt=u==null?void 0:u.size)!=null?dt:"40px",v=(ie=a==null?void 0:a.iconSize)!=null?ie:H,X=parseFloat(v)||24,N=(ct=a==null?void 0:a.backgroundColor)!=null?ct:u==null?void 0:u.backgroundColor,B=(Rt=a==null?void 0:a.iconColor)!=null?Rt:u==null?void 0:u.textColor;R.style.width=v,R.style.height=v,R.style.minWidth=v,R.style.minHeight=v,R.style.fontSize="18px",R.style.lineHeight="1";let _=B||"currentColor",Me=ve(se,X,_,1.5);Me?(R.appendChild(Me),R.style.color=_):(R.textContent="\u{1F3A4}",R.style.color=_),N?R.style.backgroundColor=N:R.classList.add("tvw-bg-cw-primary"),B?R.style.color=B:!B&&!(u!=null&&u.textColor)&&R.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(R.style.borderWidth=a.borderWidth,R.style.borderStyle="solid"),a!=null&&a.borderColor&&(R.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(R.style.paddingLeft=a.paddingX,R.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(R.style.paddingTop=a.paddingY,R.style.paddingBottom=a.paddingY),O.appendChild(R);let ge=(It=a==null?void 0:a.tooltipText)!=null?It:"Start voice recognition";if(((Mt=a==null?void 0:a.showTooltip)!=null?Mt:!1)&&ge){let qt=p("div","tvw-send-button-tooltip");qt.textContent=ge,O.appendChild(qt)}return{micButton:R,micButtonWrapper:O}},ot=()=>{if(K){let a=Z.value.trim();de.manuallyDeactivated=!0,be(),ce("user"),a&&(Z.value="",j.sendMessage(a))}else de.manuallyDeactivated=!1,be(),Oe("user")};M&&(M.addEventListener("click",ot),$e.push(()=>{ce("system"),M&&M.removeEventListener("click",ot)}));let ee=s.on("assistant:complete",()=>{Dt&&(de.active||de.manuallyDeactivated||Dt==="assistant"&&!de.lastUserMessageWasVoice||setTimeout(()=>{!de.active&&!de.manuallyDeactivated&&Oe("auto")},600))});$e.push(ee);let C=()=>{st(!x,"user")},h=null,k=null;if(w){let a=o.find(u=>u.renderLauncher);if(a!=null&&a.renderLauncher){let u=a.renderLauncher({config:t,defaultRenderer:()=>pn(t,C).element,onToggle:C});u&&(k=u)}k||(h=pn(t,C))}h?n.appendChild(h.element):k&&n.appendChild(k),_t(),tt.render(t.suggestionChips,j,Z,void 0,t.suggestionChipsConfig),on(),Kt(j.isStreaming()),vt(!0),yt();let ye=()=>{var T,O,R,se,H,v,X,N;let a=(O=(T=t.launcher)==null?void 0:T.sidebarMode)!=null?O:!1,u=a||((se=(R=t.launcher)==null?void 0:R.fullHeight)!=null?se:!1);if(!w){W.style.height="",W.style.width="";return}if(!a){let B=(v=(H=t==null?void 0:t.launcher)==null?void 0:H.width)!=null?v:t==null?void 0:t.launcherWidth,_=B!=null?B:"min(400px, calc(100vw - 24px))";W.style.width=_,W.style.maxWidth=_}if(!u){let B=window.innerHeight,_=64,Me=(N=(X=t.launcher)==null?void 0:X.heightOffset)!=null?N:0,ge=Math.max(200,B-_),re=Math.min(640,ge),Ie=Math.max(200,re-Me);W.style.height=`${Ie}px`}};ye(),window.addEventListener("resize",ye),$e.push(()=>window.removeEventListener("resize",ye)),We=U.scrollTop;let Ae=()=>{let a=U.scrollTop,u=U.scrollHeight,T=U.clientHeight,O=u-a-T,R=Math.abs(a-We);if(We=a,!Ue&&!(R<=Bt)){if(!Ke&&O<gt){Se=!1,Ke=!0;return}Ke&&O>gt&&(Se=!0,ke=Date.now()+St,Ke=!1)}};U.addEventListener("scroll",Ae,{passive:!0}),$e.push(()=>U.removeEventListener("scroll",Ae)),$e.push(()=>{J&&cancelAnimationFrame(J)});let Xe=()=>{D&&(qe&&(D.removeEventListener("click",qe),qe=null),w?(D.style.display="",qe=()=>{x=!1,_t()},D.addEventListener("click",qe)):D.style.display="none")};Xe(),(()=>{let{clearChatButton:a}=le;a&&a.addEventListener("click",()=>{j.clearMessages();try{localStorage.removeItem(sn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${sn}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==sn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.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(O=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",O)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}l={},b.syncFromMetadata()})})(),Ye.addEventListener("submit",rn),Z.addEventListener("keydown",an),$e.push(()=>{Ye.removeEventListener("submit",rn),Z.removeEventListener("keydown",an)}),$e.push(()=>{j.cancel()}),h?$e.push(()=>{h==null||h.destroy()}):k&&$e.push(()=>{k==null||k.remove()});let xe={update(a){var ln,zt,Xt,ps,us,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,ks,Hs,Rs,Is,$s,Ps,Os,Ns,Fs,Ds,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs,Qs,eo,to,no,so,oo,ro,io,ao,lo,co,po;let u=t.toolCall;t={...t,...a},wt(),_n(n,t);let T=gn.getForInstance(t.plugins);if(o.length=0,o.push(...T),w=(zt=(ln=t.launcher)==null?void 0:ln.enabled)!=null?zt:!0,q=(ps=(Xt=t.launcher)==null?void 0:Xt.autoExpand)!=null?ps:!1,S=(gs=(us=t.features)==null?void 0:us.showReasoning)!=null?gs:!0,Y=(ms=(hs=t.features)==null?void 0:hs.showToolCalls)!=null?ms:!0,((fs=t.launcher)==null?void 0:fs.enabled)===!1&&h&&(h.destroy(),h=null),((ws=t.launcher)==null?void 0:ws.enabled)===!1&&k&&(k.remove(),k=null),((ys=t.launcher)==null?void 0:ys.enabled)!==!1&&!h&&!k){let E=o.find(fe=>fe.renderLauncher);if(E!=null&&E.renderLauncher){let fe=E.renderLauncher({config:t,defaultRenderer:()=>pn(t,C).element,onToggle:C});fe&&(k=fe,n.appendChild(k))}k||(h=pn(t,C),n.appendChild(h.element))}h&&h.update(t),mt&&((vs=t.launcher)==null?void 0:vs.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((bs=t.launcher)==null?void 0:bs.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),w!==m?w?st(q,"auto"):(x=!0,_t()):q!==F&&st(q,"auto"),F=q,m=w,ye(),Xe(),JSON.stringify(a.toolCall)!==JSON.stringify(u)&&j&&jt(z,j.getMessages(),I);let H=(xs=t.launcher)!=null?xs:{},v=(Cs=H.headerIconHidden)!=null?Cs:!1,X=H.headerIconName,N=(Ss=H.headerIconSize)!=null?Ss:"48px";if(me){let E=G.querySelector(".tvw-border-b-cw-divider"),fe=E==null?void 0:E.querySelector(".tvw-flex-col");if(v)me.style.display="none",E&&fe&&!E.contains(fe)&&E.insertBefore(fe,E.firstChild);else{if(me.style.display="",me.style.height=N,me.style.width=N,E&&fe&&(E.contains(me)?me.nextSibling!==fe&&(me.remove(),E.insertBefore(me,fe)):E.insertBefore(me,fe)),X){let Ee=parseFloat(N)||24,Ce=ve(X,Ee*.6,"#ffffff",2);Ce?me.replaceChildren(Ce):me.textContent=(As=H.agentIconText)!=null?As:"\u{1F4AC}"}else if(H.iconUrl){let Ee=me.querySelector("img");if(Ee)Ee.src=H.iconUrl,Ee.style.height=N,Ee.style.width=N;else{let Ce=document.createElement("img");Ce.src=H.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=N,Ce.style.width=N,me.replaceChildren(Ce)}}else{let Ee=me.querySelector("svg"),Ce=me.querySelector("img");(Ee||Ce)&&me.replaceChildren(),me.textContent=(Ts=H.agentIconText)!=null?Ts:"\u{1F4AC}"}let te=me.querySelector("img");te&&(te.style.height=N,te.style.width=N)}}if(D){let E=(Es=H.closeButtonSize)!=null?Es:"32px",fe=(Ws=H.closeButtonPlacement)!=null?Ws:"inline";D.style.height=E,D.style.width=E;let{closeButtonWrapper:te}=le,Ee=fe==="top-right",Ce=te==null?void 0:te.classList.contains("tvw-absolute");if(te&&Ee!==Ce)if(te.remove(),Ee)te.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",G.style.position="relative",G.appendChild(te);else{let he=(Ls=(Ms=H.clearChat)==null?void 0:Ms.placement)!=null?Ls:"inline",Ge=(ks=(Bs=H.clearChat)==null?void 0:Bs.enabled)!=null?ks:!0;te.className=Ge&&he==="inline"?"":"tvw-ml-auto";let Ze=G.querySelector(".tvw-border-b-cw-divider");Ze&&Ze.appendChild(te)}if(H.closeButtonColor?(D.style.color=H.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),H.closeButtonBackgroundColor?(D.style.backgroundColor=H.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),H.closeButtonBorderWidth||H.closeButtonBorderColor){let he=H.closeButtonBorderWidth||"0px",Ge=H.closeButtonBorderColor||"transparent";D.style.border=`${he} solid ${Ge}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");H.closeButtonBorderRadius?(D.style.borderRadius=H.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),H.closeButtonPaddingX?(D.style.paddingLeft=H.closeButtonPaddingX,D.style.paddingRight=H.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),H.closeButtonPaddingY?(D.style.paddingTop=H.closeButtonPaddingY,D.style.paddingBottom=H.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Ve=(Hs=H.closeButtonIconName)!=null?Hs:"x",je=(Rs=H.closeButtonIconText)!=null?Rs:"\xD7";D.innerHTML="";let ut=ve(Ve,"20px",H.closeButtonColor||"",2);ut?D.appendChild(ut):D.textContent=je;let Nt=(Is=H.closeButtonTooltipText)!=null?Is:"Close chat",Te=($s=H.closeButtonShowTooltip)!=null?$s:!0;if(D.setAttribute("aria-label",Nt),te&&(te._cleanupTooltip&&(te._cleanupTooltip(),delete te._cleanupTooltip),Te&&Nt)){let he=null,Ge=()=>{if(he||!D)return;he=p("div","tvw-clear-chat-tooltip"),he.textContent=Nt;let Vt=p("div");Vt.className="tvw-clear-chat-tooltip-arrow",he.appendChild(Vt);let Fn=D.getBoundingClientRect();he.style.position="fixed",he.style.left=`${Fn.left+Fn.width/2}px`,he.style.top=`${Fn.top-8}px`,he.style.transform="translate(-50%, -100%)",document.body.appendChild(he)},Ze=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};te.addEventListener("mouseenter",Ge),te.addEventListener("mouseleave",Ze),D.addEventListener("focus",Ge),D.addEventListener("blur",Ze),te._cleanupTooltip=()=>{Ze(),te&&(te.removeEventListener("mouseenter",Ge),te.removeEventListener("mouseleave",Ze)),D&&(D.removeEventListener("focus",Ge),D.removeEventListener("blur",Ze))}}}let{clearChatButton:B,clearChatButtonWrapper:_}=le;if(B){let E=(Ps=H.clearChat)!=null?Ps:{},fe=(Os=E.enabled)!=null?Os:!0,te=(Ns=E.placement)!=null?Ns:"inline";if(_){_.style.display=fe?"":"none";let Ee=te==="top-right",Ce=_.classList.contains("tvw-absolute");if(Ee!==Ce&&fe){if(_.remove(),Ee)_.className="tvw-absolute tvw-top-4 tvw-z-50",_.style.right="48px",G.style.position="relative",G.appendChild(_);else{_.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",_.style.right="";let je=G.querySelector(".tvw-border-b-cw-divider"),ut=le.closeButtonWrapper;je&&ut&&ut.parentElement===je?je.insertBefore(_,ut):je&&je.appendChild(_)}let Ve=le.closeButtonWrapper;Ve&&!Ve.classList.contains("tvw-absolute")&&(Ee?Ve.classList.add("tvw-ml-auto"):Ve.classList.remove("tvw-ml-auto"))}}if(fe){let Ee=(Fs=E.size)!=null?Fs:"32px";B.style.height=Ee,B.style.width=Ee;let Ce=(Ds=E.iconName)!=null?Ds:"refresh-cw",Ve=(js=E.iconColor)!=null?js:"";B.innerHTML="";let je=ve(Ce,"20px",Ve||"",2);if(je&&B.appendChild(je),Ve?(B.style.color=Ve,B.classList.remove("tvw-text-cw-muted")):(B.style.color="",B.classList.add("tvw-text-cw-muted")),E.backgroundColor?(B.style.backgroundColor=E.backgroundColor,B.classList.remove("hover:tvw-bg-gray-100")):(B.style.backgroundColor="",B.classList.add("hover:tvw-bg-gray-100")),E.borderWidth||E.borderColor){let Te=E.borderWidth||"0px",he=E.borderColor||"transparent";B.style.border=`${Te} solid ${he}`,B.classList.remove("tvw-border-none")}else B.style.border="",B.classList.add("tvw-border-none");E.borderRadius?(B.style.borderRadius=E.borderRadius,B.classList.remove("tvw-rounded-full")):(B.style.borderRadius="",B.classList.add("tvw-rounded-full")),E.paddingX?(B.style.paddingLeft=E.paddingX,B.style.paddingRight=E.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),E.paddingY?(B.style.paddingTop=E.paddingY,B.style.paddingBottom=E.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let ut=(_s=E.tooltipText)!=null?_s:"Clear chat",Nt=(qs=E.showTooltip)!=null?qs:!0;if(B.setAttribute("aria-label",ut),_&&(_._cleanupTooltip&&(_._cleanupTooltip(),delete _._cleanupTooltip),Nt&&ut)){let Te=null,he=()=>{if(Te||!B)return;Te=p("div","tvw-clear-chat-tooltip"),Te.textContent=ut;let Ze=p("div");Ze.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(Ze);let Vt=B.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${Vt.left+Vt.width/2}px`,Te.style.top=`${Vt.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},Ge=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};_.addEventListener("mouseenter",he),_.addEventListener("mouseleave",Ge),B.addEventListener("focus",he),B.addEventListener("blur",Ge),_._cleanupTooltip=()=>{Ge(),_&&(_.removeEventListener("mouseenter",he),_.removeEventListener("mouseleave",Ge)),B&&(B.removeEventListener("focus",he),B.removeEventListener("blur",Ge))}}}}let Me=t.actionParsers&&t.actionParsers.length?t.actionParsers:[hn],ge=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Jt.message,Jt.messageAndClick];b=mn({parsers:Me,handlers:ge,getMetadata:g,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),I=Ro(t,b),j.updateConfig(t),jt(z,j.getMessages(),I),tt.render(t.suggestionChips,j,Z,void 0,t.suggestionChipsConfig),on(),Kt(j.isStreaming());let re=((Us=t.voiceRecognition)==null?void 0:Us.enabled)===!0,Ie=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=re&&Ie;if(Ye.classList.remove("tvw-gap-1","tvw-gap-3"),Ye.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),re&&Ie)if(!M||!Be){let E=L(t.voiceRecognition,t.sendButton);E&&(M=E.micButton,Be=E.micButtonWrapper,Ye.insertBefore(Be,Ne),M.addEventListener("click",ot),M.disabled=j.isStreaming())}else{let E=(zs=t.voiceRecognition)!=null?zs:{},fe=(Ys=t.sendButton)!=null?Ys:{},te=(Js=E.iconName)!=null?Js:"mic",Ee=(Ks=fe.size)!=null?Ks:"40px",Ce=(Xs=E.iconSize)!=null?Xs:Ee,Ve=parseFloat(Ce)||24;M.style.width=Ce,M.style.height=Ce,M.style.minWidth=Ce,M.style.minHeight=Ce;let je=(Gs=(Vs=E.iconColor)!=null?Vs:fe.textColor)!=null?Gs:"currentColor";M.innerHTML="";let ut=ve(te,Ve,je,2);ut?M.appendChild(ut):M.textContent="\u{1F3A4}";let Nt=(Zs=E.backgroundColor)!=null?Zs:fe.backgroundColor;Nt?(M.style.backgroundColor=Nt,M.classList.remove("tvw-bg-cw-primary")):(M.style.backgroundColor="",M.classList.add("tvw-bg-cw-primary")),je?(M.style.color=je,M.classList.remove("tvw-text-white")):!je&&!fe.textColor&&(M.style.color="",M.classList.add("tvw-text-white")),E.borderWidth?(M.style.borderWidth=E.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),E.borderColor?M.style.borderColor=E.borderColor:M.style.borderColor="",E.paddingX?(M.style.paddingLeft=E.paddingX,M.style.paddingRight=E.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),E.paddingY?(M.style.paddingTop=E.paddingY,M.style.paddingBottom=E.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Te=Be==null?void 0:Be.querySelector(".tvw-send-button-tooltip"),he=(Qs=E.tooltipText)!=null?Qs:"Start voice recognition";if(((eo=E.showTooltip)!=null?eo:!1)&&he)if(Te)Te.textContent=he,Te.style.display="";else{let Ze=document.createElement("div");Ze.className="tvw-send-button-tooltip",Ze.textContent=he,Be==null||Be.insertBefore(Ze,M)}else Te&&(Te.style.display="none");Be.style.display="",M.disabled=j.isStreaming()}else M&&Be&&(Be.style.display="none",K&&ce());let ie=(to=t.sendButton)!=null?to:{},ct=(no=ie.useIcon)!=null?no:!1,Rt=(so=ie.iconText)!=null?so:"\u2191",It=ie.iconName,Mt=(oo=ie.tooltipText)!=null?oo:"Send message",qt=(ro=ie.showTooltip)!=null?ro:!1,$t=(io=ie.size)!=null?io:"40px",Ut=ie.backgroundColor,pt=ie.textColor;if(ct){if($.style.width=$t,$.style.height=$t,$.style.minWidth=$t,$.style.minHeight=$t,$.style.fontSize="18px",$.style.lineHeight="1",$.innerHTML="",It){let E=parseFloat($t)||24,fe=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",te=ve(It,E,fe,2);te?($.appendChild(te),$.style.color=fe):($.textContent=Rt,pt?$.style.color=pt:$.classList.add("tvw-text-white"))}else $.textContent=Rt,pt?$.style.color=pt:$.classList.add("tvw-text-white");$.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Ut?($.style.backgroundColor=Ut,$.classList.remove("tvw-bg-cw-primary")):$.classList.add("tvw-bg-cw-primary")}else $.textContent=(lo=(ao=t.copy)==null?void 0:ao.sendButtonLabel)!=null?lo:"Send",$.style.width="",$.style.height="",$.style.minWidth="",$.style.minHeight="",$.style.fontSize="",$.style.lineHeight="",$.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",Ut?($.style.backgroundColor=Ut,$.classList.remove("tvw-bg-cw-accent")):$.classList.add("tvw-bg-cw-accent"),pt?$.style.color=pt:$.classList.add("tvw-text-white");ie.borderWidth?($.style.borderWidth=ie.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),ie.borderColor?$.style.borderColor=ie.borderColor:$.style.borderColor="",ie.paddingX?($.style.paddingLeft=ie.paddingX,$.style.paddingRight=ie.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),ie.paddingY?($.style.paddingTop=ie.paddingY,$.style.paddingBottom=ie.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let Pt=Ne==null?void 0:Ne.querySelector(".tvw-send-button-tooltip");if(qt&&Mt)if(Pt)Pt.textContent=Mt,Pt.style.display="";else{let E=document.createElement("div");E.className="tvw-send-button-tooltip",E.textContent=Mt,Ne==null||Ne.insertBefore(E,$)}else Pt&&(Pt.style.display="none");let Ot=(co=t.statusIndicator)!=null?co:{},vn=(po=Ot.visible)!=null?po:!0;if(Qe.style.display=vn?"":"none",j){let E=j.getStatus(),fe=te=>{var Ee,Ce,Ve,je;return te==="idle"?(Ee=Ot.idleText)!=null?Ee:ze.idle:te==="connecting"?(Ce=Ot.connectingText)!=null?Ce:ze.connecting:te==="connected"?(Ve=Ot.connectedText)!=null?Ve:ze.connected:te==="error"?(je=Ot.errorText)!=null?je:ze.error:ze[te]};Qe.textContent=fe(E)}},open(){w&&st(!0,"api")},close(){w&&st(!1,"api")},toggle(){w&&st(!x,"api")},clearChat(){j.clearMessages();try{localStorage.removeItem(sn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${sn}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==sn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(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={},b.syncFromMetadata()},setMessage(a){return!Z||j.isStreaming()?!1:(!x&&w&&st(!0,"system"),Z.value=a,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(j.isStreaming())return!1;let u=(a==null?void 0:a.trim())||Z.value.trim();return u?(!x&&w&&st(!0,"system"),Z.value="",j.sendMessage(u),!0):!1},startVoiceRecognition(){return K||j.isStreaming()||!Pe()?!1:(!x&&w&&st(!0,"system"),de.manuallyDeactivated=!1,be(),Oe("user"),!0)},stopVoiceRecognition(){return K?(de.manuallyDeactivated=!0,be(),ce("user"),!0):!1},injectTestMessage(a){!x&&w&&st(!0,"system"),j.injectTestEvent(a)},getMessages(){return j.getMessages()},getStatus(){return j.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,u){return s.on(a,u)},off(a,u){s.off(a,u)},isOpen(){return w&&x},isVoiceActive(){return de.active},getState(){return{open:w&&x,launcherEnabled:w,voiceActive:de.active,streaming:j.isStreaming()}},destroy(){$e.forEach(a=>a()),Q.remove(),h==null||h.destroy(),k==null||k.remove(),qe&&D.removeEventListener("click",qe)}};if((((cs=r==null?void 0:r.debugTools)!=null?cs:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,u={controller:xe,getMessages:xe.getMessages,getStatus:xe.getStatus,getMetadata:xe.getPersistentMetadata,updateMetadata:xe.updatePersistentMetadata,clearHistory:()=>xe.clearChat(),setVoiceActive:T=>T?xe.startVoiceRecognition():xe.stopVoiceRecognition()};window.AgentWidgetBrowser=u,$e.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}return xe};var ns={},dr=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},cr=()=>{try{if(typeof ns!="undefined"&&ns.url)return new URL("../widget.css",ns.url).href}catch{}return null},Io=n=>{let e=cr(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let o=t.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},ss=n=>{var g,d,A,f;let e=dr(n.target),r=document.createElement("div");r.className="vanilla-agent-host";let t=(A=(d=(g=n.config)==null?void 0:g.launcher)==null?void 0:d.enabled)!=null?A:!0;t||(r.style.height="100%"),e.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let b=r.attachShadow({mode:"open"});i=b,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),b.appendChild(s),Io(b)}else i=r,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),Io(r);let l=Pn(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let c={...l,host:r,destroy(){l.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=c),c};function pr(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function On(n){var e,r;return(r=(e=n.parserType)!=null?e:pr(n.streamParser))!=null?r:"plain"}function $o(n,e="esm"){let r={...n};return delete r.postprocessMessage,delete r.initialMessages,e==="esm"?ur(r):e==="script-installer"?mr(r):e==="script-advanced"?wr(r):e==="react-component"?gr(r):e==="react-advanced"?hr(r):fr(r)}function ur(n){let e=On(n),r=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
57
- `)}function gr(n){let e=On(n),r=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
58
- `)}function hr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"?e.push(` ${r}: ${t},`):typeof t=="number"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,t])=>{e.push(` ${r}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
59
- `)}function mr(n){let e=On(n),r=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
60
- `)}function fr(n){let e=On(n),r=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
61
- `)}function wr(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"?e.push(` ${r}: ${t},`):typeof t=="number"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,t])=>{e.push(` ${r}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" }),"),e.push(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
62
- `)}var yr=ss;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_WIDGET_CONFIG,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,generateCodeSnippet,getHeaderLayout,hasComponentDirective,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,pluginRegistry,renderComponentDirective});
60
+ `}if(!he){let Jt="max-height: -moz-available !important; max-height: stretch !important;",Vt=i?"":"padding-top: 1.25em !important;";B.style.cssText+=Jt+Vt}};wt(),Yn(n,t);let $e=[],ot=Ro(ne),Ue=null,I,dt=!1,Se=!0,Oe=0,te=0,Ae=null,Te=!1,ze=0,Je=!1,xt=125,Bt=2e3,yt=5,Et=50,St=new Map,ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Ht=(ms=(hs=t.voiceRecognition)==null?void 0:hs.autoResume)!=null?ms:!1,Le=i=>{o.emit("voice:state",{active:ye.active,source:i,timestamp:Date.now()})},Ye=()=>{f(i=>({...i,voiceState:{active:ye.active,timestamp:Date.now(),manuallyDeactivated:ye.manuallyDeactivated}}))},At=()=>{var O,k;if(((O=t.voiceRecognition)==null?void 0:O.enabled)===!1)return;let i=as(l.voiceState),u=!!i.active,E=Number((k=i.timestamp)!=null?k:0);ye.manuallyDeactivated=!!i.manuallyDeactivated,u&&Date.now()-E<wr&&setTimeout(()=>{ye.active||(ye.manuallyDeactivated=!1,Ne("restore"))},1e3)},Dt=()=>I?Do(I.getMessages()).filter(i=>!i.__skipPersist):[];function Mt(i){if(!(a!=null&&a.save))return;let E={messages:i?Do(i):I?Dt():[],metadata:l};try{let O=a.save(E);O instanceof Promise&&O.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(O){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",O)}}let _t=(i=!1)=>{if(!Se)return;let u=Date.now();Te&&u<ze&&!i||(Te&&u>=ze&&(Te=!1),!(!i&&!dt)&&(u-te<xt||(te=u,Ae&&cancelAnimationFrame(Ae),Ae=requestAnimationFrame(()=>{Te||!Se||(Je=!0,K.scrollTop=K.scrollHeight,Oe=K.scrollTop,requestAnimationFrame(()=>{Je=!1}),Ae=null)}))))},Wt=null,wn=()=>B.querySelector("#vanilla-agent-scroll-container")||K,yn=(i,u=500)=>{let E=i.scrollTop,O=i.clientHeight,k=i.scrollHeight,ee=k-E;if(E+O>=k-2||Math.abs(ee)<5)return;Wt!==null&&(cancelAnimationFrame(Wt),Wt=null);let T=performance.now(),G=R=>1-Math.pow(1-R,3),z=R=>{let Y=i.scrollHeight;Y!==k&&(k=Y,ee=k-E);let Be=R-T,he=Math.min(Be/u,1),ae=G(he),Ie=E+ee*ae;i.scrollTop=Ie,he<1?Wt=requestAnimationFrame(z):(i.scrollTop=i.scrollHeight,Wt=null)};Wt=requestAnimationFrame(z)},vn=i=>{let u=new Map;i.forEach(E=>{let O=St.get(E.id);u.set(E.id,{streaming:E.streaming,role:E.role}),!O&&E.role==="assistant"&&o.emit("assistant:message",E),E.role==="assistant"&&(O!=null&&O.streaming)&&E.streaming===!1&&o.emit("assistant:complete",E)}),St.clear(),u.forEach((E,O)=>{St.set(O,E)})},jt=(i,u,E)=>{i.innerHTML="";let O=document.createDocumentFragment();u.forEach(T=>{var Be,he;let G=null,z=r.find(ae=>!!(T.variant==="reasoning"&&ae.renderReasoning||T.variant==="tool"&&ae.renderToolCall||!T.variant&&ae.renderMessage)),R=(Be=t.layout)==null?void 0:Be.messages;if(z)if(T.variant==="reasoning"&&T.reasoning&&z.renderReasoning){if(!v)return;G=z.renderReasoning({message:T,defaultRenderer:()=>es(T),config:t})}else if(T.variant==="tool"&&T.toolCall&&z.renderToolCall){if(!D)return;G=z.renderToolCall({message:T,defaultRenderer:()=>ns(T,t),config:t})}else z.renderMessage&&(G=z.renderMessage({message:T,defaultRenderer:()=>{let ae=tn(T,E,R,t.messageActions,x);return T.role!=="user"&&ss(ae,T,t,I),ae},config:t}));if(!G&&T.role==="assistant"&&!T.variant&&t.enableComponentStreaming!==!1&&Fn(T)){let Ie=Nn(T);if(Ie){let ct=$n(Ie,{config:t,message:T,transform:E});if(ct){let le=document.createElement("div");if(le.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(" "),le.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let ut=document.createElement("div");ut.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ut.innerHTML=E({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),le.appendChild(ut)}le.appendChild(ct),G=le}}}if(!G)if(T.variant==="reasoning"&&T.reasoning){if(!v)return;G=es(T)}else if(T.variant==="tool"&&T.toolCall){if(!D)return;G=ns(T,t)}else{let ae=(he=t.layout)==null?void 0:he.messages;ae!=null&&ae.renderUserMessage&&T.role==="user"?G=ae.renderUserMessage({message:T,config:t,streaming:!!T.streaming}):ae!=null&&ae.renderAssistantMessage&&T.role==="assistant"?G=ae.renderAssistantMessage({message:T,config:t,streaming:!!T.streaming}):G=tn(T,E,ae,t.messageActions,x),T.role!=="user"&&G&&ss(G,T,t,I)}let Y=document.createElement("div");Y.className="tvw-flex",T.role==="user"&&Y.classList.add("tvw-justify-end"),Y.appendChild(G),O.appendChild(Y)});let k=u.some(T=>T.role==="assistant"&&T.streaming),ee=u[u.length-1],N=(ee==null?void 0:ee.role)==="assistant"&&!ee.streaming;if(dt&&u.some(T=>T.role==="user")&&!k&&!N){let T=gn(),G=document.createElement("div");G.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(" "),G.appendChild(T);let z=document.createElement("div");z.className="tvw-flex",z.appendChild(G),O.appendChild(z)}i.appendChild(O),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let T=wn();yn(T)})})},qt=()=>{g&&(b?(B.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-95","tvw-opacity-0"),_.classList.add("tvw-scale-100","tvw-opacity-100"),y?y.element.style.display="none":F&&(F.style.display="none")):(B.classList.add("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-100","tvw-opacity-100"),_.classList.add("tvw-scale-95","tvw-opacity-0"),y?y.element.style.display="":F&&(F.style.display="")))},Ke=(i,u="user")=>{if(!g||b===i)return;let E=b;b=i,qt(),b&&(be(),_t(!0));let O={open:b,source:u,timestamp:Date.now()};b&&!E?o.emit("widget:opened",O):!b&&E&&o.emit("widget:closed",O),o.emit("widget:state",{open:b,launcherEnabled:g,voiceActive:ye.active,streaming:I.isStreaming()})},Xt=i=>{q.disabled=i,H&&(H.disabled=i),ot.buttons.forEach(u=>{u.disabled=i})},rn=()=>{var k,ee,N,T,G,z,R,Y,Be,he,ae,Ie,ct,le;bt.textContent=(ee=(k=t.copy)==null?void 0:k.welcomeTitle)!=null?ee:"Hello \u{1F44B}",Ct.textContent=(T=(N=t.copy)==null?void 0:N.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",re.placeholder=(z=(G=t.copy)==null?void 0:G.inputPlaceholder)!=null?z:"How can I help...",((Y=(R=t.sendButton)==null?void 0:R.useIcon)!=null?Y:!1)||(q.textContent=(he=(Be=t.copy)==null?void 0:Be.sendButtonLabel)!=null?he:"Send");let u=(Ie=(ae=t.theme)==null?void 0:ae.inputFontFamily)!=null?Ie:"sans-serif",E=(le=(ct=t.theme)==null?void 0:ct.inputFontWeight)!=null?le:"400",O=ut=>{switch(ut){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'}};re.style.fontFamily=O(u),re.style.fontWeight=E};I=new Zt(t,{onMessagesChanged(i){jt(Q,i,W),I&&(i.some(O=>O.role==="user")?ot.render([],I,re,i):ot.render(t.suggestionChips,I,re,i,t.suggestionChipsConfig)),_t(!dt),vn(i);let u=[...i].reverse().find(E=>E.role==="user");ye.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Mt(i)},onStatusChanged(i){var O;let u=(O=t.statusIndicator)!=null?O:{},E=k=>{var ee,N,T,G;return k==="idle"?(ee=u.idleText)!=null?ee:Xe.idle:k==="connecting"?(N=u.connectingText)!=null?N:Xe.connecting:k==="connected"?(T=u.connectedText)!=null?T:Xe.connected:k==="error"?(G=u.errorText)!=null?G:Xe.error:Xe[k]};nt.textContent=E(i)},onStreamingChanged(i){dt=i,Xt(i),I&&jt(Q,I.getMessages(),W),i||_t(!0)}}),p&&p.then(i=>{var u;i&&(i.metadata&&(l=as(i.metadata),C.syncFromMetadata()),(u=i.messages)!=null&&u.length&&I.hydrateMessages(i.messages))}).catch(i=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)});let an=i=>{i.preventDefault();let u=re.value.trim();u&&(re.value="",I.sendMessage(u))},ln=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),q.click())},A=null,V=!1,ie=null,ve=null,Fe=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ne=(i="user")=>{var ee,N,T,G;if(V||I.isStreaming())return;let u=Fe();if(!u)return;A=new u;let O=(N=((ee=t.voiceRecognition)!=null?ee:{}).pauseDuration)!=null?N:2e3;A.continuous=!0,A.interimResults=!0,A.lang="en-US";let k=re.value;A.onresult=z=>{let R="",Y="";for(let he=0;he<z.results.length;he++){let ae=z.results[he],Ie=ae[0].transcript;ae.isFinal?R+=Ie+" ":Y=Ie}let Be=k+R+Y;re.value=Be,ie&&clearTimeout(ie),(R||Y)&&(ie=window.setTimeout(()=>{let he=re.value.trim();he&&A&&V&&(ue(),re.value="",I.sendMessage(he,{viaVoice:!0}))},O))},A.onerror=z=>{z.error!=="no-speech"&&ue()},A.onend=()=>{if(V){let z=re.value.trim();z&&z!==k.trim()&&(re.value="",I.sendMessage(z,{viaVoice:!0})),ue()}};try{if(A.start(),V=!0,ye.active=!0,i!=="system"&&(ye.manuallyDeactivated=!1),Le(i),Ye(),H){ve={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor};let z=(T=t.voiceRecognition)!=null?T:{},R=(G=z.recordingBackgroundColor)!=null?G:"#ef4444",Y=z.recordingIconColor,Be=z.recordingBorderColor;if(H.classList.add("tvw-voice-recording"),H.style.backgroundColor=R,Y){H.style.color=Y;let he=H.querySelector("svg");he&&he.setAttribute("stroke",Y)}Be&&(H.style.borderColor=Be),H.setAttribute("aria-label","Stop voice recognition")}}catch{ue("system")}},ue=(i="user")=>{if(V){if(V=!1,ie&&(clearTimeout(ie),ie=null),A){try{A.stop()}catch{}A=null}if(ye.active=!1,Le(i),Ye(),H){if(H.classList.remove("tvw-voice-recording"),ve){H.style.backgroundColor=ve.backgroundColor,H.style.color=ve.color,H.style.borderColor=ve.borderColor;let u=H.querySelector("svg");u&&u.setAttribute("stroke",ve.color||"currentColor"),ve=null}H.setAttribute("aria-label","Start voice recognition")}}},P=(i,u)=>{var Ie,ct,le,ut,Pt,Rt,kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let O=m("div","tvw-send-button-wrapper"),k=m("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");k.type="button",k.setAttribute("aria-label","Start voice recognition");let ee=(Ie=i==null?void 0:i.iconName)!=null?Ie:"mic",N=(ct=u==null?void 0:u.size)!=null?ct:"40px",T=(le=i==null?void 0:i.iconSize)!=null?le:N,G=parseFloat(T)||24,z=(ut=i==null?void 0:i.backgroundColor)!=null?ut:u==null?void 0:u.backgroundColor,R=(Pt=i==null?void 0:i.iconColor)!=null?Pt:u==null?void 0:u.textColor;k.style.width=T,k.style.height=T,k.style.minWidth=T,k.style.minHeight=T,k.style.fontSize="18px",k.style.lineHeight="1";let Y=R||"currentColor",Be=ce(ee,G,Y,1.5);Be?(k.appendChild(Be),k.style.color=Y):(k.textContent="\u{1F3A4}",k.style.color=Y),z?k.style.backgroundColor=z:k.classList.add("tvw-bg-cw-primary"),R?k.style.color=R:!R&&!(u!=null&&u.textColor)&&k.classList.add("tvw-text-white"),i!=null&&i.borderWidth&&(k.style.borderWidth=i.borderWidth,k.style.borderStyle="solid"),i!=null&&i.borderColor&&(k.style.borderColor=i.borderColor),i!=null&&i.paddingX&&(k.style.paddingLeft=i.paddingX,k.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(k.style.paddingTop=i.paddingY,k.style.paddingBottom=i.paddingY),O.appendChild(k);let he=(Rt=i==null?void 0:i.tooltipText)!=null?Rt:"Start voice recognition";if(((kt=i==null?void 0:i.showTooltip)!=null?kt:!1)&&he){let Ut=m("div","tvw-send-button-tooltip");Ut.textContent=he,O.appendChild(Ut)}return{micButton:k,micButtonWrapper:O}},rt=()=>{if(V){let i=re.value.trim();ye.manuallyDeactivated=!0,Ye(),ue("user"),i&&(re.value="",I.sendMessage(i))}else ye.manuallyDeactivated=!1,Ye(),Ne("user")};H&&(H.addEventListener("click",rt),$e.push(()=>{ue("system"),H&&H.removeEventListener("click",rt)}));let se=o.on("assistant:complete",()=>{Ht&&(ye.active||ye.manuallyDeactivated||Ht==="assistant"&&!ye.lastUserMessageWasVoice||setTimeout(()=>{!ye.active&&!ye.manuallyDeactivated&&Ne("auto")},600))});$e.push(se);let M=()=>{Ke(!b,"user")},y=null,F=null;if(g){let i=r.find(u=>u.renderLauncher);if(i!=null&&i.renderLauncher){let u=i.renderLauncher({config:t,defaultRenderer:()=>pn(t,M).element,onToggle:M});u&&(F=u)}F||(y=pn(t,M))}y?n.appendChild(y.element):F&&n.appendChild(F),qt(),ot.render(t.suggestionChips,I,re,void 0,t.suggestionChipsConfig),rn(),Xt(I.isStreaming()),_t(!0),At();let be=()=>{var E,O,k,ee,N,T,G,z;let i=(O=(E=t.launcher)==null?void 0:E.sidebarMode)!=null?O:!1,u=i||((ee=(k=t.launcher)==null?void 0:k.fullHeight)!=null?ee:!1);if(!g){_.style.height="",_.style.width="";return}if(!i){let R=(T=(N=t==null?void 0:t.launcher)==null?void 0:N.width)!=null?T:t==null?void 0:t.launcherWidth,Y=R!=null?R:"min(400px, calc(100vw - 24px))";_.style.width=Y,_.style.maxWidth=Y}if(!u){let R=window.innerHeight,Y=64,Be=(z=(G=t.launcher)==null?void 0:G.heightOffset)!=null?z:0,he=Math.max(200,R-Y),ae=Math.min(640,he),Ie=Math.max(200,ae-Be);_.style.height=`${Ie}px`}};be(),window.addEventListener("resize",be),$e.push(()=>window.removeEventListener("resize",be)),Oe=K.scrollTop;let Ee=()=>{let i=K.scrollTop,u=K.scrollHeight,E=K.clientHeight,O=u-i-E,k=Math.abs(i-Oe);if(Oe=i,!Je&&!(k<=yt)){if(!Se&&O<Et){Te=!1,Se=!0;return}Se&&O>Et&&(Te=!0,ze=Date.now()+Bt,Se=!1)}};K.addEventListener("scroll",Ee,{passive:!0}),$e.push(()=>K.removeEventListener("scroll",Ee)),$e.push(()=>{Ae&&cancelAnimationFrame(Ae)});let Ze=()=>{J&&(Ue&&(J.removeEventListener("click",Ue),Ue=null),g?(J.style.display="",Ue=()=>{b=!1,qt()},J.addEventListener("click",Ue)):J.style.display="none")};Ze(),(()=>{let{clearChatButton:i}=Z;i&&i.addEventListener("click",()=>{I.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let u=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),a!=null&&a.clear)try{let E=a.clear();E instanceof Promise&&E.catch(O=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",O)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},C.syncFromMetadata()})})(),Ve.addEventListener("submit",an),re.addEventListener("keydown",ln),$e.push(()=>{Ve.removeEventListener("submit",an),re.removeEventListener("keydown",ln)}),$e.push(()=>{I.cancel()}),y?$e.push(()=>{y==null||y.destroy()}):F&&$e.push(()=>{F==null||F.remove()});let Ce={update(i){var dn,Jt,Vt,ws,ys,vs,bs,Cs,xs,Ss,As,Ts,Es,Ms,Ws,ks,Ls,Bs,Hs,Ps,Rs,Is,$s,Fs,Ns,Os,Ds,_s,js,qs,Us,zs,Js,Ys,Ks,Xs,Vs,Gs,Zs,Qs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,ho,mo,fo,wo;let u=t.toolCall;t={...t,...i},wt(),Yn(n,t);let E=hn.getForInstance(t.plugins);if(r.length=0,r.push(...E),g=(Jt=(dn=t.launcher)==null?void 0:dn.enabled)!=null?Jt:!0,U=(ws=(Vt=t.launcher)==null?void 0:Vt.autoExpand)!=null?ws:!1,v=(vs=(ys=t.features)==null?void 0:ys.showReasoning)!=null?vs:!0,D=(Cs=(bs=t.features)==null?void 0:bs.showToolCalls)!=null?Cs:!0,((xs=t.launcher)==null?void 0:xs.enabled)===!1&&y&&(y.destroy(),y=null),((Ss=t.launcher)==null?void 0:Ss.enabled)===!1&&F&&(F.remove(),F=null),((As=t.launcher)==null?void 0:As.enabled)!==!1&&!y&&!F){let L=r.find(we=>we.renderLauncher);if(L!=null&&L.renderLauncher){let we=L.renderLauncher({config:t,defaultRenderer:()=>pn(t,M).element,onToggle:M});we&&(F=we,n.appendChild(F))}F||(y=pn(t,M),n.appendChild(y.element))}y&&y.update(t),mt&&((Ts=t.launcher)==null?void 0:Ts.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((Es=t.launcher)==null?void 0:Es.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),g!==h?g?Ke(U,"auto"):(b=!0,qt()):U!==$&&Ke(U,"auto"),$=U,h=g,be(),Ze(),JSON.stringify(i.toolCall)!==JSON.stringify(u)&&I&&jt(Q,I.getMessages(),W);let N=(Ms=t.launcher)!=null?Ms:{},T=(Ws=N.headerIconHidden)!=null?Ws:!1,G=N.headerIconName,z=(ks=N.headerIconSize)!=null?ks:"48px";if(fe){let L=j.querySelector(".tvw-border-b-cw-divider"),we=L==null?void 0:L.querySelector(".tvw-flex-col");if(T)fe.style.display="none",L&&we&&!L.contains(we)&&L.insertBefore(we,L.firstChild);else{if(fe.style.display="",fe.style.height=z,fe.style.width=z,L&&we&&(L.contains(fe)?fe.nextSibling!==we&&(fe.remove(),L.insertBefore(fe,we)):L.insertBefore(fe,we)),G){let We=parseFloat(z)||24,xe=ce(G,We*.6,"#ffffff",2);xe?fe.replaceChildren(xe):fe.textContent=(Ls=N.agentIconText)!=null?Ls:"\u{1F4AC}"}else if(N.iconUrl){let We=fe.querySelector("img");if(We)We.src=N.iconUrl,We.style.height=z,We.style.width=z;else{let xe=document.createElement("img");xe.src=N.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=z,xe.style.width=z,fe.replaceChildren(xe)}}else{let We=fe.querySelector("svg"),xe=fe.querySelector("img");(We||xe)&&fe.replaceChildren(),fe.textContent=(Bs=N.agentIconText)!=null?Bs:"\u{1F4AC}"}let oe=fe.querySelector("img");oe&&(oe.style.height=z,oe.style.width=z)}}if(J){let L=(Hs=N.closeButtonSize)!=null?Hs:"32px",we=(Ps=N.closeButtonPlacement)!=null?Ps:"inline";J.style.height=L,J.style.width=L;let{closeButtonWrapper:oe}=Z,We=we==="top-right",xe=oe==null?void 0:oe.classList.contains("tvw-absolute");if(oe&&We!==xe)if(oe.remove(),We)oe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",j.style.position="relative",j.appendChild(oe);else{let me=(Is=(Rs=N.clearChat)==null?void 0:Rs.placement)!=null?Is:"inline",et=(Fs=($s=N.clearChat)==null?void 0:$s.enabled)!=null?Fs:!0;oe.className=et&&me==="inline"?"":"tvw-ml-auto";let tt=j.querySelector(".tvw-border-b-cw-divider");tt&&tt.appendChild(oe)}if(N.closeButtonColor?(J.style.color=N.closeButtonColor,J.classList.remove("tvw-text-cw-muted")):(J.style.color="",J.classList.add("tvw-text-cw-muted")),N.closeButtonBackgroundColor?(J.style.backgroundColor=N.closeButtonBackgroundColor,J.classList.remove("hover:tvw-bg-gray-100")):(J.style.backgroundColor="",J.classList.add("hover:tvw-bg-gray-100")),N.closeButtonBorderWidth||N.closeButtonBorderColor){let me=N.closeButtonBorderWidth||"0px",et=N.closeButtonBorderColor||"transparent";J.style.border=`${me} solid ${et}`,J.classList.remove("tvw-border-none")}else J.style.border="",J.classList.add("tvw-border-none");N.closeButtonBorderRadius?(J.style.borderRadius=N.closeButtonBorderRadius,J.classList.remove("tvw-rounded-full")):(J.style.borderRadius="",J.classList.add("tvw-rounded-full")),N.closeButtonPaddingX?(J.style.paddingLeft=N.closeButtonPaddingX,J.style.paddingRight=N.closeButtonPaddingX):(J.style.paddingLeft="",J.style.paddingRight=""),N.closeButtonPaddingY?(J.style.paddingTop=N.closeButtonPaddingY,J.style.paddingBottom=N.closeButtonPaddingY):(J.style.paddingTop="",J.style.paddingBottom="");let Qe=(Ns=N.closeButtonIconName)!=null?Ns:"x",je=(Os=N.closeButtonIconText)!=null?Os:"\xD7";J.innerHTML="";let gt=ce(Qe,"20px",N.closeButtonColor||"",2);gt?J.appendChild(gt):J.textContent=je;let Nt=(Ds=N.closeButtonTooltipText)!=null?Ds:"Close chat",Me=(_s=N.closeButtonShowTooltip)!=null?_s:!0;if(J.setAttribute("aria-label",Nt),oe&&(oe._cleanupTooltip&&(oe._cleanupTooltip(),delete oe._cleanupTooltip),Me&&Nt)){let me=null,et=()=>{if(me||!J)return;me=m("div","tvw-clear-chat-tooltip"),me.textContent=Nt;let Gt=m("div");Gt.className="tvw-clear-chat-tooltip-arrow",me.appendChild(Gt);let Un=J.getBoundingClientRect();me.style.position="fixed",me.style.left=`${Un.left+Un.width/2}px`,me.style.top=`${Un.top-8}px`,me.style.transform="translate(-50%, -100%)",document.body.appendChild(me)},tt=()=>{me&&me.parentNode&&(me.parentNode.removeChild(me),me=null)};oe.addEventListener("mouseenter",et),oe.addEventListener("mouseleave",tt),J.addEventListener("focus",et),J.addEventListener("blur",tt),oe._cleanupTooltip=()=>{tt(),oe&&(oe.removeEventListener("mouseenter",et),oe.removeEventListener("mouseleave",tt)),J&&(J.removeEventListener("focus",et),J.removeEventListener("blur",tt))}}}let{clearChatButton:R,clearChatButtonWrapper:Y}=Z;if(R){let L=(js=N.clearChat)!=null?js:{},we=(qs=L.enabled)!=null?qs:!0,oe=(Us=L.placement)!=null?Us:"inline";if(Y){Y.style.display=we?"":"none";let We=oe==="top-right",xe=Y.classList.contains("tvw-absolute");if(We!==xe&&we){if(Y.remove(),We)Y.className="tvw-absolute tvw-top-4 tvw-z-50",Y.style.right="48px",j.style.position="relative",j.appendChild(Y);else{Y.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Y.style.right="";let je=j.querySelector(".tvw-border-b-cw-divider"),gt=Z.closeButtonWrapper;je&&gt&&gt.parentElement===je?je.insertBefore(Y,gt):je&&je.appendChild(Y)}let Qe=Z.closeButtonWrapper;Qe&&!Qe.classList.contains("tvw-absolute")&&(We?Qe.classList.add("tvw-ml-auto"):Qe.classList.remove("tvw-ml-auto"))}}if(we){let We=(zs=L.size)!=null?zs:"32px";R.style.height=We,R.style.width=We;let xe=(Js=L.iconName)!=null?Js:"refresh-cw",Qe=(Ys=L.iconColor)!=null?Ys:"";R.innerHTML="";let je=ce(xe,"20px",Qe||"",2);if(je&&R.appendChild(je),Qe?(R.style.color=Qe,R.classList.remove("tvw-text-cw-muted")):(R.style.color="",R.classList.add("tvw-text-cw-muted")),L.backgroundColor?(R.style.backgroundColor=L.backgroundColor,R.classList.remove("hover:tvw-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let Me=L.borderWidth||"0px",me=L.borderColor||"transparent";R.style.border=`${Me} solid ${me}`,R.classList.remove("tvw-border-none")}else R.style.border="",R.classList.add("tvw-border-none");L.borderRadius?(R.style.borderRadius=L.borderRadius,R.classList.remove("tvw-rounded-full")):(R.style.borderRadius="",R.classList.add("tvw-rounded-full")),L.paddingX?(R.style.paddingLeft=L.paddingX,R.style.paddingRight=L.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),L.paddingY?(R.style.paddingTop=L.paddingY,R.style.paddingBottom=L.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let gt=(Ks=L.tooltipText)!=null?Ks:"Clear chat",Nt=(Xs=L.showTooltip)!=null?Xs:!0;if(R.setAttribute("aria-label",gt),Y&&(Y._cleanupTooltip&&(Y._cleanupTooltip(),delete Y._cleanupTooltip),Nt&&gt)){let Me=null,me=()=>{if(Me||!R)return;Me=m("div","tvw-clear-chat-tooltip"),Me.textContent=gt;let tt=m("div");tt.className="tvw-clear-chat-tooltip-arrow",Me.appendChild(tt);let Gt=R.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${Gt.left+Gt.width/2}px`,Me.style.top=`${Gt.top-8}px`,Me.style.transform="translate(-50%, -100%)",document.body.appendChild(Me)},et=()=>{Me&&Me.parentNode&&(Me.parentNode.removeChild(Me),Me=null)};Y.addEventListener("mouseenter",me),Y.addEventListener("mouseleave",et),R.addEventListener("focus",me),R.addEventListener("blur",et),Y._cleanupTooltip=()=>{et(),Y&&(Y.removeEventListener("mouseenter",me),Y.removeEventListener("mouseleave",et)),R&&(R.removeEventListener("focus",me),R.removeEventListener("blur",et))}}}}let Be=t.actionParsers&&t.actionParsers.length?t.actionParsers:[mn],he=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick];C=fn({parsers:Be,handlers:he,getMetadata:c,updateMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),W=_o(t,C),I.updateConfig(t),jt(Q,I.getMessages(),W),ot.render(t.suggestionChips,I,re,void 0,t.suggestionChipsConfig),rn(),Xt(I.isStreaming());let ae=((Vs=t.voiceRecognition)==null?void 0:Vs.enabled)===!0,Ie=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ct=ae&&Ie;if(Ve.classList.remove("tvw-gap-1","tvw-gap-3"),Ve.classList.add(ct?"tvw-gap-1":"tvw-gap-3"),ae&&Ie)if(!H||!He){let L=P(t.voiceRecognition,t.sendButton);L&&(H=L.micButton,He=L.micButtonWrapper,Ve.insertBefore(He,qe),H.addEventListener("click",rt),H.disabled=I.isStreaming())}else{let L=(Gs=t.voiceRecognition)!=null?Gs:{},we=(Zs=t.sendButton)!=null?Zs:{},oe=(Qs=L.iconName)!=null?Qs:"mic",We=(eo=we.size)!=null?eo:"40px",xe=(to=L.iconSize)!=null?to:We,Qe=parseFloat(xe)||24;H.style.width=xe,H.style.height=xe,H.style.minWidth=xe,H.style.minHeight=xe;let je=(so=(no=L.iconColor)!=null?no:we.textColor)!=null?so:"currentColor";H.innerHTML="";let gt=ce(oe,Qe,je,2);gt?H.appendChild(gt):H.textContent="\u{1F3A4}";let Nt=(oo=L.backgroundColor)!=null?oo:we.backgroundColor;Nt?(H.style.backgroundColor=Nt,H.classList.remove("tvw-bg-cw-primary")):(H.style.backgroundColor="",H.classList.add("tvw-bg-cw-primary")),je?(H.style.color=je,H.classList.remove("tvw-text-white")):!je&&!we.textColor&&(H.style.color="",H.classList.add("tvw-text-white")),L.borderWidth?(H.style.borderWidth=L.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),L.borderColor?H.style.borderColor=L.borderColor:H.style.borderColor="",L.paddingX?(H.style.paddingLeft=L.paddingX,H.style.paddingRight=L.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),L.paddingY?(H.style.paddingTop=L.paddingY,H.style.paddingBottom=L.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Me=He==null?void 0:He.querySelector(".tvw-send-button-tooltip"),me=(ro=L.tooltipText)!=null?ro:"Start voice recognition";if(((io=L.showTooltip)!=null?io:!1)&&me)if(Me)Me.textContent=me,Me.style.display="";else{let tt=document.createElement("div");tt.className="tvw-send-button-tooltip",tt.textContent=me,He==null||He.insertBefore(tt,H)}else Me&&(Me.style.display="none");He.style.display="",H.disabled=I.isStreaming()}else H&&He&&(He.style.display="none",V&&ue());let le=(ao=t.sendButton)!=null?ao:{},ut=(lo=le.useIcon)!=null?lo:!1,Pt=(co=le.iconText)!=null?co:"\u2191",Rt=le.iconName,kt=(uo=le.tooltipText)!=null?uo:"Send message",Ut=(po=le.showTooltip)!=null?po:!1,It=(go=le.size)!=null?go:"40px",zt=le.backgroundColor,pt=le.textColor;if(ut){if(q.style.width=It,q.style.height=It,q.style.minWidth=It,q.style.minHeight=It,q.style.fontSize="18px",q.style.lineHeight="1",q.innerHTML="",Rt){let L=parseFloat(It)||24,we=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",oe=ce(Rt,L,we,2);oe?(q.appendChild(oe),q.style.color=we):(q.textContent=Pt,pt?q.style.color=pt:q.classList.add("tvw-text-white"))}else q.textContent=Pt,pt?q.style.color=pt:q.classList.add("tvw-text-white");q.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",zt?(q.style.backgroundColor=zt,q.classList.remove("tvw-bg-cw-primary")):q.classList.add("tvw-bg-cw-primary")}else q.textContent=(mo=(ho=t.copy)==null?void 0:ho.sendButtonLabel)!=null?mo:"Send",q.style.width="",q.style.height="",q.style.minWidth="",q.style.minHeight="",q.style.fontSize="",q.style.lineHeight="",q.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",zt?(q.style.backgroundColor=zt,q.classList.remove("tvw-bg-cw-accent")):q.classList.add("tvw-bg-cw-accent"),pt?q.style.color=pt:q.classList.add("tvw-text-white");le.borderWidth?(q.style.borderWidth=le.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),le.borderColor?q.style.borderColor=le.borderColor:q.style.borderColor="",le.paddingX?(q.style.paddingLeft=le.paddingX,q.style.paddingRight=le.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),le.paddingY?(q.style.paddingTop=le.paddingY,q.style.paddingBottom=le.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let $t=qe==null?void 0:qe.querySelector(".tvw-send-button-tooltip");if(Ut&&kt)if($t)$t.textContent=kt,$t.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=kt,qe==null||qe.insertBefore(L,q)}else $t&&($t.style.display="none");let Ft=(fo=t.statusIndicator)!=null?fo:{},bn=(wo=Ft.visible)!=null?wo:!0;if(nt.style.display=bn?"":"none",I){let L=I.getStatus(),we=oe=>{var We,xe,Qe,je;return oe==="idle"?(We=Ft.idleText)!=null?We:Xe.idle:oe==="connecting"?(xe=Ft.connectingText)!=null?xe:Xe.connecting:oe==="connected"?(Qe=Ft.connectedText)!=null?Qe:Xe.connected:oe==="error"?(je=Ft.errorText)!=null?je:Xe.error:Xe[oe]};nt.textContent=we(L)}},open(){g&&Ke(!0,"api")},close(){g&&Ke(!1,"api")},toggle(){g&&Ke(!b,"api")},clearChat(){I.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let i=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(i),a!=null&&a.clear)try{let u=a.clear();u instanceof Promise&&u.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}l={},C.syncFromMetadata()},setMessage(i){return!re||I.isStreaming()?!1:(!b&&g&&Ke(!0,"system"),re.value=i,re.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(I.isStreaming())return!1;let u=(i==null?void 0:i.trim())||re.value.trim();return u?(!b&&g&&Ke(!0,"system"),re.value="",I.sendMessage(u),!0):!1},startVoiceRecognition(){return V||I.isStreaming()||!Fe()?!1:(!b&&g&&Ke(!0,"system"),ye.manuallyDeactivated=!1,Ye(),Ne("user"),!0)},stopVoiceRecognition(){return V?(ye.manuallyDeactivated=!0,Ye(),ue("user"),!0):!1},injectTestMessage(i){!b&&g&&Ke(!0,"system"),I.injectTestEvent(i)},getMessages(){return I.getMessages()},getStatus(){return I.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(i){f(i)},on(i,u){return o.on(i,u)},off(i,u){o.off(i,u)},isOpen(){return g&&b},isVoiceActive(){return ye.active},getState(){return{open:g&&b,launcherEnabled:g,voiceActive:ye.active,streaming:I.isStreaming()}},showCSATFeedback(i){!b&&g&&Ke(!0,"system");let u=Q.querySelector(".tvw-feedback-container");u&&u.remove();let E=On({onSubmit:async(O,k)=>{var ee;I.isClientTokenMode()&&await I.submitCSATFeedback(O,k),(ee=i==null?void 0:i.onSubmit)==null||ee.call(i,O,k)},onDismiss:i==null?void 0:i.onDismiss,...i});Q.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!b&&g&&Ke(!0,"system");let u=Q.querySelector(".tvw-feedback-container");u&&u.remove();let E=Dn({onSubmit:async(O,k)=>{var ee;I.isClientTokenMode()&&await I.submitNPSFeedback(O,k),(ee=i==null?void 0:i.onSubmit)==null||ee.call(i,O,k)},onDismiss:i==null?void 0:i.onDismiss,...i});Q.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,u){return I.submitCSATFeedback(i,u)},async submitNPSFeedback(i,u){return I.submitNPSFeedback(i,u)},destroy(){$e.forEach(i=>i()),B.remove(),y==null||y.destroy(),F==null||F.remove(),Ue&&J.removeEventListener("click",Ue)}};if((((fs=s==null?void 0:s.debugTools)!=null?fs:!1)||!!t.debug)&&typeof window!="undefined"){let i=window.AgentWidgetBrowser,u={controller:Ce,getMessages:Ce.getMessages,getStatus:Ce.getStatus,getMetadata:Ce.getPersistentMetadata,updateMetadata:Ce.updatePersistentMetadata,clearHistory:()=>Ce.clearChat(),setVoiceActive:E=>E?Ce.startVoiceRecognition():Ce.stopVoiceRecognition()};window.AgentWidgetBrowser=u,$e.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=i)})}return Ce};var ls={},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 e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},vr=()=>{try{if(typeof ls!="undefined"&&ls.url)return new URL("../widget.css",ls.url).href}catch{}return null},jo=n=>{let e=vr(),s=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let r=t.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else s();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},ds=n=>{var c,f,w,d;let e=yr(n.target),s=document.createElement("div");s.className="vanilla-agent-host";let t=(w=(f=(c=n.config)==null?void 0:c.launcher)==null?void 0:f.enabled)!=null?w:!0;t||(s.style.height="100%"),e.appendChild(s);let r=n.useShadowDom===!0,o,a;if(r){let C=s.attachShadow({mode:"open"});a=C,o=document.createElement("div"),o.id="vanilla-agent-root",t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),C.appendChild(o),jo(C)}else a=s,o=document.createElement("div"),o.id="vanilla-agent-root",t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),s.appendChild(o),jo(s);let l=_n(o,n.config,{debugTools:n.debugTools});(d=n.onReady)==null||d.call(n);let p={...l,host:s,destroy(){l.destroy(),s.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=p),p};function br(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function jn(n){var e,s;return(s=(e=n.parserType)!=null?e:br(n.streamParser))!=null?s:"plain"}function qo(n,e="esm"){let s={...n};return delete s.postprocessMessage,delete s.initialMessages,e==="esm"?Cr(s):e==="script-installer"?Ar(s):e==="script-advanced"?Er(s):e==="react-component"?xr(s):e==="react-advanced"?Sr(s):Tr(s)}function Cr(n){let e=jn(n),s=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
61
+ `)}function xr(n){let e=jn(n),s=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
62
+ `)}function Sr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
63
+ `)}function Ar(n){let e=jn(n),s=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
64
+ `)}function Tr(n){let e=jn(n),s=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
65
+ `)}function Er(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" }),"),e.push(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
66
+ `)}var Mr=ds;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_WIDGET_CONFIG,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getHeaderLayout,hasComponentDirective,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,pluginRegistry,renderComponentDirective});
63
67
  //# sourceMappingURL=index.cjs.map