vanilla-agent 1.32.0 → 1.33.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 Hr=Object.create;var Bn=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Rr=Object.getOwnPropertyNames;var Pr=Object.getPrototypeOf,$r=Object.prototype.hasOwnProperty;var Fr=(n,t)=>{for(var s in t)Bn(n,s,{get:t[s],enumerable:!0})},Zo=(n,t,s,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Rr(t))!$r.call(n,r)&&r!==s&&Bn(n,r,{get:()=>t[r],enumerable:!(e=Ir(t,r))||e.enumerable});return n};var Nr=(n,t,s)=>(s=n!=null?Hr(Pr(n)):{},Zo(t||!n||!n.__esModule?Bn(s,"default",{value:n,enumerable:!0}):s,n)),Or=n=>Zo(Bn({},"__esModule",{value:!0}),n);var wi={};Fr(wi,{AgentWidgetClient:()=>Jt,AgentWidgetSession:()=>Vt,DEFAULT_DARK_THEME:()=>ws,DEFAULT_LIGHT_THEME:()=>fs,DEFAULT_WIDGET_CONFIG:()=>Me,attachHeaderToContainer:()=>Yt,buildComposer:()=>Qt,buildDefaultHeader:()=>as,buildExpandedHeader:()=>ds,buildHeader:()=>Pt,buildHeaderWithLayout:()=>Gt,buildMinimalHeader:()=>ls,componentRegistry:()=>nn,createActionManager:()=>xn,createAgentExperience:()=>Gn,createBubbleWithLayout:()=>wr,createCSATFeedback:()=>Xn,createComponentMiddleware:()=>Tr,createComponentStreamParser:()=>zn,createDirectivePostprocessor:()=>or,createFlexibleJsonStreamParser:()=>lr,createJsonStreamParser:()=>Fn,createLocalStorageAdapter:()=>Un,createMarkdownProcessor:()=>fn,createMarkdownProcessorFromConfig:()=>wn,createMessageActions:()=>us,createNPSFeedback:()=>Vn,createPlainTextParser:()=>Pn,createRegexJsonParser:()=>$n,createStandardBubble:()=>Zt,createTypingIndicator:()=>vn,createXmlParser:()=>Nn,default:()=>fi,defaultActionHandlers:()=>Kt,defaultJsonActionParser:()=>Cn,directivePostprocessor:()=>rr,escapeHtml:()=>Hn,extractComponentDirectiveFromMessage:()=>Kn,generateAssistantMessageId:()=>Dn,generateCodeSnippet:()=>Wr,generateMessageId:()=>cr,generateUserMessageId:()=>On,getHeaderLayout:()=>cs,hasComponentDirective:()=>Yn,headerLayouts:()=>jn,initAgentWidget:()=>xs,isComponentDirectiveType:()=>Ar,markdownPostprocessor:()=>os,mergeWithDefaults:()=>qn,pluginRegistry:()=>bn,renderComponentDirective:()=>Jn});module.exports=Or(wi);var tr=require("marked"),Dr=n=>{if(n)return n},fn=n=>{var r,o;let t=n==null?void 0:n.markedOptions,s=new tr.Marked({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=Dr(n==null?void 0:n.renderer);return e&&s.use({renderer:e}),i=>s.parse(i)},wn=n=>n?fn({markedOptions:n.options,renderer:n.renderer}):fn(),_r=fn(),os=n=>_r(n),Hn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),nr=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),er=n=>`%%FORM_PLACEHOLDER_${n}%%`,sr=(n,t)=>{let s=n;return s=s.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,r)=>{try{let o=JSON.parse(r.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let i=er(t.length);return t.push({token:i,type:String(o.type)}),i}}catch{return e}return e}),s=s.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let o=er(t.length);return t.push({token:o,type:r}),o}),s},or=n=>{let t=wn(n);return s=>{let e=[],r=sr(s,e),o=t(r);return e.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),w=`<div class="tvw-form-directive" data-tv-form="${nr(l)}"></div>`;o=o.replace(d,w)}),o}},rr=n=>{let t=[],s=sr(n,t),e=os(s);return t.forEach(({token:r,type:o})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${nr(o)}"></div>`;e=e.replace(i,d)}),e};var Rt=require("partial-json"),In=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),rs=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)}},jr=n=>{var i,l;let t=(i=n.completedAt)!=null?i:Date.now(),s=(l=n.startedAt)!=null?l:t,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-s))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},ir=n=>n.status==="complete"?jr(n):n.status==="pending"?"Waiting":"",qr=n=>{var r,o,i;let s=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((r=n.completedAt)!=null?r:Date.now())-((i=(o=n.startedAt)!=null?o:n.completedAt)!=null?i: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 ar=n=>n.status==="complete"?qr(n):"Using tool...",Ur=()=>{let n=null,t=0,s=e=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=e.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 i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=e.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let o=s(e);return o!==null&&(n=o),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},Rn=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Pn=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},$n=()=>{var t;let n=Ur();return{processChunk:async s=>{let e=s.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(s)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},Fn=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:s=>{let e=s.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(s.length<=t)return n!==null||n===""?{text:n||"",raw:s}:null;try{let r=(0,Rt.parse)(s,Rt.STR|Rt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?In(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=In(r.text)))}catch{}return t=s.length,n!==null?{text:n,raw:s}:null},close:()=>{}}},lr=n=>{let t=null,s=0,r=n||(o=>{if(!o||typeof o!="object")return null;let i=l=>typeof l=="string"?In(l):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?In(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return i(o.on_load_text)||i(o.text)||null;case"message":case"message_and_click":case"checkout":return i(o.text)||null;default:return i(o.text)||i(o.display_text)||i(o.message)||null}return i(o.text)||i(o.display_text)||i(o.message)||i(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let i=o.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(o.length<=s)return t!==null?{text:t,raw:o}:null;try{let l=(0,Rt.parse)(o,Rt.STR|Rt.OBJ),d=r(l);d!==null&&(t=d)}catch{}return s=o.length,{text:t||"",raw:o}},close:()=>{}}},Nn=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var zr="https://api.travrse.ai/v1/dispatch",dr="https://api.travrse.ai";function Jr(n){switch(n){case"json":return Fn;case"regex-json":return $n;case"xml":return Nn;case"plain":default:return Pn}}var Jt=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var s,e,r;this.apiUrl=(s=t.apiUrl)!=null?s:zr,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:Jr(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(t){var e;let s=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||dr;return t==="init"?`${s}/v1/client/init`:`${s}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,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 e=await this.sessionInitPromise;return this.clientSession=e,(s=(t=this.config).onSessionInit)==null||s.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,i;let t=((i=(o=this.config).getStoredSessionId)==null?void 0:i.call(o))||null,s={token:this.config.clientToken,...this.config.flowId&&{flow_id:this.config.flowId},...t&&{session_id:t}},e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!e.ok){let l=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):e.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let r=await e.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.session_id),{sessionId:r.session_id,expiresAt:new Date(r.expires_at),flow:r.flow,config:{welcomeMessage:r.config.welcome_message,placeholder:r.config.placeholder,theme:r.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$/,""))||dr}/v1/client/feedback`}async sendFeedback(t){var o,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.message_id)throw new Error(`message_id is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(o=this.config).onSessionExpired)==null||i.call(o),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,message_id:t,type:s})}async submitCSATFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"csat",rating:t,comment:s})}async submitNPSFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"nps",rating:t,comment:s})}async dispatch(t,s){return this.isClientTokenMode()?this.dispatchClientToken(t,s):this.dispatchProxy(t,s)}async dispatchClientToken(t,s){var r,o,i,l;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),s({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(r=this.config).onSessionExpired)==null||o.call(r);let f=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:f}),f}let c=await this.buildPayload(t.messages),w=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([f])=>f!=="session_id")):void 0,g={session_id:d.sessionId,messages:t.messages.map(f=>({id:f.id,role:f.role,content:f.rawContent||f.content})),...t.assistantMessageId&&{assistant_message_id:t.assistantMessageId},...w&&Object.keys(w).length>0&&{metadata:w},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g);let p=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g),signal:e.signal});if(!p.ok){let f=await p.json().catch(()=>({error:"Chat request failed"}));if(p.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let F=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:F}),F}if(p.status===429){let F=new Error(f.hint||"Message limit reached for this session.");throw s({type:"error",error:F}),F}let m=new Error(f.error||"Failed to send message");throw s({type:"error",error:m}),m}if(!p.body){let f=new Error("No response body received");throw s({type:"error",error:f}),f}s({type:"status",status:"connected"});try{await this.streamResponse(p.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&s({type:"error",error:c}),c}}async dispatchProxy(t,s){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),s({type:"status",status:"connecting"});let r=await this.buildPayload(t.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 i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw s({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw s({type:"error",error:l}),l}s({type:"status",status:"connected"});try{await this.streamResponse(i.body,s)}finally{s({type:"status",status:"idle"})}}async buildPayload(t){let e={messages:t.slice().sort((r,o)=>{let i=new Date(r.createdAt).getTime(),l=new Date(o.createdAt).getTime();return i-l}).map(r=>({role:r.role,content:r.rawContent||r.content,createdAt:r.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async o=>{try{let i=await o({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(e.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...e},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return e}async handleCustomSSEEvent(t,s,e,r,o){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let l=()=>{if(e.current)return e.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return e.current=d,r(d),d};if(i.text!==void 0){let d=l();d.content+=i.text,r(d)}return i.done&&(e.current&&(e.current.streaming=!1,r(e.current)),s({type:"status",status:"idle"})),i.error&&s({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,s,e){var it,se,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,P,$e,ut,pt,Lt,bt,Ct,Fe,et,xt,ke,Le,b,Be,Ee,Ke,st,ot,gt,mt,Mt,$t,Xt,Ot,He,ht,pe,Ft,Bt,Ht,Sn,An,rn,Dt,It,Tn,En,Mn,ss,_t,jt,Ye;let r=t.getReader(),o=new TextDecoder,i="",l=Date.now(),d=0,c=()=>l+d++,w=B=>{let re=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,he=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Ie=B.tools?B.tools.map(fe=>({...fe,chunks:fe.chunks?[...fe.chunks]:void 0})):void 0;return{...B,reasoning:re,toolCall:he,tools:Ie}},g=B=>{s({type:"message",message:w(B)})},p=null,f={current:null},m=new Map,F=new Map,M={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},S=B=>{if(B==null)return null;try{return String(B)}catch{return null}},R=B=>{var re,he,Ie,fe,Ae;return S((Ae=(fe=(Ie=(he=(re=B.stepId)!=null?re:B.step_id)!=null?he:B.step)!=null?Ie:B.parentId)!=null?fe:B.flowStepId)!=null?Ae:B.flow_step_id)},v=B=>{var re,he,Ie,fe,Ae,be,H;return S((H=(be=(Ae=(fe=(Ie=(he=(re=B.callId)!=null?re:B.call_id)!=null?he:B.requestId)!=null?Ie:B.request_id)!=null?fe:B.toolCallId)!=null?Ae:B.tool_call_id)!=null?be:B.stepId)!=null?H:B.step_id)},N=()=>p||(p={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(p),p),x=(B,re)=>{M.lastId=re,B&&M.byStep.set(B,re)},k=(B,re)=>{var Ae;let he=(Ae=B.reasoningId)!=null?Ae:B.id,Ie=R(B);if(he){let be=String(he);return x(Ie,be),be}if(Ie){let be=M.byStep.get(Ie);if(be)return M.lastId=be,be}if(M.lastId&&!re)return M.lastId;if(!re)return null;let fe=`reason-${c()}`;return x(Ie,fe),fe},Y=B=>{let re=m.get(B);if(re)return re;let he={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"streaming",chunks:[]}};return m.set(B,he),g(he),he},z=(B,re)=>{y.lastId=re,B&&y.byCall.set(B,re)},j=(B,re)=>{var Ae;let he=(Ae=B.toolId)!=null?Ae:B.id,Ie=v(B);if(he){let be=String(he);return z(Ie,be),be}if(Ie){let be=y.byCall.get(Ie);if(be)return y.lastId=be,be}if(y.lastId&&!re)return y.lastId;if(!re)return null;let fe=`tool-${c()}`;return z(Ie,fe),fe},O=B=>{let re=F.get(B);if(re)return re;let he={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:B,status:"pending"}};return F.set(B,he),g(he),he},q=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let re=Number(B);if(!Number.isNaN(re)&&Number.isFinite(re))return re;let he=Date.parse(B);if(!Number.isNaN(he))return he}return Date.now()},U=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},J=new Map,V=new Map;for(;;){let{done:B,value:re}=await r.read();if(B)break;i+=o.decode(re,{stream:!0});let he=i.split(`
1
+ "use strict";var Or=Object.create;var Bn=Object.defineProperty;var Nr=Object.getOwnPropertyDescriptor;var Dr=Object.getOwnPropertyNames;var _r=Object.getPrototypeOf,jr=Object.prototype.hasOwnProperty;var qr=(e,s)=>{for(var o in s)Bn(e,o,{get:s[o],enumerable:!0})},tr=(e,s,o,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of Dr(s))!jr.call(e,r)&&r!==o&&Bn(e,r,{get:()=>s[r],enumerable:!(t=Nr(s,r))||t.enumerable});return e};var Ur=(e,s,o)=>(o=e!=null?Or(_r(e)):{},tr(s||!e||!e.__esModule?Bn(o,"default",{value:e,enumerable:!0}):o,e)),zr=e=>tr(Bn({},"__esModule",{value:!0}),e);var Ei={};qr(Ei,{AgentWidgetClient:()=>Yt,AgentWidgetSession:()=>Gt,DEFAULT_DARK_THEME:()=>ys,DEFAULT_LIGHT_THEME:()=>ws,DEFAULT_WIDGET_CONFIG:()=>Me,attachHeaderToContainer:()=>Kt,buildComposer:()=>Zt,buildDefaultHeader:()=>ls,buildExpandedHeader:()=>cs,buildHeader:()=>It,buildHeaderWithLayout:()=>Qt,buildMinimalHeader:()=>ds,componentRegistry:()=>sn,createActionManager:()=>Sn,createAgentExperience:()=>Qn,createBubbleWithLayout:()=>vr,createCSATFeedback:()=>Vn,createComponentMiddleware:()=>Mr,createComponentStreamParser:()=>Jn,createDirectivePostprocessor:()=>ir,createFlexibleJsonStreamParser:()=>cr,createJsonStreamParser:()=>On,createLocalStorageAdapter:()=>zn,createMarkdownProcessor:()=>wn,createMarkdownProcessorFromConfig:()=>yn,createMessageActions:()=>ps,createNPSFeedback:()=>Gn,createPlainTextParser:()=>$n,createRegexJsonParser:()=>Fn,createStandardBubble:()=>en,createTypingIndicator:()=>bn,createXmlParser:()=>Nn,default:()=>Ti,defaultActionHandlers:()=>Xt,defaultJsonActionParser:()=>xn,directivePostprocessor:()=>ar,escapeHtml:()=>Pn,extractComponentDirectiveFromMessage:()=>Xn,generateAssistantMessageId:()=>_n,generateCodeSnippet:()=>Ir,generateMessageId:()=>pr,generateUserMessageId:()=>Dn,getHeaderLayout:()=>us,hasComponentDirective:()=>Kn,headerLayouts:()=>qn,initAgentWidget:()=>Ss,isComponentDirectiveType:()=>Er,markdownPostprocessor:()=>rs,mergeWithDefaults:()=>Un,pluginRegistry:()=>Cn,renderComponentDirective:()=>Yn});module.exports=zr(Ei);var sr=require("marked"),Jr=e=>{if(e)return e},wn=e=>{var r,n;let s=e==null?void 0:e.markedOptions,o=new sr.Marked({gfm:(r=s==null?void 0:s.gfm)!=null?r:!0,breaks:(n=s==null?void 0:s.breaks)!=null?n:!0,pedantic:s==null?void 0:s.pedantic,silent:s==null?void 0:s.silent}),t=Jr(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},yn=e=>e?wn({markedOptions:e.options,renderer:e.renderer}):wn(),Yr=wn(),rs=e=>Yr(e),Pn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),or=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),nr=e=>`%%FORM_PLACEHOLDER_${e}%%`,rr=(e,s)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let n=JSON.parse(r.trim());if(n&&typeof n=="object"&&n.component==="form"&&n.type){let i=nr(s.length);return s.push({token:i,type:String(n.type)}),i}}catch{return t}return t}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let n=nr(s.length);return s.push({token:n,type:r}),n}),o},ir=e=>{let s=yn(e);return o=>{let t=[],r=rr(o,t),n=s(r);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),w=`<div class="tvw-form-directive" data-tv-form="${or(a)}"></div>`;n=n.replace(d,w)}),n}},ar=e=>{let s=[],o=rr(e,s),t=rs(o);return s.forEach(({token:r,type:n})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${or(n)}"></div>`;t=t.replace(i,d)}),t};var Rt=require("partial-json"),Rn=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),is=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Kr=e=>{var i,a;let s=(i=e.completedAt)!=null?i:Date.now(),o=(a=e.startedAt)!=null?a:s,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,s-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},lr=e=>e.status==="complete"?Kr(e):e.status==="pending"?"Waiting":"",Xr=e=>{var r,n,i;let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((i=(n=e.startedAt)!=null?n:e.completedAt)!=null?i:Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var dr=e=>e.status==="complete"?Xr(e):"Using tool...",Vr=()=>{let e=null,s=0,o=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,n=t.match(r);if(n&&n[1])try{return n[1].replace(/\\n/g,`
3
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return n[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=t.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=s)return e!==null?{text:e,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let n=o(t);return n!==null&&(e=n),s=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},In=e=>{try{let s=JSON.parse(e);if(s&&typeof s=="object"&&typeof s.text=="string")return s.text}catch{return null}return null},$n=()=>{let e={processChunk:s=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Fn=()=>{var s;let e=Vr();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(o)},getExtractedText:e.getExtractedText.bind(e),close:(s=e.close)==null?void 0:s.bind(e)}},On=()=>{let e=null,s=0;return{getExtractedText:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=s)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,Rt.parse)(o,Rt.STR|Rt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Rn(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Rn(r.text)))}catch{}return s=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},cr=e=>{let s=null,o=0,r=e||(n=>{if(!n||typeof n!="object")return null;let i=a=>typeof a=="string"?Rn(a):null;if(n.component&&typeof n.component=="string")return typeof n.text=="string"?Rn(n.text):"";if(n.type==="init"&&n.form)return"";if(n.action)switch(n.action){case"nav_then_click":return i(n.on_load_text)||i(n.text)||null;case"message":case"message_and_click":case"checkout":return i(n.text)||null;default:return i(n.text)||i(n.display_text)||i(n.message)||null}return i(n.text)||i(n.display_text)||i(n.message)||i(n.content)||null});return{getExtractedText:()=>s,processChunk:n=>{let i=n.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(n.length<=o)return s!==null?{text:s,raw:n}:null;try{let a=(0,Rt.parse)(n,Rt.STR|Rt.OBJ),d=r(a);d!==null&&(s=d)}catch{}return o=n.length,{text:s||"",raw:n}},close:()=>{}}},Nn=()=>{let e=null;return{processChunk:s=>{if(!s.trim().startsWith("<"))return null;let t=s.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:s}):null},getExtractedText:()=>e}};var Gr="https://api.travrse.ai/v1/dispatch",ur="https://api.travrse.ai";function Qr(e){switch(e){case"json":return On;case"regex-json":return Fn;case"xml":return Nn;case"plain":default:return $n}}var Yt=class{constructor(s={}){this.config=s;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=s.apiUrl)!=null?o:Gr,this.headers={"Content-Type":"application/json",...s.headers},this.debug=!!s.debug,this.createStreamParser=(t=s.streamParser)!=null?t:Qr(s.parserType),this.contextProviders=(r=s.contextProviders)!=null?r:[],this.requestMiddleware=s.requestMiddleware,this.customFetch=s.customFetch,this.parseSSEEvent=s.parseSSEEvent,this.getHeaders=s.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(s){var t;let o=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ur;return s==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var s,o;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(o=(s=this.config).onSessionInit)==null||o.call(s,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var n,i;let s=((i=(n=this.config).getStoredSessionId)==null?void 0:i.call(n))||null,o={token:this.config.clientToken,...this.config.flowId&&{flow_id:this.config.flowId},...s&&{session_id:s}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let r=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.session_id),{sessionId:r.session_id,expiresAt:new Date(r.expires_at),flow:r.flow,config:{welcomeMessage:r.config.welcome_message,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ur}/v1/client/feedback`}async sendFeedback(s){var n,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(s.type)&&!s.message_id)throw new Error(`message_id is required for ${s.type} feedback type`);if(s.type==="csat"&&(s.rating===void 0||s.rating<1||s.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(s.type==="nps"&&(s.rating===void 0||s.rating<0||s.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",s);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(n=this.config).onSessionExpired)==null||i.call(n),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(s,o){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:s,type:o})}async submitCSATFeedback(s,o){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:s,comment:o})}async submitNPSFeedback(s,o){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:s,comment:o})}async dispatch(s,o){return this.isClientTokenMode()?this.dispatchClientToken(s,o):this.dispatchProxy(s,o)}async dispatchClientToken(s,o){var r,n,i,a;let t=new AbortController;s.signal&&s.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(n=(r=this.config).onSessionExpired)==null||n.call(r);let f=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:f}),f}let c=await this.buildPayload(s.messages),w=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([f])=>f!=="session_id")):void 0,g={session_id:d.sessionId,messages:s.messages.map(f=>({id:f.id,role:f.role,content:f.rawContent||f.content})),...s.assistantMessageId&&{assistant_message_id:s.assistantMessageId},...w&&Object.keys(w).length>0&&{metadata:w},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g);let p=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g),signal:t.signal});if(!p.ok){let f=await p.json().catch(()=>({error:"Chat request failed"}));if(p.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let F=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:F}),F}if(p.status===429){let F=new Error(f.hint||"Message limit reached for this session.");throw o({type:"error",error:F}),F}let m=new Error(f.error||"Failed to send message");throw o({type:"error",error:m}),m}if(!p.body){let f=new Error("No response body received");throw o({type:"error",error:f}),f}o({type:"status",status:"connected"});try{await this.streamResponse(p.body,o,s.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&o({type:"error",error:c}),c}}async dispatchProxy(s,o){let t=new AbortController;s.signal&&s.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(s.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let n={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();n={...n,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:n,body:JSON.stringify(r),signal:t.signal},r)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:n,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:a}),a}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(s){let t={messages:s.slice().sort((r,n)=>{let i=new Date(r.createdAt).getTime(),a=new Date(n.createdAt).getTime();return i-a}).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 n=>{try{let i=await n({messages:s,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(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(s,o,t,r,n){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(s);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:n()};return t.current=d,r(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(s,o,t){var it,se,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,I,$e,ut,pt,Lt,bt,Ct,Fe,et,xt,We,Le,b,He,Ee,Ke,st,ot,gt,mt,Mt,Ft,Vt,Dt,Be,ht,pe,Ot,Ht,Bt,An,Tn,an,_t,Pt,En,Mn,Wn,os,jt,qt,Ye;let r=s.getReader(),n=new TextDecoder,i="",a=Date.now(),d=0,c=()=>a+d++,w=H=>{let re=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,he=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,Pe=H.tools?H.tools.map(fe=>({...fe,chunks:fe.chunks?[...fe.chunks]:void 0})):void 0;return{...H,reasoning:re,toolCall:he,tools:Pe}},g=H=>{o({type:"message",message:w(H)})},p=null,f={current:null},m=new Map,F=new Map,M={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},S=H=>{if(H==null)return null;try{return String(H)}catch{return null}},R=H=>{var re,he,Pe,fe,Ae;return S((Ae=(fe=(Pe=(he=(re=H.stepId)!=null?re:H.step_id)!=null?he:H.step)!=null?Pe:H.parentId)!=null?fe:H.flowStepId)!=null?Ae:H.flow_step_id)},v=H=>{var re,he,Pe,fe,Ae,be,B;return S((B=(be=(Ae=(fe=(Pe=(he=(re=H.callId)!=null?re:H.call_id)!=null?he:H.requestId)!=null?Pe:H.request_id)!=null?fe:H.toolCallId)!=null?Ae:H.tool_call_id)!=null?be:H.stepId)!=null?B:H.step_id)},O=()=>p||(p={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(p),p),x=(H,re)=>{M.lastId=re,H&&M.byStep.set(H,re)},W=(H,re)=>{var Ae;let he=(Ae=H.reasoningId)!=null?Ae:H.id,Pe=R(H);if(he){let be=String(he);return x(Pe,be),be}if(Pe){let be=M.byStep.get(Pe);if(be)return M.lastId=be,be}if(M.lastId&&!re)return M.lastId;if(!re)return null;let fe=`reason-${c()}`;return x(Pe,fe),fe},Y=H=>{let re=m.get(H);if(re)return re;let he={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:H,status:"streaming",chunks:[]}};return m.set(H,he),g(he),he},z=(H,re)=>{y.lastId=re,H&&y.byCall.set(H,re)},j=(H,re)=>{var Ae;let he=(Ae=H.toolId)!=null?Ae:H.id,Pe=v(H);if(he){let be=String(he);return z(Pe,be),be}if(Pe){let be=y.byCall.get(Pe);if(be)return y.lastId=be,be}if(y.lastId&&!re)return y.lastId;if(!re)return null;let fe=`tool-${c()}`;return z(Pe,fe),fe},N=H=>{let re=F.get(H);if(re)return re;let he={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:H,status:"pending"}};return F.set(H,he),g(he),he},q=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let re=Number(H);if(!Number.isNaN(re)&&Number.isFinite(re))return re;let he=Date.parse(H);if(!Number.isNaN(he))return he}return Date.now()},U=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},J=new Map,V=new Map;for(;;){let{done:H,value:re}=await r.read();if(H)break;i+=n.decode(re,{stream:!0});let he=i.split(`
5
5
 
6
- `);i=(it=he.pop())!=null?it:"";for(let Ie of he){let fe=Ie.split(`
7
- `),Ae="message",be="";for(let te of fe)te.startsWith("event:")?Ae=te.replace("event:","").trim():te.startsWith("data:")&&(be+=te.replace("data:","").trim());if(!be)continue;let H;try{H=JSON.parse(be)}catch(te){s({type:"error",error:te instanceof Error?te:new Error("Failed to parse chat stream payload")});continue}let ft=Ae!=="message"?Ae:(se=H.type)!=null?se:"message";if(this.parseSSEEvent){f.current=p;let te=await this.handleCustomSSEEvent(H,s,f,g,c);if(f.current&&!p&&(p=f.current),te)continue}if(ft==="reason_start"){let te=(D=k(H,!0))!=null?D:`reason-${c()}`,W=Y(te);W.reasoning=(Ve=W.reasoning)!=null?Ve:{id:te,status:"streaming",chunks:[]},W.reasoning.startedAt=(at=W.reasoning.startedAt)!=null?at:q((nt=H.startedAt)!=null?nt:H.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",g(W)}else if(ft==="reason_chunk"){let te=(Et=(Tt=k(H,!1))!=null?Tt:k(H,!0))!=null?Et:`reason-${c()}`,W=Y(te);W.reasoning=(_=W.reasoning)!=null?_:{id:te,status:"streaming",chunks:[]},W.reasoning.startedAt=(Ge=W.reasoning.startedAt)!=null?Ge:q((ue=H.startedAt)!=null?ue:H.timestamp);let E=(Ze=(_e=(Qe=H.reasoningText)!=null?Qe:H.text)!=null?_e:H.delta)!=null?Ze:"";if(E&&H.hidden!==!0&&W.reasoning.chunks.push(String(E)),W.reasoning.status=H.done?"complete":"streaming",H.done){W.reasoning.completedAt=q((P=H.completedAt)!=null?P:H.timestamp);let K=($e=W.reasoning.startedAt)!=null?$e:Date.now();W.reasoning.durationMs=Math.max(0,((ut=W.reasoning.completedAt)!=null?ut:Date.now())-K)}W.streaming=W.reasoning.status!=="complete",g(W)}else if(ft==="reason_complete"){let te=(Lt=(pt=k(H,!1))!=null?pt:k(H,!0))!=null?Lt:`reason-${c()}`,W=m.get(te);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=q((bt=H.completedAt)!=null?bt:H.timestamp);let K=(Ct=W.reasoning.startedAt)!=null?Ct:Date.now();W.reasoning.durationMs=Math.max(0,((Fe=W.reasoning.completedAt)!=null?Fe:Date.now())-K),W.streaming=!1,g(W)}let E=R(H);E&&M.byStep.delete(E)}else if(ft==="tool_start"){let te=(et=j(H,!0))!=null?et:`tool-${c()}`,W=O(te),E=(xt=W.toolCall)!=null?xt:{id:te,status:"pending"};E.name=(ke=H.toolName)!=null?ke:E.name,E.status="running",H.args!==void 0&&(E.args=H.args),E.startedAt=(b=E.startedAt)!=null?b:q((Le=H.startedAt)!=null?Le:H.timestamp),E.completedAt=void 0,E.durationMs=void 0,W.toolCall=E,W.streaming=!0,g(W)}else if(ft==="tool_chunk"){let te=(Ee=(Be=j(H,!1))!=null?Be:j(H,!0))!=null?Ee:`tool-${c()}`,W=O(te),E=(Ke=W.toolCall)!=null?Ke:{id:te,status:"running"};E.startedAt=(ot=E.startedAt)!=null?ot:q((st=H.startedAt)!=null?st:H.timestamp);let K=(Mt=(mt=(gt=H.text)!=null?gt:H.delta)!=null?mt:H.message)!=null?Mt:"";K&&(E.chunks=($t=E.chunks)!=null?$t:[],E.chunks.push(String(K))),E.status="running",W.toolCall=E,W.streaming=!0,g(W)}else if(ft==="tool_complete"){let te=(Ot=(Xt=j(H,!1))!=null?Xt:j(H,!0))!=null?Ot:`tool-${c()}`,W=O(te),E=(He=W.toolCall)!=null?He:{id:te,status:"running"};if(E.status="complete",H.result!==void 0&&(E.result=H.result),typeof H.duration=="number"&&(E.duration=H.duration),E.completedAt=q((ht=H.completedAt)!=null?ht:H.timestamp),typeof H.duration=="number")E.durationMs=H.duration;else{let We=(pe=E.startedAt)!=null?pe:Date.now();E.durationMs=Math.max(0,((Ft=E.completedAt)!=null?Ft:Date.now())-We)}W.toolCall=E,W.streaming=!1,g(W);let K=v(H);K&&y.byCall.delete(K)}else if(ft==="step_chunk"){let te=H.stepType,W=H.executionType;if(te==="tool"||W==="context")continue;let E=N(),K=(An=(Sn=(Ht=(Bt=H.text)!=null?Bt:H.delta)!=null?Ht:H.content)!=null?Sn:H.chunk)!=null?An:"";if(K){let ye=((rn=V.get(E.id))!=null?rn:"")+K;E.rawContent=ye,J.has(E.id)||J.set(E.id,this.createStreamParser());let ie=J.get(E.id),Q=ye.trim().startsWith("{")||ye.trim().startsWith("[");if(Q&&V.set(E.id,ye),ie.__isPlainTextParser===!0){E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E);continue}let je=ie.processChunk(ye);if(je instanceof Promise)je.then(ge=>{var ve;let Ce=typeof ge=="string"?ge:(ve=ge==null?void 0:ge.text)!=null?ve:null;if(Ce!==null&&Ce.trim()!==""){let xe=p;xe&&xe.id===E.id&&(xe.content=Ce,g(xe))}else if(!Q&&!ye.trim().startsWith("<")){let xe=p;xe&&xe.id===E.id&&(xe.content+=K,V.delete(xe.id),J.delete(xe.id),xe.rawContent=void 0,g(xe))}}).catch(()=>{E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E)});else{let ge=typeof je=="string"?je:(Dt=je==null?void 0:je.text)!=null?Dt:null;ge!==null&&ge.trim()!==""?(E.content=ge,g(E)):!Q&&!ye.trim().startsWith("<")&&(E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E))}}if(H.isComplete){let We=(Tn=(It=H.result)==null?void 0:It.response)!=null?Tn:E.content;if(We){let ye=V.get(E.id),ie=ye!=null?ye:U(We);E.rawContent=ie;let Q=J.get(E.id),Re=null,je=!1;if(Q&&(Re=Q.getExtractedText(),Re===null&&(Re=Rn(ie)),Re===null)){let ge=Q.processChunk(ie);ge instanceof Promise?(je=!0,ge.then(Ce=>{var xe;let ve=typeof Ce=="string"?Ce:(xe=Ce==null?void 0:Ce.text)!=null?xe:null;if(ve!==null){let Ue=p;Ue&&Ue.id===E.id&&(Ue.content=ve,Ue.streaming=!1,J.delete(Ue.id),V.delete(Ue.id),g(Ue))}})):Re=typeof ge=="string"?ge:(En=ge==null?void 0:ge.text)!=null?En:null}if(!je){Re!==null&&Re.trim()!==""?E.content=Re:V.has(E.id)||(E.content=U(We));let ge=J.get(E.id);if(ge){let Ce=(Mn=ge.close)==null?void 0:Mn.call(ge);Ce instanceof Promise&&Ce.catch(()=>{}),J.delete(E.id)}V.delete(E.id),E.streaming=!1,g(E)}}}}else if(ft==="step_complete"){let te=H.stepType,W=H.executionType;if(te==="tool"||W==="context")continue;let E=(ss=H.result)==null?void 0:ss.response,K=N();if(E!=null){let We=J.get(K.id),ye=!1,ie=!1;if(We){let Q=We.getExtractedText(),Re=V.get(K.id),je=Re!=null?Re:U(E);if(K.rawContent=je,Q!==null&&Q.trim()!=="")K.content=Q,ye=!0;else{let ge=Rn(je);if(ge!==null)K.content=ge,ye=!0;else{let Ce=We.processChunk(je);if(Ce instanceof Promise)ie=!0,Ce.then(ve=>{var Ue;let xe=typeof ve=="string"?ve:(Ue=ve==null?void 0:ve.text)!=null?Ue:null;if(xe!==null&&xe.trim()!==""){let lt=p;lt&&lt.id===K.id&&(lt.content=xe,lt.streaming=!1,J.delete(lt.id),V.delete(lt.id),g(lt))}else{let lt=We.getExtractedText(),vt=p;vt&&vt.id===K.id&&(lt!==null&&lt.trim()!==""?vt.content=lt:V.has(vt.id)||(vt.content=U(E)),vt.streaming=!1,J.delete(vt.id),V.delete(vt.id),g(vt))}});else{let ve=typeof Ce=="string"?Ce:(_t=Ce==null?void 0:Ce.text)!=null?_t:null;if(ve!==null&&ve.trim()!=="")K.content=ve,ye=!0;else{let xe=We.getExtractedText();xe!==null&&xe.trim()!==""&&(K.content=xe,ye=!0)}}}}}if(!ie){if(!K.rawContent){let Q=V.get(K.id);K.rawContent=Q!=null?Q:U(E)}if(!ye&&!V.has(K.id)&&(K.content=U(E)),We){let Q=(jt=We.close)==null?void 0:jt.call(We);Q instanceof Promise&&Q.catch(()=>{})}J.delete(K.id),V.delete(K.id),K.streaming=!1,g(K)}}else J.delete(K.id),V.delete(K.id),K.streaming=!1,g(K)}else if(ft==="flow_complete"){let te=(Ye=H.result)==null?void 0:Ye.response;if(te!=null){let W=N(),E=V.get(W.id),K=E!=null?E:U(te);W.rawContent=K;let We=U(te),ye=J.get(W.id);if(ye){let Re=Rn(K);if(Re!==null)We=Re;else{let je=ye.processChunk(K);je instanceof Promise&&je.then(Ce=>{var xe;let ve=typeof Ce=="string"?Ce:(xe=Ce==null?void 0:Ce.text)!=null?xe:null;if(ve!==null){let Ue=p;Ue&&Ue.id===W.id&&(Ue.content=ve,Ue.streaming=!1,g(Ue))}});let ge=ye.getExtractedText();ge!==null&&(We=ge)}}J.delete(W.id),V.delete(W.id);let ie=We!==W.content,Q=W.streaming!==!1;ie&&(W.content=We),W.streaming=!1,(ie||Q)&&g(W)}else if(p!==null){let W=p;J.delete(W.id),V.delete(W.id),W.streaming!==!1&&(W.streaming=!1,g(W))}s({type:"status",status:"idle"})}else ft==="error"&&H.error&&s({type:"error",error:H.error instanceof Error?H.error:new Error(String(H.error))})}}}};function cr(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function On(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function Dn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var Vt=class{constructor(t={},s){this.config=t;this.callbacks=s;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=t=>{var s,e;t.type==="message"?this.upsertMessage(t.message):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null)):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(s=this.callbacks).onError)==null||e.call(s,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(r=>{var o;return{...r,sequence:(o=r.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Jt(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var t,s;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(s=(t=this.callbacks).onError)==null||s.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let s={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(s)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,s){return this.client.submitMessageFeedback(t,s)}async submitCSATFeedback(t,s){return this.client.submitCSATFeedback(t,s)}async submitNPSFeedback(t,s){return this.client.submitNPSFeedback(t,s)}updateConfig(t){this.config={...this.config,...t},this.client=new Jt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}async sendMessage(t,s){var c,w,g,p,f;let e=t.trim();if(!e)return;(c=this.abortController)==null||c.abort();let r=On(),o=Dn(),i={id:r,role:"user",content:e,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(s==null?void 0:s.viaVoice)||!1};this.appendMessage(i),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:l.signal,assistantMessageId:o},this.handleEvent)}catch(m){let F={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(F),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m instanceof Error?(g=(w=this.callbacks).onError)==null||g.call(w,m):(f=(p=this.callbacks).onError)==null||f.call(p,new Error(String(m)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var r;return{...e,streaming:!1,sequence:(r=e.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){this.streaming!==t&&(this.streaming=t,this.callbacks.onStreamingChanged(t))}appendMessage(t){let s=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,s]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let s=this.ensureSequence(t),e=this.messages.findIndex(r=>r.id===s.id);if(e===-1){this.appendMessage(s);return}this.messages=this.messages.map((r,o)=>o===e?{...r,...s}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((s,e)=>{var d,c;let r=new Date(s.createdAt).getTime(),o=new Date(e.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let i=(d=s.sequence)!=null?d:0,l=(c=e.sequence)!=null?c:0;return i!==l?i-l:s.id.localeCompare(e.id)})}};var is=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Yr=n=>{var o,i,l;let t=(o=n==null?void 0:n.colorScheme)!=null?o:"light",s=(i=n==null?void 0:n.theme)!=null?i:{},e=(l=n==null?void 0:n.darkTheme)!=null?l:s;return t==="light"?s:t==="dark"||is()==="dark"?e:s},ur=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let s=new MutationObserver(()=>{n(is())});s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>s.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let s=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(is());s.addEventListener?(s.addEventListener("change",e),t.push(()=>s.removeEventListener("change",e))):s.addListener&&(s.addListener(e),t.push(()=>s.removeListener(e)))}return()=>{t.forEach(s=>s())}},_n=(n,t)=>{let s=Yr(t);Object.entries(s).forEach(([e,r])=>{if(r==null||r==="")return;let o=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${o}`,String(r))})};var Kr=Nr(require("lucide"),1),de=(n,t=24,s="currentColor",e=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),o=Kr[r];return o?Xr(o,t,s,e):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function Xr(n,t,s,e){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",s),r.setAttribute("stroke-width",String(e)),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 i=o[0],l=o[1];if(l){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([c,w])=>{c!=="stroke"&&d.setAttribute(c,String(w))}),r.appendChild(d)}}}),r}var h=(n,t)=>{let s=document.createElement(n);return t&&(s.className=t),s};var pr=require("idiomorph"),gr=(n,t,s={})=>{let{preserveTypingAnimation:e=!0}=s;pr.Idiomorph.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,o){if(r instanceof HTMLElement&&e&&r.classList.contains("tvw-animate-typing"))return!1}}})};var tt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var At={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var yn=(n,t)=>{let s=h("button");s.type="button",s.innerHTML=`
6
+ `);i=(it=he.pop())!=null?it:"";for(let Pe of he){let fe=Pe.split(`
7
+ `),Ae="message",be="";for(let te of fe)te.startsWith("event:")?Ae=te.replace("event:","").trim():te.startsWith("data:")&&(be+=te.replace("data:","").trim());if(!be)continue;let B;try{B=JSON.parse(be)}catch(te){o({type:"error",error:te instanceof Error?te:new Error("Failed to parse chat stream payload")});continue}let ft=Ae!=="message"?Ae:(se=B.type)!=null?se:"message";if(this.parseSSEEvent){f.current=p;let te=await this.handleCustomSSEEvent(B,o,f,g,c);if(f.current&&!p&&(p=f.current),te)continue}if(ft==="reason_start"){let te=(D=W(B,!0))!=null?D:`reason-${c()}`,k=Y(te);k.reasoning=(Ve=k.reasoning)!=null?Ve:{id:te,status:"streaming",chunks:[]},k.reasoning.startedAt=(at=k.reasoning.startedAt)!=null?at:q((nt=B.startedAt)!=null?nt:B.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",g(k)}else if(ft==="reason_chunk"){let te=(Et=(Tt=W(B,!1))!=null?Tt:W(B,!0))!=null?Et:`reason-${c()}`,k=Y(te);k.reasoning=(_=k.reasoning)!=null?_:{id:te,status:"streaming",chunks:[]},k.reasoning.startedAt=(Ge=k.reasoning.startedAt)!=null?Ge:q((ue=B.startedAt)!=null?ue:B.timestamp);let E=(Ze=(_e=(Qe=B.reasoningText)!=null?Qe:B.text)!=null?_e:B.delta)!=null?Ze:"";if(E&&B.hidden!==!0&&k.reasoning.chunks.push(String(E)),k.reasoning.status=B.done?"complete":"streaming",B.done){k.reasoning.completedAt=q((I=B.completedAt)!=null?I:B.timestamp);let K=($e=k.reasoning.startedAt)!=null?$e:Date.now();k.reasoning.durationMs=Math.max(0,((ut=k.reasoning.completedAt)!=null?ut:Date.now())-K)}k.streaming=k.reasoning.status!=="complete",g(k)}else if(ft==="reason_complete"){let te=(Lt=(pt=W(B,!1))!=null?pt:W(B,!0))!=null?Lt:`reason-${c()}`,k=m.get(te);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=q((bt=B.completedAt)!=null?bt:B.timestamp);let K=(Ct=k.reasoning.startedAt)!=null?Ct:Date.now();k.reasoning.durationMs=Math.max(0,((Fe=k.reasoning.completedAt)!=null?Fe:Date.now())-K),k.streaming=!1,g(k)}let E=R(B);E&&M.byStep.delete(E)}else if(ft==="tool_start"){let te=(et=j(B,!0))!=null?et:`tool-${c()}`,k=N(te),E=(xt=k.toolCall)!=null?xt:{id:te,status:"pending"};E.name=(We=B.toolName)!=null?We:E.name,E.status="running",B.args!==void 0&&(E.args=B.args),E.startedAt=(b=E.startedAt)!=null?b:q((Le=B.startedAt)!=null?Le:B.timestamp),E.completedAt=void 0,E.durationMs=void 0,k.toolCall=E,k.streaming=!0,g(k)}else if(ft==="tool_chunk"){let te=(Ee=(He=j(B,!1))!=null?He:j(B,!0))!=null?Ee:`tool-${c()}`,k=N(te),E=(Ke=k.toolCall)!=null?Ke:{id:te,status:"running"};E.startedAt=(ot=E.startedAt)!=null?ot:q((st=B.startedAt)!=null?st:B.timestamp);let K=(Mt=(mt=(gt=B.text)!=null?gt:B.delta)!=null?mt:B.message)!=null?Mt:"";K&&(E.chunks=(Ft=E.chunks)!=null?Ft:[],E.chunks.push(String(K))),E.status="running",k.toolCall=E,k.streaming=!0,g(k)}else if(ft==="tool_complete"){let te=(Dt=(Vt=j(B,!1))!=null?Vt:j(B,!0))!=null?Dt:`tool-${c()}`,k=N(te),E=(Be=k.toolCall)!=null?Be:{id:te,status:"running"};if(E.status="complete",B.result!==void 0&&(E.result=B.result),typeof B.duration=="number"&&(E.duration=B.duration),E.completedAt=q((ht=B.completedAt)!=null?ht:B.timestamp),typeof B.duration=="number")E.durationMs=B.duration;else{let ke=(pe=E.startedAt)!=null?pe:Date.now();E.durationMs=Math.max(0,((Ot=E.completedAt)!=null?Ot:Date.now())-ke)}k.toolCall=E,k.streaming=!1,g(k);let K=v(B);K&&y.byCall.delete(K)}else if(ft==="step_chunk"){let te=B.stepType,k=B.executionType;if(te==="tool"||k==="context")continue;let E=O(),K=(Tn=(An=(Bt=(Ht=B.text)!=null?Ht:B.delta)!=null?Bt:B.content)!=null?An:B.chunk)!=null?Tn:"";if(K){let ye=((an=V.get(E.id))!=null?an:"")+K;E.rawContent=ye,J.has(E.id)||J.set(E.id,this.createStreamParser());let ie=J.get(E.id),Q=ye.trim().startsWith("{")||ye.trim().startsWith("[");if(Q&&V.set(E.id,ye),ie.__isPlainTextParser===!0){E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E);continue}let je=ie.processChunk(ye);if(je instanceof Promise)je.then(ge=>{var ve;let Ce=typeof ge=="string"?ge:(ve=ge==null?void 0:ge.text)!=null?ve:null;if(Ce!==null&&Ce.trim()!==""){let xe=p;xe&&xe.id===E.id&&(xe.content=Ce,g(xe))}else if(!Q&&!ye.trim().startsWith("<")){let xe=p;xe&&xe.id===E.id&&(xe.content+=K,V.delete(xe.id),J.delete(xe.id),xe.rawContent=void 0,g(xe))}}).catch(()=>{E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E)});else{let ge=typeof je=="string"?je:(_t=je==null?void 0:je.text)!=null?_t:null;ge!==null&&ge.trim()!==""?(E.content=ge,g(E)):!Q&&!ye.trim().startsWith("<")&&(E.content+=K,V.delete(E.id),J.delete(E.id),E.rawContent=void 0,g(E))}}if(B.isComplete){let ke=(En=(Pt=B.result)==null?void 0:Pt.response)!=null?En:E.content;if(ke){let ye=V.get(E.id),ie=ye!=null?ye:U(ke);E.rawContent=ie;let Q=J.get(E.id),Re=null,je=!1;if(Q&&(Re=Q.getExtractedText(),Re===null&&(Re=In(ie)),Re===null)){let ge=Q.processChunk(ie);ge instanceof Promise?(je=!0,ge.then(Ce=>{var xe;let ve=typeof Ce=="string"?Ce:(xe=Ce==null?void 0:Ce.text)!=null?xe:null;if(ve!==null){let Ue=p;Ue&&Ue.id===E.id&&(Ue.content=ve,Ue.streaming=!1,J.delete(Ue.id),V.delete(Ue.id),g(Ue))}})):Re=typeof ge=="string"?ge:(Mn=ge==null?void 0:ge.text)!=null?Mn:null}if(!je){Re!==null&&Re.trim()!==""?E.content=Re:V.has(E.id)||(E.content=U(ke));let ge=J.get(E.id);if(ge){let Ce=(Wn=ge.close)==null?void 0:Wn.call(ge);Ce instanceof Promise&&Ce.catch(()=>{}),J.delete(E.id)}V.delete(E.id),E.streaming=!1,g(E)}}}}else if(ft==="step_complete"){let te=B.stepType,k=B.executionType;if(te==="tool"||k==="context")continue;let E=(os=B.result)==null?void 0:os.response,K=O();if(E!=null){let ke=J.get(K.id),ye=!1,ie=!1;if(ke){let Q=ke.getExtractedText(),Re=V.get(K.id),je=Re!=null?Re:U(E);if(K.rawContent=je,Q!==null&&Q.trim()!=="")K.content=Q,ye=!0;else{let ge=In(je);if(ge!==null)K.content=ge,ye=!0;else{let Ce=ke.processChunk(je);if(Ce instanceof Promise)ie=!0,Ce.then(ve=>{var Ue;let xe=typeof ve=="string"?ve:(Ue=ve==null?void 0:ve.text)!=null?Ue:null;if(xe!==null&&xe.trim()!==""){let lt=p;lt&&lt.id===K.id&&(lt.content=xe,lt.streaming=!1,J.delete(lt.id),V.delete(lt.id),g(lt))}else{let lt=ke.getExtractedText(),vt=p;vt&&vt.id===K.id&&(lt!==null&&lt.trim()!==""?vt.content=lt:V.has(vt.id)||(vt.content=U(E)),vt.streaming=!1,J.delete(vt.id),V.delete(vt.id),g(vt))}});else{let ve=typeof Ce=="string"?Ce:(jt=Ce==null?void 0:Ce.text)!=null?jt:null;if(ve!==null&&ve.trim()!=="")K.content=ve,ye=!0;else{let xe=ke.getExtractedText();xe!==null&&xe.trim()!==""&&(K.content=xe,ye=!0)}}}}}if(!ie){if(!K.rawContent){let Q=V.get(K.id);K.rawContent=Q!=null?Q:U(E)}if(!ye&&!V.has(K.id)&&(K.content=U(E)),ke){let Q=(qt=ke.close)==null?void 0:qt.call(ke);Q instanceof Promise&&Q.catch(()=>{})}J.delete(K.id),V.delete(K.id),K.streaming=!1,g(K)}}else J.delete(K.id),V.delete(K.id),K.streaming=!1,g(K)}else if(ft==="flow_complete"){let te=(Ye=B.result)==null?void 0:Ye.response;if(te!=null){let k=O(),E=V.get(k.id),K=E!=null?E:U(te);k.rawContent=K;let ke=U(te),ye=J.get(k.id);if(ye){let Re=In(K);if(Re!==null)ke=Re;else{let je=ye.processChunk(K);je instanceof Promise&&je.then(Ce=>{var xe;let ve=typeof Ce=="string"?Ce:(xe=Ce==null?void 0:Ce.text)!=null?xe:null;if(ve!==null){let Ue=p;Ue&&Ue.id===k.id&&(Ue.content=ve,Ue.streaming=!1,g(Ue))}});let ge=ye.getExtractedText();ge!==null&&(ke=ge)}}J.delete(k.id),V.delete(k.id);let ie=ke!==k.content,Q=k.streaming!==!1;ie&&(k.content=ke),k.streaming=!1,(ie||Q)&&g(k)}else if(p!==null){let k=p;J.delete(k.id),V.delete(k.id),k.streaming!==!1&&(k.streaming=!1,g(k))}o({type:"status",status:"idle"})}else ft==="error"&&B.error&&o({type:"error",error:B.error instanceof Error?B.error:new Error(String(B.error))})}}}};function pr(){let e=Date.now().toString(36),s=Math.random().toString(36).substring(2,10);return`msg_${e}_${s}`}function Dn(){let e=Date.now().toString(36),s=Math.random().toString(36).substring(2,10);return`usr_${e}_${s}`}function _n(){let e=Date.now().toString(36),s=Math.random().toString(36).substring(2,10);return`ast_${e}_${s}`}var Gt=class{constructor(s={},o){this.config=s;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=s=>{var o,t;s.type==="message"?this.upsertMessage(s.message):s.type==="status"?(this.setStatus(s.status),s.status==="connecting"?this.setStreaming(!0):(s.status==="idle"||s.status==="error")&&(this.setStreaming(!1),this.abortController=null)):s.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,s.error))};var t;this.messages=[...(t=s.initialMessages)!=null?t:[]].map(r=>{var n;return{...r,sequence:(n=r.sequence)!=null?n:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yt(s),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var s,o;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(o=(s=this.callbacks).onError)==null||o.call(s,t instanceof Error?t:new Error(String(t))),null}}setClientSession(s){if(this.clientSession=s,s.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:s.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){var s;return(s=this.clientSession)!=null?s:this.client.getClientSession()}isSessionValid(){let s=this.getClientSession();return s?new Date<s.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(s,o){return this.client.submitMessageFeedback(s,o)}async submitCSATFeedback(s,o){return this.client.submitCSATFeedback(s,o)}async submitNPSFeedback(s,o){return this.client.submitNPSFeedback(s,o)}updateConfig(s){this.config={...this.config,...s},this.client=new Yt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(s){this.handleEvent(s)}async sendMessage(s,o){var c,w,g,p,f;let t=s.trim();if(!t)return;(c=this.abortController)==null||c.abort();let r=Dn(),n=_n(),i={id:r,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:n},this.handleEvent)}catch(m){let F={id:n,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(F),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m instanceof Error?(g=(w=this.callbacks).onError)==null||g.call(w,m):(f=(p=this.callbacks).onError)==null||f.call(p,new Error(String(m)))}}cancel(){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(s){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(s.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(s){this.status!==s&&(this.status=s,this.callbacks.onStatusChanged(s))}setStreaming(s){this.streaming!==s&&(this.streaming=s,this.callbacks.onStreamingChanged(s))}appendMessage(s){let o=this.ensureSequence(s);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(s){let o=this.ensureSequence(s),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,n)=>n===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(s){return s.sequence!==void 0?{...s}:{...s,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(s){return[...s].sort((o,t)=>{var d,c;let r=new Date(o.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let i=(d=o.sequence)!=null?d:0,a=(c=t.sequence)!=null?c:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var as=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Zr=e=>{var n,i,a;let s=(n=e==null?void 0:e.colorScheme)!=null?n:"light",o=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:o;return s==="light"?o:s==="dark"||as()==="dark"?t:o},gr=e=>{let s=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(as())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),s.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(as());o.addEventListener?(o.addEventListener("change",t),s.push(()=>o.removeEventListener("change",t))):o.addListener&&(o.addListener(t),s.push(()=>o.removeListener(t)))}return()=>{s.forEach(o=>o())}},jn=(e,s)=>{let o=Zr(s);Object.entries(o).forEach(([t,r])=>{if(r==null||r==="")return;let n=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${n}`,String(r))})};var ei=Ur(require("lucide"),1),de=(e,s=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),n=ei[r];return n?ti(n,s,o,t):(console.warn(`Lucide icon "${e}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${e}":`,r),null}};function ti(e,s,o,t){if(!e||!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(s)),r.setAttribute("height",String(s)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(n=>{if(Array.isArray(n)&&n.length>=2){let i=n[0],a=n[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,w])=>{c!=="stroke"&&d.setAttribute(c,String(w))}),r.appendChild(d)}}}),r}var h=(e,s)=>{let o=document.createElement(e);return s&&(o.className=s),o};var mr=require("idiomorph"),hr=(e,s,o={})=>{let{preserveTypingAnimation:t=!0}=o;mr.Idiomorph.morph(e,s.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,n){if(r instanceof HTMLElement&&t&&r.classList.contains("tvw-animate-typing"))return!1}}})};var tt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var At={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var vn=(e,s)=>{let o=h("button");o.type="button",o.innerHTML=`
8
8
  <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
10
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -12,12 +12,12 @@
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
- `,s.addEventListener("click",t);let e=o=>{var y,S,R,v,N,x,k,Y,z,j,O,q;let i=(y=o.launcher)!=null?y:{},l=s.querySelector("[data-role='launcher-title']");l&&(l.textContent=(S=i.title)!=null?S:"Chat Assistant");let d=s.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(R=i.subtitle)!=null?R:"Get answers fast");let c=s.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let w=s.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let U=(v=i.agentIconSize)!=null?v:"40px";if(w.style.height=U,w.style.width=U,w.innerHTML="",i.agentIconName){let J=parseFloat(U)||24,V=de(i.agentIconName,J*.6,"#ffffff",2);V?(w.appendChild(V),w.style.display=""):(w.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(x=i.agentIconText)!=null?x:"\u{1F4AC}",w.style.display="")}let g=s.querySelector("[data-role='launcher-image']");if(g){let U=(k=i.agentIconSize)!=null?k:"40px";g.style.height=U,g.style.width=U,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(g.src=i.iconUrl,g.style.display="block"):g.style.display="none"}let p=s.querySelector("[data-role='launcher-call-to-action-icon']");if(p){let U=(Y=i.callToActionIconSize)!=null?Y:"32px";p.style.height=U,p.style.width=U,i.callToActionIconBackgroundColor?(p.style.backgroundColor=i.callToActionIconBackgroundColor,p.classList.remove("tvw-bg-cw-primary")):(p.style.backgroundColor="",p.classList.add("tvw-bg-cw-primary"));let J=0;if(i.callToActionIconPadding?(p.style.boxSizing="border-box",p.style.padding=i.callToActionIconPadding,J=(parseFloat(i.callToActionIconPadding)||0)*2):(p.style.boxSizing="",p.style.padding=""),i.callToActionIconHidden)p.style.display="none";else if(p.style.display="",p.innerHTML="",i.callToActionIconName){let V=parseFloat(U)||24,it=Math.max(V-J,8),se=de(i.callToActionIconName,it,"currentColor",2);se?p.appendChild(se):p.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else p.textContent=(j=i.callToActionIconText)!=null?j:"\u2197"}let f=i.position&&At[i.position]?At[i.position]:At["bottom-right"],m="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";s.className=`${m} ${f}`;let F="1px solid #e5e7eb",M="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";s.style.border=(O=i.border)!=null?O:F,s.style.boxShadow=(q=i.shadow)!=null?q:M},r=()=>{s.removeEventListener("click",t),s.remove()};return n&&e(n),{element:s,update:e,destroy:r}};var Pt=n=>{var j,O,q,U,J,V,it,se,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,P,$e,ut,pt,Lt,bt,Ct,Fe,et,xt,ke,Le;let{config:t,showClose:s=!0}=n,e=h("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(j=t==null?void 0:t.launcher)!=null?j:{},o=(O=r.headerIconSize)!=null?O:"48px",i=(q=r.closeButtonSize)!=null?q:"32px",l=(U=r.closeButtonPlacement)!=null?U:"inline",d=(J=r.headerIconHidden)!=null?J:!1,c=r.headerIconName,w=h("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=o,w.style.width=o,!d)if(c){let b=parseFloat(o)||24,Be=de(c,b*.6,"#ffffff",2);Be?w.replaceChildren(Be):w.textContent=(it=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?it:"\u{1F4AC}"}else if((se=t==null?void 0:t.launcher)!=null&&se.iconUrl){let b=h("img");b.src=t.launcher.iconUrl,b.alt="",b.className="tvw-rounded-xl tvw-object-cover",b.style.height=o,b.style.width=o,w.replaceChildren(b)}else w.textContent=(Ve=(D=t==null?void 0:t.launcher)==null?void 0:D.agentIconText)!=null?Ve:"\u{1F4AC}";let g=h("div","tvw-flex tvw-flex-col"),p=h("span","tvw-text-base tvw-font-semibold");p.textContent=(at=(nt=t==null?void 0:t.launcher)==null?void 0:nt.title)!=null?at:"Chat Assistant";let f=h("span","tvw-text-xs tvw-text-cw-muted");f.textContent=(Et=(Tt=t==null?void 0:t.launcher)==null?void 0:Tt.subtitle)!=null?Et:"Here to help you get answers fast",g.append(p,f),d?e.append(g):e.append(w,g);let m=(_=r.clearChat)!=null?_:{},F=(ue=m.enabled)!=null?ue:!0,M=(Ge=m.placement)!=null?Ge:"inline",y=null,S=null;if(F){let b=(Qe=m.size)!=null?Qe:"32px",Be=(_e=m.iconName)!=null?_e:"refresh-cw",Ee=(Ze=m.iconColor)!=null?Ze:"",Ke=(P=m.backgroundColor)!=null?P:"",st=($e=m.borderWidth)!=null?$e:"",ot=(ut=m.borderColor)!=null?ut:"",gt=(pt=m.borderRadius)!=null?pt:"",mt=(Lt=m.paddingX)!=null?Lt:"",Mt=(bt=m.paddingY)!=null?bt:"",$t=(Ct=m.tooltipText)!=null?Ct:"Clear chat",Xt=(Fe=m.showTooltip)!=null?Fe:!0;S=h("div",M==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),M==="top-right"&&(S.style.right="48px"),y=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),y.style.height=b,y.style.width=b,y.type="button",y.setAttribute("aria-label",$t);let Ot=de(Be,"20px",Ee||"",2);if(Ot&&y.appendChild(Ot),Ee&&(y.style.color=Ee,y.classList.remove("tvw-text-cw-muted")),Ke&&(y.style.backgroundColor=Ke,y.classList.remove("hover:tvw-bg-gray-100")),st||ot){let He=st||"0px",ht=ot||"transparent";y.style.border=`${He} solid ${ht}`,y.classList.remove("tvw-border-none")}if(gt&&(y.style.borderRadius=gt,y.classList.remove("tvw-rounded-full")),mt?(y.style.paddingLeft=mt,y.style.paddingRight=mt):(y.style.paddingLeft="",y.style.paddingRight=""),Mt?(y.style.paddingTop=Mt,y.style.paddingBottom=Mt):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),Xt&&$t&&y&&S){let He=null,ht=()=>{if(He||!y)return;He=h("div","tvw-clear-chat-tooltip"),He.textContent=$t;let Ft=h("div");Ft.className="tvw-clear-chat-tooltip-arrow",He.appendChild(Ft);let Bt=y.getBoundingClientRect();He.style.position="fixed",He.style.left=`${Bt.left+Bt.width/2}px`,He.style.top=`${Bt.top-8}px`,He.style.transform="translate(-50%, -100%)",document.body.appendChild(He)},pe=()=>{He&&He.parentNode&&(He.parentNode.removeChild(He),He=null)};S.addEventListener("mouseenter",ht),S.addEventListener("mouseleave",pe),y.addEventListener("focus",ht),y.addEventListener("blur",pe),S._cleanupTooltip=()=>{pe(),S&&(S.removeEventListener("mouseenter",ht),S.removeEventListener("mouseleave",pe)),y&&(y.removeEventListener("focus",ht),y.removeEventListener("blur",pe))}}M==="inline"&&e.appendChild(S)}let R=h("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":F&&M==="inline"?"":"tvw-ml-auto"),v=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let N=(et=r.closeButtonTooltipText)!=null?et:"Close chat",x=(xt=r.closeButtonShowTooltip)!=null?xt:!0;v.setAttribute("aria-label",N),v.style.display=s?"":"none";let k=(ke=r.closeButtonIconName)!=null?ke:"x",Y=(Le=r.closeButtonIconText)!=null?Le:"\xD7",z=de(k,"20px",r.closeButtonColor||"",2);if(z?v.appendChild(z):v.textContent=Y,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 b=r.closeButtonBorderWidth||"0px",Be=r.closeButtonBorderColor||"transparent";v.style.border=`${b} solid ${Be}`,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=""),R.appendChild(v),x&&N){let b=null,Be=()=>{if(b)return;b=h("div","tvw-clear-chat-tooltip"),b.textContent=N;let Ke=h("div");Ke.className="tvw-clear-chat-tooltip-arrow",b.appendChild(Ke);let st=v.getBoundingClientRect();b.style.position="fixed",b.style.left=`${st.left+st.width/2}px`,b.style.top=`${st.top-8}px`,b.style.transform="translate(-50%, -100%)",document.body.appendChild(b)},Ee=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};R.addEventListener("mouseenter",Be),R.addEventListener("mouseleave",Ee),v.addEventListener("focus",Be),v.addEventListener("blur",Ee),R._cleanupTooltip=()=>{Ee(),R.removeEventListener("mouseenter",Be),R.removeEventListener("mouseleave",Ee),v.removeEventListener("focus",Be),v.removeEventListener("blur",Ee)}}return l!=="top-right"&&e.appendChild(R),{header:e,iconHolder:w,headerTitle:p,headerSubtitle:f,closeButton:v,closeButtonWrapper:R,clearChatButton:y,clearChatButtonWrapper:S}},Yt=(n,t,s)=>{var i,l,d,c;let e=(i=s==null?void 0:s.launcher)!=null?i:{},r=(l=e.closeButtonPlacement)!=null?l:"inline",o=(c=(d=e.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),r==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var as=n=>Pt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),ls=n=>{var m,F,M,y;let{config:t,showClose:s=!0,onClose:e}=n,r=(m=t==null?void 0:t.launcher)!=null?m:{},o=h("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=h("span","tvw-text-base tvw-font-semibold");i.textContent=(F=r.title)!=null?F:"Chat Assistant",o.appendChild(i);let l=(M=r.closeButtonSize)!=null?M:"32px",d=h("div",""),c=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=l,c.style.width=l,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=s?"":"none";let w=(y=r.closeButtonIconName)!=null?y:"x",g=de(w,"20px",r.closeButtonColor||"",2);g?c.appendChild(g):c.textContent="\xD7",e&&c.addEventListener("click",e),d.appendChild(c),o.appendChild(d);let p=h("div");p.style.display="none";let f=h("span");return f.style.display="none",{header:o,iconHolder:p,headerTitle:i,headerSubtitle:f,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},ds=n=>{var v,N,x,k,Y,z,j,O;let{config:t,showClose:s=!0,onClose:e,onClearChat:r}=n,o=(v=t==null?void 0:t.launcher)!=null?v:{},i=h("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=h("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=o.headerIconSize)!=null?N:"56px",c=h("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let w=o.headerIconName;if(w){let q=parseFloat(d)||24,U=de(w,q*.5,"#ffffff",2);U?c.replaceChildren(U):c.textContent=(x=o.agentIconText)!=null?x:"\u{1F4AC}"}else if(o.iconUrl){let q=h("img");q.src=o.iconUrl,q.alt="",q.className="tvw-rounded-xl tvw-object-cover",q.style.height=d,q.style.width=d,c.replaceChildren(q)}else c.textContent=(k=o.agentIconText)!=null?k:"\u{1F4AC}";let g=h("div","tvw-flex tvw-flex-col tvw-flex-1"),p=h("span","tvw-text-lg tvw-font-semibold");p.textContent=(Y=o.title)!=null?Y:"Chat Assistant";let f=h("span","tvw-text-sm tvw-text-cw-muted");f.textContent=(z=o.subtitle)!=null?z:"Here to help you get answers fast",g.append(p,f),l.append(c,g);let m=(j=o.closeButtonSize)!=null?j:"32px",F=h("div",""),M=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");M.style.height=m,M.style.width=m,M.type="button",M.setAttribute("aria-label","Close chat"),M.style.display=s?"":"none";let y=(O=o.closeButtonIconName)!=null?O:"x",S=de(y,"20px",o.closeButtonColor||"",2);S?M.appendChild(S):M.textContent="\xD7",e&&M.addEventListener("click",e),F.appendChild(M),l.appendChild(F),i.appendChild(l);let R=h("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return R.textContent="Online and ready to help",i.appendChild(R),{header:i,iconHolder:c,headerTitle:p,headerSubtitle:f,closeButton:M,closeButtonWrapper:F,clearChatButton:null,clearChatButtonWrapper:null}},jn={default:as,minimal:ls,expanded:ds},cs=n=>{var t;return(t=jn[n])!=null?t:jn.default},Gt=(n,t,s)=>{var i,l,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat}),w=h("div");w.style.display="none";let g=h("span"),p=h("span"),f=h("button");f.style.display="none";let m=h("div");return m.style.display="none",{header:c,iconHolder:w,headerTitle:g,headerSubtitle:p,closeButton:f,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",o=cs(e)({config:n,showClose:(d=(l=t==null?void 0:t.showCloseButton)!=null?l:s==null?void 0:s.showClose)!=null?d:!0,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Vr=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 V,it,se,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,P,$e,ut,pt,Lt,bt,Ct,Fe,et,xt;let{config:t}=n,s=h("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=h("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((V=t==null?void 0:t.voiceRecognition)==null?void 0:V.enabled)===!0,o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=h("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`);d.style.outline="none";let c=h("textarea");c.placeholder=(se=(it=t==null?void 0:t.copy)==null?void 0:it.inputPlaceholder)!=null?se:"Type your message\u2026",c.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",c.rows=1;let w=(Ve=(D=t==null?void 0:t.theme)==null?void 0:D.inputFontFamily)!=null?Ve:"sans-serif",g=(at=(nt=t==null?void 0:t.theme)==null?void 0:nt.inputFontWeight)!=null?at:"400";c.style.fontFamily=Vr(w),c.style.fontWeight=g,c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.addEventListener("focus",()=>{c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.style.boxShadow="none"}),c.addEventListener("blur",()=>{c.style.border="none",c.style.outline="none"});let p=(Tt=t==null?void 0:t.sendButton)!=null?Tt:{},f=(Et=p.useIcon)!=null?Et:!1,m=(_=p.iconText)!=null?_:"\u2191",F=p.iconName,M=(ue=p.tooltipText)!=null?ue:"Send message",y=(Ge=p.showTooltip)!=null?Ge:!1,S=(Qe=p.size)!=null?Qe:"40px",R=p.backgroundColor,v=p.textColor,N=h("div","tvw-send-button-wrapper"),x=h("button",f?"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",f){if(x.style.width=S,x.style.height=S,x.style.minWidth=S,x.style.minHeight=S,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",F){let ke=parseFloat(S)||24,Le=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",b=de(F,ke,Le,2);b?(x.appendChild(b),x.style.color=Le):(x.textContent=m,v?x.style.color=v:x.classList.add("tvw-text-white"))}else x.textContent=m,v?x.style.color=v:x.classList.add("tvw-text-white");R?x.style.backgroundColor=R:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(Ze=(_e=t==null?void 0:t.copy)==null?void 0:_e.sendButtonLabel)!=null?Ze:"Send",v?x.style.color=v:x.classList.add("tvw-text-white");if(p.borderWidth&&(x.style.borderWidth=p.borderWidth,x.style.borderStyle="solid"),p.borderColor&&(x.style.borderColor=p.borderColor),p.paddingX?(x.style.paddingLeft=p.paddingX,x.style.paddingRight=p.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),p.paddingY?(x.style.paddingTop=p.paddingY,x.style.paddingBottom=p.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),y&&M){let ke=h("div","tvw-send-button-tooltip");ke.textContent=M,N.appendChild(ke)}N.appendChild(x);let k=(P=t==null?void 0:t.voiceRecognition)!=null?P:{},Y=k.enabled===!0,z=null,j=null,O=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Y&&O){j=h("div","tvw-send-button-wrapper"),z=h("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),z.type="button",z.setAttribute("aria-label","Start voice recognition");let ke=($e=k.iconName)!=null?$e:"mic",Le=(ut=k.iconSize)!=null?ut:S,b=parseFloat(Le)||24,Be=(pt=k.backgroundColor)!=null?pt:R,Ee=(Lt=k.iconColor)!=null?Lt:v;z.style.width=Le,z.style.height=Le,z.style.minWidth=Le,z.style.minHeight=Le,z.style.fontSize="18px",z.style.lineHeight="1";let Ke=Ee||"currentColor",st=de(ke,b,Ke,1.5);st?(z.appendChild(st),z.style.color=Ke):(z.textContent="\u{1F3A4}",z.style.color=Ke),Be?z.style.backgroundColor=Be:z.classList.add("tvw-bg-cw-primary"),Ee?z.style.color=Ee:!Ee&&!v&&z.classList.add("tvw-text-white"),k.borderWidth&&(z.style.borderWidth=k.borderWidth,z.style.borderStyle="solid"),k.borderColor&&(z.style.borderColor=k.borderColor),k.paddingX&&(z.style.paddingLeft=k.paddingX,z.style.paddingRight=k.paddingX),k.paddingY&&(z.style.paddingTop=k.paddingY,z.style.paddingBottom=k.paddingY),j.appendChild(z);let ot=(bt=k.tooltipText)!=null?bt:"Start voice recognition";if(((Ct=k.showTooltip)!=null?Ct:!1)&&ot){let mt=h("div","tvw-send-button-tooltip");mt.textContent=ot,j.appendChild(mt)}}d.addEventListener("click",ke=>{ke.target!==x&&ke.target!==N&&ke.target!==z&&ke.target!==j&&c.focus()}),d.append(c),j&&d.append(j),d.append(N);let q=h("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),U=(Fe=t==null?void 0:t.statusIndicator)!=null?Fe:{},J=(et=U.visible)!=null?et:!0;return q.style.display=J?"":"none",q.textContent=(xt=U.idleText)!=null?xt:"Online",s.append(e,d,q),{footer:s,suggestions:e,composerForm:d,textarea:c,sendButton:x,sendButtonWrapper:N,micButton:z,micButtonWrapper:j,statusText:q}};var mr=n=>{var d,c,w,g,p,f,m;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let F=h("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),M=h("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(g=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?g:"100%";return F.style.width=y,M.style.width="100%",F.appendChild(M),{wrapper:F,panel:M}}let s=(p=n==null?void 0:n.launcher)!=null?p:{},e=s.position&&At[s.position]?At[s.position]:At["bottom-right"],r=h("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),o=h("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(m=(f=n==null?void 0:n.launcher)==null?void 0:f.width)!=null?m:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return o.style.width=l,o.style.maxWidth=l,r.appendChild(o),{wrapper:r,panel:o}},hr=(n,t=!0)=>{var f,m,F,M,y,S,R;let s=h("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),e=(f=n==null?void 0:n.layout)==null?void 0:f.header,r=((m=n==null?void 0:n.layout)==null?void 0:m.showHeader)!==!1,o=e?Gt(n,e,{showClose:t}):Pt({config:n,showClose:t}),i=h("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="vanilla-agent-scroll-container";let l=h("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=h("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(M=(F=n==null?void 0:n.copy)==null?void 0:F.welcomeTitle)!=null?M:"Hello \u{1F44B}";let c=h("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(S=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",l.append(d,c);let w=h("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(l,w);let g=Qt({config:n}),p=((R=n==null?void 0:n.layout)==null?void 0:R.showFooter)!==!1;return r?Yt(s,o,n):(o.header.style.display="none",Yt(s,o,n)),s.append(i),p||(g.footer.style.display="none"),s.append(g.footer),{container:s,body:i,messagesWrapper:w,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:c,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:g.footer}};var vn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="0ms";let 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 e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(t),n.appendChild(s),n.appendChild(e),n.appendChild(r),n},Gr=(n,t)=>{let s=h("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let r=h("img");r.src=e,r.alt=t==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",s.appendChild(r)}else s.textContent=e,s.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else s.textContent=t==="user"?"U":"A",s.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return s},fr=(n,t)=>{let s=h("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?s.textContent=t.format(e):s.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s},Qr=(n,t="bubble")=>{let s=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){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},us=(n,t,s)=>{var m,F,M,y,S,R;let e=(m=t.showCopy)!=null?m:!0,r=(F=t.showUpvote)!=null?F:!0,o=(M=t.showDownvote)!=null?M:!0,i=(y=t.visibility)!=null?y:"hover",l=(S=t.align)!=null?S:"right",d=(R=t.layout)!=null?R:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],g=h("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`);g.id=`actions-${n.id}`,g.setAttribute("data-actions-for",n.id);let p=null,f=(v,N,x,k)=>{let Y=document.createElement("button");Y.className="tvw-message-action-btn",Y.setAttribute("aria-label",N),Y.setAttribute("title",N),k&&Y.setAttribute("data-action",k);let z=de(v,14,"currentColor",2);return z&&Y.appendChild(z),Y.addEventListener("click",j=>{j.preventDefault(),j.stopPropagation(),x()}),Y};if(e){let v=f("copy","Copy message",()=>{let N=n.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let x=de("check",14,"currentColor",2);x&&(v.innerHTML="",v.appendChild(x)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=de("copy",14,"currentColor",2);k&&(v.innerHTML="",v.appendChild(k))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),s!=null&&s.onCopy&&s.onCopy(n),t.onCopy&&t.onCopy(n)},"copy");g.appendChild(v)}if(r){let v=f("thumbs-up","Upvote",()=>{if(p==="upvote")p=null,v.classList.remove("tvw-message-action-active");else{let x=g.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),p="upvote",v.classList.add("tvw-message-action-active");let k={type:"upvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(k),t.onFeedback&&t.onFeedback(k)}},"upvote");g.appendChild(v)}if(o){let v=f("thumbs-down","Downvote",()=>{if(p==="downvote")p=null,v.classList.remove("tvw-message-action-active");else{let x=g.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),p="downvote",v.classList.add("tvw-message-action-active");let k={type:"downvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(k),t.onFeedback&&t.onFeedback(k)}},"downvote");g.appendChild(v)}return g},Zt=(n,t,s,e,r)=>{var R,v,N,x,k;let o=s!=null?s:{},i=(R=o.layout)!=null?R:"bubble",l=o.avatar,d=o.timestamp,c=(v=l==null?void 0:l.show)!=null?v:!1,w=(N=d==null?void 0:d.show)!=null?N:!1,g=(x=l==null?void 0:l.position)!=null?x:"left",p=(k=d==null?void 0:d.position)!=null?k:"below",f=Qr(n.role,i),m=h("div",f.join(" "));m.id=`bubble-${n.id}`,m.setAttribute("data-message-id",n.id);let F=document.createElement("div");if(F.innerHTML=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),w&&p==="inline"&&n.createdAt){let Y=fr(n,d);Y.classList.add("tvw-ml-2","tvw-inline"),F.appendChild(Y)}if(m.appendChild(F),w&&p==="below"&&n.createdAt){let Y=fr(n,d);Y.classList.add("tvw-mt-1"),m.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=vn();m.appendChild(Y)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let Y=us(n,e,r);m.appendChild(Y)}if(!c||n.role==="system")return m;let y=h("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),S=Gr(l,n.role);return g==="right"||g==="left"&&n.role==="user"?y.append(m,S):y.append(S,m),m.classList.remove("tvw-max-w-[85%]"),m.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},wr=(n,t,s,e,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}):Zt(n,t,s,e,r)};var en=new Set,yr=(n,t)=>{let s=en.has(n),e=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".tvw-border-t");if(!e||!r)return;e.setAttribute("aria-expanded",s?"true":"false");let o=e.querySelector(".tvw-ml-auto"),i=o==null?void 0:o.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=de(s?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=s?"Hide":"Show"}r.style.display=s?"":"none"},ps=n=>{let t=n.reasoning,s=h("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),!t)return s;let e=en.has(n.id),r=h("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",e?"true":"false"),r.setAttribute("data-expand-header","true"),r.setAttribute("data-bubble-type","reasoning");let o=h("div","tvw-flex tvw-flex-col tvw-text-left"),i=h("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",o.appendChild(i);let l=h("span","tvw-text-xs tvw-text-cw-primary");l.textContent=ir(t),o.appendChild(l),t.status==="complete"?i.style.display="none":i.style.display="";let d=h("div","tvw-flex tvw-items-center"),w=de(e?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=e?"Hide":"Show";let g=h("div","tvw-flex tvw-items-center tvw-ml-auto");g.append(d),r.append(o,g);let p=h("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");p.style.display=e?"":"none";let f=t.chunks.join(""),m=h("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return m.textContent=f||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),p.appendChild(m),(()=>{r.setAttribute("aria-expanded",e?"true":"false"),d.innerHTML="";let y=de(e?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=e?"Hide":"Show",p.style.display=e?"":"none"})(),s.append(r,p),s};var tn=new Set,vr=(n,t,s)=>{var c;let e=tn.has(n),r=(c=s==null?void 0:s.toolCall)!=null?c:{},o=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".tvw-border-t");if(!o||!i)return;o.setAttribute("aria-expanded",e?"true":"false");let l=o.querySelector(".tvw-ml-auto"),d=l==null?void 0:l.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let w=r.toggleTextColor||r.headerTextColor||"currentColor",g=de(e?"chevron-up":"chevron-down",16,w,2);g?d.appendChild(g):d.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},gs=(n,t)=>{var F;let s=n.toolCall,e=(F=t==null?void 0:t.toolCall)!=null?F:{},r=h("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),e.backgroundColor&&(r.style.backgroundColor=e.backgroundColor),e.borderColor&&(r.style.borderColor=e.borderColor),e.borderWidth&&(r.style.borderWidth=e.borderWidth),e.borderRadius&&(r.style.borderRadius=e.borderRadius),!s)return r;let o=tn.has(n.id),i=h("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",o?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let l=h("div","tvw-flex tvw-flex-col tvw-text-left"),d=h("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(d.style.color=e.headerTextColor),d.textContent=ar(s),l.appendChild(d);let c=h("div","tvw-flex tvw-items-center"),w=e.toggleTextColor||e.headerTextColor||"currentColor",g=de(o?"chevron-up":"chevron-down",16,w,2);g?c.appendChild(g):c.textContent=o?"Hide":"Show";let p=h("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");p.append(c),i.append(l,p);let f=h("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(f.style.display=o?"":"none",e.contentBackgroundColor&&(f.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(f.style.color=e.contentTextColor),e.contentPaddingX&&(f.style.paddingLeft=e.contentPaddingX,f.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(f.style.paddingTop=e.contentPaddingY,f.style.paddingBottom=e.contentPaddingY),s.name){let M=h("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?M.style.color=e.contentTextColor:e.headerTextColor&&(M.style.color=e.headerTextColor),M.textContent=s.name,f.appendChild(M)}if(s.args!==void 0){let M=h("div","tvw-space-y-1"),y=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(y.style.color=e.labelTextColor),y.textContent="Arguments";let S=h("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(S.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(S.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(S.style.color=e.codeBlockTextColor),S.textContent=rs(s.args),M.append(y,S),f.appendChild(M)}if(s.chunks&&s.chunks.length){let M=h("div","tvw-space-y-1"),y=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(y.style.color=e.labelTextColor),y.textContent="Activity";let S=h("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(S.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(S.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(S.style.color=e.codeBlockTextColor),S.textContent=s.chunks.join(`
16
- `),M.append(y,S),f.appendChild(M)}if(s.status==="complete"&&s.result!==void 0){let M=h("div","tvw-space-y-1"),y=h("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(y.style.color=e.labelTextColor),y.textContent="Result";let S=h("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(S.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(S.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(S.style.color=e.codeBlockTextColor),S.textContent=rs(s.result),M.append(y,S),f.appendChild(M)}if(s.status==="complete"&&typeof s.duration=="number"){let M=h("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(M.style.color=e.contentTextColor),M.textContent=`Duration: ${s.duration}ms`,f.appendChild(M)}return(()=>{i.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let M=e.toggleTextColor||e.headerTextColor||"currentColor",y=de(o?"chevron-up":"chevron-down",16,M,2);y?c.appendChild(y):c.textContent=o?"Hide":"Show",f.style.display=o?"":"none"})(),r.append(i,f),r};var br=n=>{let t=[];return{buttons:t,render:(e,r,o,i,l)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:r?r.getMessages():[]).some(f=>f.role==="user"))return;let w=document.createDocumentFragment(),g=r?r.isStreaming():!1,p=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(f=>{let m=h("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");m.type="button",m.textContent=f,m.disabled=g,l!=null&&l.fontFamily&&(m.style.fontFamily=p(l.fontFamily)),l!=null&&l.fontWeight&&(m.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(m.style.paddingLeft=l.paddingX,m.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(m.style.paddingTop=l.paddingY,m.style.paddingBottom=l.paddingY),m.addEventListener("click",()=>{!r||r.isStreaming()||(o.value="",r.sendMessage(f))}),w.appendChild(m),t.push(m)}),n.appendChild(w)}}};var Cr={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},ms=(n,t,s,e)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(o=>{var m,F,M;if(o.dataset.enhanced==="true")return;let i=(m=o.dataset.tvForm)!=null?m:"init";o.dataset.enhanced="true";let l=(F=Cr[i])!=null?F:Cr.init;o.classList.add("tvw-form-card","tvw-space-y-4");let d=h("div","tvw-space-y-1"),c=h("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=l.title,d.appendChild(c),l.description){let y=h("p","tvw-text-sm tvw-text-cw-muted");y.textContent=l.description,d.appendChild(y)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(y=>{var x,k;let S=h("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${t.id}-${i}-${y.name}`;let R=h("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");R.textContent=y.label,S.appendChild(R);let v=(x=y.type)!=null?x:"text",N;v==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=v),N.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",N.id=`${t.id}-${i}-${y.name}`,N.name=y.name,N.placeholder=(k=y.placeholder)!=null?k:"",y.required&&(N.required=!0),S.appendChild(N),w.appendChild(S)});let g=h("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),p=h("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),f=h("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");f.type="submit",f.textContent=(M=l.submitLabel)!=null?M:"Submit",g.appendChild(p),g.appendChild(f),w.appendChild(g),o.replaceChildren(d,w),w.addEventListener("submit",async y=>{var N,x;y.preventDefault();let S=(N=s.formEndpoint)!=null?N:"/form",R=new FormData(w),v={};R.forEach((k,Y)=>{v[Y]=k}),v.type=i,f.disabled=!0,p.textContent="Submitting\u2026";try{let k=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let Y=await k.json();p.textContent=(x=Y.message)!=null?x:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await e.sendMessage(String(Y.nextPrompt))}catch(k){p.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var hs=class{constructor(){this.plugins=new Map}register(t){var s;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(s=t.onRegister)==null||s.call(t)}unregister(t){var e;let s=this.plugins.get(t);s&&((e=s.onUnregister)==null||e.call(s),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,s)=>{var e,r;return((e=s.priority)!=null?e:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let s=this.getAll();if(!t||t.length===0)return s;let e=new Set(t.map(o=>o.id));return[...s.filter(o=>!e.has(o.id)),...t].sort((o,i)=>{var l,d;return((l=i.priority)!=null?l:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var s;return(s=t.onUnregister)==null?void 0:s.call(t)}),this.plugins.clear()}},bn=new hs;var fs={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"},ws={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},Me={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:fs,darkTheme:ws,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function qn(n){var t,s,e,r,o,i,l,d,c,w,g,p,f,m,F,M,y,S,R;return n?{...Me,...n,theme:{...Me.theme,...n.theme},darkTheme:{...Me.darkTheme,...n.darkTheme},launcher:{...Me.launcher,...n.launcher,clearChat:{...(t=Me.launcher)==null?void 0:t.clearChat,...(s=n.launcher)==null?void 0:s.clearChat}},copy:{...Me.copy,...n.copy},sendButton:{...Me.sendButton,...n.sendButton},statusIndicator:{...Me.statusIndicator,...n.statusIndicator},voiceRecognition:{...Me.voiceRecognition,...n.voiceRecognition},features:{...Me.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:Me.suggestionChips,suggestionChipsConfig:{...Me.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Me.layout,...n.layout,header:{...(r=Me.layout)==null?void 0:r.header,...(o=n.layout)==null?void 0:o.header},messages:{...(i=Me.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(c=(d=Me.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(g=(w=n.layout)==null?void 0:w.messages)==null?void 0:g.avatar},timestamp:{...(f=(p=Me.layout)==null?void 0:p.messages)==null?void 0:f.timestamp,...(F=(m=n.layout)==null?void 0:m.messages)==null?void 0:F.timestamp}},slots:{...(M=Me.layout)==null?void 0:M.slots,...(y=n.layout)==null?void 0:y.slots}},markdown:{...Me.markdown,...n.markdown,options:{...(S=Me.markdown)==null?void 0:S.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...Me.messageActions,...n.messageActions}}:Me}var xr=()=>{let n=new Map,t=(r,o)=>(n.has(r)||n.set(r,new Set),n.get(r).add(o),()=>s(r,o)),s=(r,o)=>{var i;(i=n.get(r))==null||i.delete(o)};return{on:t,off:s,emit:(r,o)=>{var i;(i=n.get(r))==null||i.forEach(l=>{try{l(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Zr=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},ei=n=>{let t=n.trim(),s=t.indexOf("{");if(s===-1)return null;let e=0;for(let r=s;r<t.length;r+=1){let o=t[r];if(o==="{"&&(e+=1),o==="}"&&(e-=1,e===0))return t.slice(s,r+1)}return null},Cn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=Zr(n),s=ei(t);if(!s)return null;let e=JSON.parse(s);if(!e||typeof e!="object"||!e.action)return null;let{action:r,...o}=e;return{type:String(r),payload:o,raw:e}}catch{return null}},ys=n=>typeof n=="string"?n:n==null?"":String(n),Kt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:ys(n.payload.text)},messageAndClick:(n,t)=>{var r;if(n.type!=="message_and_click")return;let s=n.payload,e=ys(s.element);if(e&&((r=t.document)!=null&&r.querySelector)){let o=t.document.querySelector(e);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:ys(s.text)}}},Sr=n=>Array.isArray(n)?n.map(t=>String(t)):[],xn=n=>{let t=new Set(Sr(n.getSessionMetadata().processedActionMessageIds)),s=()=>{t=new Set(Sr(n.getSessionMetadata().processedActionMessageIds))},e=()=>{let o=Array.from(t);n.updateSessionMetadata(i=>({...i,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let i=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!i&&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=i?n.parsers.reduce((c,w)=>c||(w==null?void 0:w({text:i,message:o.message}))||null,null):null;if(!l)return null;t.add(o.message.id),e();let d={action:l,message:o.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let w=c(l,{message:o.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef});if(!w)continue;if(w.handled){let g=w.persistMessage!==!1;return{text:w.displayText!==void 0?w.displayText:"",persist:g}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:s}};var ti=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},ni=n=>n.map(t=>({...t,streaming:!1})),Un=(n="vanilla-agent-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let s=t();return s?ti(s.getItem(n)):null},save:s=>{let e=t();if(e)try{let r={...s,messages:s.messages?ni(s.messages):void 0};e.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let s=t();if(s)try{s.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var vs=class{constructor(){this.components=new Map}register(t,s){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,s)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([s,e])=>{this.register(s,e)})}},nn=new vs;var sn=require("partial-json");function si(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function oi(n,t){if(!si(n))return null;let s=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:s,raw:t}}function zn(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:s=>{let e=s.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(s.length<=t)return n;try{let r=(0,sn.parse)(s,sn.STR|sn.OBJ),o=oi(r,s);o&&(n=o)}catch{}return t=s.length,n},reset:()=>{n=null,t=0}}}function Ar(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Jn(n,t){let{config:s,message:e,onPropsUpdate:r}=t,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 i={message:e,config:s,updateProps:l=>{r&&r(l)}};try{return o(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Tr(){let n=zn();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Yn(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Kn(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var ri=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xn(n){let{onSubmit:t,onDismiss:s,title:e="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:c=ri}=n,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-csat",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Customer satisfaction feedback");let g=null,p=document.createElement("div");p.className="tvw-feedback-content";let f=document.createElement("div");f.className="tvw-feedback-header";let m=document.createElement("h3");m.className="tvw-feedback-title",m.textContent=e,f.appendChild(m);let F=document.createElement("p");F.className="tvw-feedback-subtitle",F.textContent=r,f.appendChild(F),p.appendChild(f);let M=document.createElement("div");M.className="tvw-feedback-rating tvw-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let x=1;x<=5;x++){let k=document.createElement("button");k.type="button",k.className="tvw-feedback-rating-btn tvw-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${c[x-1]}`),k.title=c[x-1],k.dataset.rating=String(x),k.innerHTML=`
15
+ `,o.addEventListener("click",s);let t=n=>{var y,S,R,v,O,x,W,Y,z,j,N,q;let i=(y=n.launcher)!=null?y:{},a=o.querySelector("[data-role='launcher-title']");a&&(a.textContent=(S=i.title)!=null?S:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(R=i.subtitle)!=null?R:"Get answers fast");let c=o.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let w=o.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let U=(v=i.agentIconSize)!=null?v:"40px";if(w.style.height=U,w.style.width=U,w.innerHTML="",i.agentIconName){let J=parseFloat(U)||24,V=de(i.agentIconName,J*.6,"#ffffff",2);V?(w.appendChild(V),w.style.display=""):(w.textContent=(O=i.agentIconText)!=null?O:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(x=i.agentIconText)!=null?x:"\u{1F4AC}",w.style.display="")}let g=o.querySelector("[data-role='launcher-image']");if(g){let U=(W=i.agentIconSize)!=null?W:"40px";g.style.height=U,g.style.width=U,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(g.src=i.iconUrl,g.style.display="block"):g.style.display="none"}let p=o.querySelector("[data-role='launcher-call-to-action-icon']");if(p){let U=(Y=i.callToActionIconSize)!=null?Y:"32px";p.style.height=U,p.style.width=U,i.callToActionIconBackgroundColor?(p.style.backgroundColor=i.callToActionIconBackgroundColor,p.classList.remove("tvw-bg-cw-primary")):(p.style.backgroundColor="",p.classList.add("tvw-bg-cw-primary"));let J=0;if(i.callToActionIconPadding?(p.style.boxSizing="border-box",p.style.padding=i.callToActionIconPadding,J=(parseFloat(i.callToActionIconPadding)||0)*2):(p.style.boxSizing="",p.style.padding=""),i.callToActionIconHidden)p.style.display="none";else if(p.style.display="",p.innerHTML="",i.callToActionIconName){let V=parseFloat(U)||24,it=Math.max(V-J,8),se=de(i.callToActionIconName,it,"currentColor",2);se?p.appendChild(se):p.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else p.textContent=(j=i.callToActionIconText)!=null?j:"\u2197"}let f=i.position&&At[i.position]?At[i.position]:At["bottom-right"],m="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${m} ${f}`;let F="1px solid #e5e7eb",M="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(N=i.border)!=null?N:F,o.style.boxShadow=(q=i.shadow)!=null?q:M},r=()=>{o.removeEventListener("click",s),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var It=e=>{var j,N,q,U,J,V,it,se,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,I,$e,ut,pt,Lt,bt,Ct,Fe,et,xt,We,Le;let{config:s,showClose:o=!0}=e,t=h("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(j=s==null?void 0:s.launcher)!=null?j:{},n=(N=r.headerIconSize)!=null?N:"48px",i=(q=r.closeButtonSize)!=null?q:"32px",a=(U=r.closeButtonPlacement)!=null?U:"inline",d=(J=r.headerIconHidden)!=null?J:!1,c=r.headerIconName,w=h("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=n,w.style.width=n,!d)if(c){let b=parseFloat(n)||24,He=de(c,b*.6,"#ffffff",2);He?w.replaceChildren(He):w.textContent=(it=(V=s==null?void 0:s.launcher)==null?void 0:V.agentIconText)!=null?it:"\u{1F4AC}"}else if((se=s==null?void 0:s.launcher)!=null&&se.iconUrl){let b=h("img");b.src=s.launcher.iconUrl,b.alt="",b.className="tvw-rounded-xl tvw-object-cover",b.style.height=n,b.style.width=n,w.replaceChildren(b)}else w.textContent=(Ve=(D=s==null?void 0:s.launcher)==null?void 0:D.agentIconText)!=null?Ve:"\u{1F4AC}";let g=h("div","tvw-flex tvw-flex-col"),p=h("span","tvw-text-base tvw-font-semibold");p.textContent=(at=(nt=s==null?void 0:s.launcher)==null?void 0:nt.title)!=null?at:"Chat Assistant";let f=h("span","tvw-text-xs tvw-text-cw-muted");f.textContent=(Et=(Tt=s==null?void 0:s.launcher)==null?void 0:Tt.subtitle)!=null?Et:"Here to help you get answers fast",g.append(p,f),d?t.append(g):t.append(w,g);let m=(_=r.clearChat)!=null?_:{},F=(ue=m.enabled)!=null?ue:!0,M=(Ge=m.placement)!=null?Ge:"inline",y=null,S=null;if(F){let b=(Qe=m.size)!=null?Qe:"32px",He=(_e=m.iconName)!=null?_e:"refresh-cw",Ee=(Ze=m.iconColor)!=null?Ze:"",Ke=(I=m.backgroundColor)!=null?I:"",st=($e=m.borderWidth)!=null?$e:"",ot=(ut=m.borderColor)!=null?ut:"",gt=(pt=m.borderRadius)!=null?pt:"",mt=(Lt=m.paddingX)!=null?Lt:"",Mt=(bt=m.paddingY)!=null?bt:"",Ft=(Ct=m.tooltipText)!=null?Ct:"Clear chat",Vt=(Fe=m.showTooltip)!=null?Fe:!0;S=h("div",M==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),M==="top-right"&&(S.style.right="48px"),y=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),y.style.height=b,y.style.width=b,y.type="button",y.setAttribute("aria-label",Ft);let Dt=de(He,"20px",Ee||"",2);if(Dt&&y.appendChild(Dt),Ee&&(y.style.color=Ee,y.classList.remove("tvw-text-cw-muted")),Ke&&(y.style.backgroundColor=Ke,y.classList.remove("hover:tvw-bg-gray-100")),st||ot){let Be=st||"0px",ht=ot||"transparent";y.style.border=`${Be} solid ${ht}`,y.classList.remove("tvw-border-none")}if(gt&&(y.style.borderRadius=gt,y.classList.remove("tvw-rounded-full")),mt?(y.style.paddingLeft=mt,y.style.paddingRight=mt):(y.style.paddingLeft="",y.style.paddingRight=""),Mt?(y.style.paddingTop=Mt,y.style.paddingBottom=Mt):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),Vt&&Ft&&y&&S){let Be=null,ht=()=>{if(Be||!y)return;Be=h("div","tvw-clear-chat-tooltip"),Be.textContent=Ft;let Ot=h("div");Ot.className="tvw-clear-chat-tooltip-arrow",Be.appendChild(Ot);let Ht=y.getBoundingClientRect();Be.style.position="fixed",Be.style.left=`${Ht.left+Ht.width/2}px`,Be.style.top=`${Ht.top-8}px`,Be.style.transform="translate(-50%, -100%)",document.body.appendChild(Be)},pe=()=>{Be&&Be.parentNode&&(Be.parentNode.removeChild(Be),Be=null)};S.addEventListener("mouseenter",ht),S.addEventListener("mouseleave",pe),y.addEventListener("focus",ht),y.addEventListener("blur",pe),S._cleanupTooltip=()=>{pe(),S&&(S.removeEventListener("mouseenter",ht),S.removeEventListener("mouseleave",pe)),y&&(y.removeEventListener("focus",ht),y.removeEventListener("blur",pe))}}M==="inline"&&t.appendChild(S)}let R=h("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":F&&M==="inline"?"":"tvw-ml-auto"),v=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let O=(et=r.closeButtonTooltipText)!=null?et:"Close chat",x=(xt=r.closeButtonShowTooltip)!=null?xt:!0;v.setAttribute("aria-label",O),v.style.display=o?"":"none";let W=(We=r.closeButtonIconName)!=null?We:"x",Y=(Le=r.closeButtonIconText)!=null?Le:"\xD7",z=de(W,"20px",r.closeButtonColor||"",2);if(z?v.appendChild(z):v.textContent=Y,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 b=r.closeButtonBorderWidth||"0px",He=r.closeButtonBorderColor||"transparent";v.style.border=`${b} solid ${He}`,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=""),R.appendChild(v),x&&O){let b=null,He=()=>{if(b)return;b=h("div","tvw-clear-chat-tooltip"),b.textContent=O;let Ke=h("div");Ke.className="tvw-clear-chat-tooltip-arrow",b.appendChild(Ke);let st=v.getBoundingClientRect();b.style.position="fixed",b.style.left=`${st.left+st.width/2}px`,b.style.top=`${st.top-8}px`,b.style.transform="translate(-50%, -100%)",document.body.appendChild(b)},Ee=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};R.addEventListener("mouseenter",He),R.addEventListener("mouseleave",Ee),v.addEventListener("focus",He),v.addEventListener("blur",Ee),R._cleanupTooltip=()=>{Ee(),R.removeEventListener("mouseenter",He),R.removeEventListener("mouseleave",Ee),v.removeEventListener("focus",He),v.removeEventListener("blur",Ee)}}return a!=="top-right"&&t.appendChild(R),{header:t,iconHolder:w,headerTitle:p,headerSubtitle:f,closeButton:v,closeButtonWrapper:R,clearChatButton:y,clearChatButtonWrapper:S}},Kt=(e,s,o)=>{var i,a,d,c;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",n=(c=(d=t.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(s.header),r==="top-right"&&(e.style.position="relative",e.appendChild(s.closeButtonWrapper)),s.clearChatButtonWrapper&&n==="top-right"&&(e.style.position="relative",e.appendChild(s.clearChatButtonWrapper))};var ls=e=>It({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),ds=e=>{var m,F,M,y;let{config:s,showClose:o=!0,onClose:t}=e,r=(m=s==null?void 0:s.launcher)!=null?m:{},n=h("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=h("span","tvw-text-base tvw-font-semibold");i.textContent=(F=r.title)!=null?F:"Chat Assistant",n.appendChild(i);let a=(M=r.closeButtonSize)!=null?M:"32px",d=h("div",""),c=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=a,c.style.width=a,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=o?"":"none";let w=(y=r.closeButtonIconName)!=null?y:"x",g=de(w,"20px",r.closeButtonColor||"",2);g?c.appendChild(g):c.textContent="\xD7",t&&c.addEventListener("click",t),d.appendChild(c),n.appendChild(d);let p=h("div");p.style.display="none";let f=h("span");return f.style.display="none",{header:n,iconHolder:p,headerTitle:i,headerSubtitle:f,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},cs=e=>{var v,O,x,W,Y,z,j,N;let{config:s,showClose:o=!0,onClose:t,onClearChat:r}=e,n=(v=s==null?void 0:s.launcher)!=null?v:{},i=h("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=h("div","tvw-flex tvw-items-center tvw-gap-3"),d=(O=n.headerIconSize)!=null?O:"56px",c=h("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let w=n.headerIconName;if(w){let q=parseFloat(d)||24,U=de(w,q*.5,"#ffffff",2);U?c.replaceChildren(U):c.textContent=(x=n.agentIconText)!=null?x:"\u{1F4AC}"}else if(n.iconUrl){let q=h("img");q.src=n.iconUrl,q.alt="",q.className="tvw-rounded-xl tvw-object-cover",q.style.height=d,q.style.width=d,c.replaceChildren(q)}else c.textContent=(W=n.agentIconText)!=null?W:"\u{1F4AC}";let g=h("div","tvw-flex tvw-flex-col tvw-flex-1"),p=h("span","tvw-text-lg tvw-font-semibold");p.textContent=(Y=n.title)!=null?Y:"Chat Assistant";let f=h("span","tvw-text-sm tvw-text-cw-muted");f.textContent=(z=n.subtitle)!=null?z:"Here to help you get answers fast",g.append(p,f),a.append(c,g);let m=(j=n.closeButtonSize)!=null?j:"32px",F=h("div",""),M=h("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");M.style.height=m,M.style.width=m,M.type="button",M.setAttribute("aria-label","Close chat"),M.style.display=o?"":"none";let y=(N=n.closeButtonIconName)!=null?N:"x",S=de(y,"20px",n.closeButtonColor||"",2);S?M.appendChild(S):M.textContent="\xD7",t&&M.addEventListener("click",t),F.appendChild(M),a.appendChild(F),i.appendChild(a);let R=h("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return R.textContent="Online and ready to help",i.appendChild(R),{header:i,iconHolder:c,headerTitle:p,headerSubtitle:f,closeButton:M,closeButtonWrapper:F,clearChatButton:null,clearChatButtonWrapper:null}},qn={default:ls,minimal:ds,expanded:cs},us=e=>{var s;return(s=qn[e])!=null?s:qn.default},Qt=(e,s,o)=>{var i,a,d;if(s!=null&&s.render){let c=s.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),w=h("div");w.style.display="none";let g=h("span"),p=h("span"),f=h("button");f.style.display="none";let m=h("div");return m.style.display="none",{header:c,iconHolder:w,headerTitle:g,headerSubtitle:p,closeButton:f,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=s==null?void 0:s.layout)!=null?i:"default",n=us(t)({config:e,showClose:(d=(a=s==null?void 0:s.showCloseButton)!=null?a:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return s&&(s.showIcon===!1&&(n.iconHolder.style.display="none"),s.showTitle===!1&&(n.headerTitle.style.display="none"),s.showSubtitle===!1&&(n.headerSubtitle.style.display="none"),s.showCloseButton===!1&&(n.closeButton.style.display="none"),s.showClearChat===!1&&n.clearChatButtonWrapper&&(n.clearChatButtonWrapper.style.display="none")),n};var ni=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Zt=e=>{var V,it,se,D,Ve,nt,at,Tt,Et,_,ue,Ge,Qe,_e,Ze,I,$e,ut,pt,Lt,bt,Ct,Fe,et,xt;let{config:s}=e,o=h("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=h("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((V=s==null?void 0:s.voiceRecognition)==null?void 0:V.enabled)===!0,n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=h("form",`tvw-widget-composer tvw-flex tvw-items-end ${r&&n?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);d.style.outline="none";let c=h("textarea");c.placeholder=(se=(it=s==null?void 0:s.copy)==null?void 0:it.inputPlaceholder)!=null?se:"Type your message\u2026",c.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",c.rows=1;let w=(Ve=(D=s==null?void 0:s.theme)==null?void 0:D.inputFontFamily)!=null?Ve:"sans-serif",g=(at=(nt=s==null?void 0:s.theme)==null?void 0:nt.inputFontWeight)!=null?at:"400";c.style.fontFamily=ni(w),c.style.fontWeight=g,c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.addEventListener("focus",()=>{c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.style.boxShadow="none"}),c.addEventListener("blur",()=>{c.style.border="none",c.style.outline="none"});let p=(Tt=s==null?void 0:s.sendButton)!=null?Tt:{},f=(Et=p.useIcon)!=null?Et:!1,m=(_=p.iconText)!=null?_:"\u2191",F=p.iconName,M=(ue=p.tooltipText)!=null?ue:"Send message",y=(Ge=p.showTooltip)!=null?Ge:!1,S=(Qe=p.size)!=null?Qe:"40px",R=p.backgroundColor,v=p.textColor,O=h("div","tvw-send-button-wrapper"),x=h("button",f?"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",f){if(x.style.width=S,x.style.height=S,x.style.minWidth=S,x.style.minHeight=S,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",F){let We=parseFloat(S)||24,Le=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",b=de(F,We,Le,2);b?(x.appendChild(b),x.style.color=Le):(x.textContent=m,v?x.style.color=v:x.classList.add("tvw-text-white"))}else x.textContent=m,v?x.style.color=v:x.classList.add("tvw-text-white");R?x.style.backgroundColor=R:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(Ze=(_e=s==null?void 0:s.copy)==null?void 0:_e.sendButtonLabel)!=null?Ze:"Send",v?x.style.color=v:x.classList.add("tvw-text-white");if(p.borderWidth&&(x.style.borderWidth=p.borderWidth,x.style.borderStyle="solid"),p.borderColor&&(x.style.borderColor=p.borderColor),p.paddingX?(x.style.paddingLeft=p.paddingX,x.style.paddingRight=p.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),p.paddingY?(x.style.paddingTop=p.paddingY,x.style.paddingBottom=p.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),y&&M){let We=h("div","tvw-send-button-tooltip");We.textContent=M,O.appendChild(We)}O.appendChild(x);let W=(I=s==null?void 0:s.voiceRecognition)!=null?I:{},Y=W.enabled===!0,z=null,j=null,N=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Y&&N){j=h("div","tvw-send-button-wrapper"),z=h("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),z.type="button",z.setAttribute("aria-label","Start voice recognition");let We=($e=W.iconName)!=null?$e:"mic",Le=(ut=W.iconSize)!=null?ut:S,b=parseFloat(Le)||24,He=(pt=W.backgroundColor)!=null?pt:R,Ee=(Lt=W.iconColor)!=null?Lt:v;z.style.width=Le,z.style.height=Le,z.style.minWidth=Le,z.style.minHeight=Le,z.style.fontSize="18px",z.style.lineHeight="1";let Ke=Ee||"currentColor",st=de(We,b,Ke,1.5);st?(z.appendChild(st),z.style.color=Ke):(z.textContent="\u{1F3A4}",z.style.color=Ke),He?z.style.backgroundColor=He:z.classList.add("tvw-bg-cw-primary"),Ee?z.style.color=Ee:!Ee&&!v&&z.classList.add("tvw-text-white"),W.borderWidth&&(z.style.borderWidth=W.borderWidth,z.style.borderStyle="solid"),W.borderColor&&(z.style.borderColor=W.borderColor),W.paddingX&&(z.style.paddingLeft=W.paddingX,z.style.paddingRight=W.paddingX),W.paddingY&&(z.style.paddingTop=W.paddingY,z.style.paddingBottom=W.paddingY),j.appendChild(z);let ot=(bt=W.tooltipText)!=null?bt:"Start voice recognition";if(((Ct=W.showTooltip)!=null?Ct:!1)&&ot){let mt=h("div","tvw-send-button-tooltip");mt.textContent=ot,j.appendChild(mt)}}d.addEventListener("click",We=>{We.target!==x&&We.target!==O&&We.target!==z&&We.target!==j&&c.focus()}),d.append(c),j&&d.append(j),d.append(O);let q=h("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),U=(Fe=s==null?void 0:s.statusIndicator)!=null?Fe:{},J=(et=U.visible)!=null?et:!0;return q.style.display=J?"":"none",q.textContent=(xt=U.idleText)!=null?xt:"Online",o.append(t,d,q),{footer:o,suggestions:t,composerForm:d,textarea:c,sendButton:x,sendButtonWrapper:O,micButton:z,micButtonWrapper:j,statusText:q}};var fr=e=>{var d,c,w,g,p,f,m;if(!((c=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?c:!0)){let F=h("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),M=h("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(g=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?g:"100%";return F.style.width=y,M.style.width="100%",F.appendChild(M),{wrapper:F,panel:M}}let o=(p=e==null?void 0:e.launcher)!=null?p:{},t=o.position&&At[o.position]?At[o.position]:At["bottom-right"],r=h("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),n=h("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?m:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return n.style.width=a,n.style.maxWidth=a,r.appendChild(n),{wrapper:r,panel:n}},wr=(e,s=!0)=>{var f,m,F,M,y,S,R;let o=h("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(f=e==null?void 0:e.layout)==null?void 0:f.header,r=((m=e==null?void 0:e.layout)==null?void 0:m.showHeader)!==!1,n=t?Qt(e,t,{showClose:s}):It({config:e,showClose:s}),i=h("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="vanilla-agent-scroll-container";let a=h("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=h("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(M=(F=e==null?void 0:e.copy)==null?void 0:F.welcomeTitle)!=null?M:"Hello \u{1F44B}";let c=h("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",a.append(d,c);let w=h("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,w);let g=Zt({config:e}),p=((R=e==null?void 0:e.layout)==null?void 0:R.showFooter)!==!1;return r?Kt(o,n,e):(n.header.style.display="none",Kt(o,n,e)),o.append(i),p||(g.footer.style.display="none"),o.append(g.footer),{container:o,body:i,messagesWrapper:w,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:c,closeButton:n.closeButton,closeButtonWrapper:n.closeButtonWrapper,clearChatButton:n.clearChatButton,clearChatButtonWrapper:n.clearChatButtonWrapper,iconHolder:n.iconHolder,headerTitle:n.headerTitle,headerSubtitle:n.headerSubtitle,header:n.header,footer:g.footer}};var bn=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.style.animationDelay="250ms";let 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",e.appendChild(s),e.appendChild(o),e.appendChild(t),e.appendChild(r),e},si=(e,s)=>{let o=h("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=s==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=h("img");r.src=t,r.alt=s==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(s==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=s==="user"?"U":"A",o.classList.add(s==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},yr=(e,s)=>{let o=h("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return s.format?o.textContent=s.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},oi=(e,s="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(s){case"flat":e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return o},ps=(e,s,o)=>{var m,F,M,y,S,R;let t=(m=s.showCopy)!=null?m:!0,r=(F=s.showUpvote)!=null?F:!0,n=(M=s.showDownvote)!=null?M:!0,i=(y=s.visibility)!=null?y:"hover",a=(S=s.align)!=null?S:"right",d=(R=s.layout)!=null?R:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],g=h("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let p=null,f=(v,O,x,W)=>{let Y=document.createElement("button");Y.className="tvw-message-action-btn",Y.setAttribute("aria-label",O),Y.setAttribute("title",O),W&&Y.setAttribute("data-action",W);let z=de(v,14,"currentColor",2);return z&&Y.appendChild(z),Y.addEventListener("click",j=>{j.preventDefault(),j.stopPropagation(),x()}),Y};if(t){let v=f("copy","Copy message",()=>{let O=e.content||"";navigator.clipboard.writeText(O).then(()=>{v.classList.add("tvw-message-action-success");let x=de("check",14,"currentColor",2);x&&(v.innerHTML="",v.appendChild(x)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let W=de("copy",14,"currentColor",2);W&&(v.innerHTML="",v.appendChild(W))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),o!=null&&o.onCopy&&o.onCopy(e),s.onCopy&&s.onCopy(e)},"copy");g.appendChild(v)}if(r){let v=f("thumbs-up","Upvote",()=>{if(p==="upvote")p=null,v.classList.remove("tvw-message-action-active");else{let x=g.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),p="upvote",v.classList.add("tvw-message-action-active");let W={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(W),s.onFeedback&&s.onFeedback(W)}},"upvote");g.appendChild(v)}if(n){let v=f("thumbs-down","Downvote",()=>{if(p==="downvote")p=null,v.classList.remove("tvw-message-action-active");else{let x=g.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),p="downvote",v.classList.add("tvw-message-action-active");let W={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(W),s.onFeedback&&s.onFeedback(W)}},"downvote");g.appendChild(v)}return g},en=(e,s,o,t,r)=>{var R,v,O,x,W;let n=o!=null?o:{},i=(R=n.layout)!=null?R:"bubble",a=n.avatar,d=n.timestamp,c=(v=a==null?void 0:a.show)!=null?v:!1,w=(O=d==null?void 0:d.show)!=null?O:!1,g=(x=a==null?void 0:a.position)!=null?x:"left",p=(W=d==null?void 0:d.position)!=null?W:"below",f=oi(e.role,i),m=h("div",f.join(" "));m.id=`bubble-${e.id}`,m.setAttribute("data-message-id",e.id);let F=document.createElement("div");if(F.innerHTML=s({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),w&&p==="inline"&&e.createdAt){let Y=yr(e,d);Y.classList.add("tvw-ml-2","tvw-inline"),F.appendChild(Y)}if(m.appendChild(F),w&&p==="below"&&e.createdAt){let Y=yr(e,d);Y.classList.add("tvw-mt-1"),m.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=bn();m.appendChild(Y)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let Y=ps(e,t,r);m.appendChild(Y)}if(!c||e.role==="system")return m;let y=h("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),S=si(a,e.role);return g==="right"||g==="left"&&e.role==="user"?y.append(m,S):y.append(S,m),m.classList.remove("tvw-max-w-[85%]"),m.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},vr=(e,s,o,t,r)=>{let n=o!=null?o:{};return e.role==="user"&&n.renderUserMessage?n.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&n.renderAssistantMessage?n.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):en(e,s,o,t,r)};var tn=new Set,br=(e,s)=>{let o=tn.has(e),t=s.querySelector('button[data-expand-header="true"]'),r=s.querySelector(".tvw-border-t");if(!t||!r)return;t.setAttribute("aria-expanded",o?"true":"false");let n=t.querySelector(".tvw-ml-auto"),i=n==null?void 0:n.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=de(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},gs=e=>{let s=e.reasoning,o=h("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!s)return o;let t=tn.has(e.id),r=h("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("data-expand-header","true"),r.setAttribute("data-bubble-type","reasoning");let n=h("div","tvw-flex tvw-flex-col tvw-text-left"),i=h("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",n.appendChild(i);let a=h("span","tvw-text-xs tvw-text-cw-primary");a.textContent=lr(s),n.appendChild(a),s.status==="complete"?i.style.display="none":i.style.display="";let d=h("div","tvw-flex tvw-items-center"),w=de(t?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=t?"Hide":"Show";let g=h("div","tvw-flex tvw-items-center tvw-ml-auto");g.append(d),r.append(n,g);let p=h("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");p.style.display=t?"":"none";let f=s.chunks.join(""),m=h("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return m.textContent=f||(s.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),p.appendChild(m),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=de(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",p.style.display=t?"":"none"})(),o.append(r,p),o};var nn=new Set,Cr=(e,s,o)=>{var c;let t=nn.has(e),r=(c=o==null?void 0:o.toolCall)!=null?c:{},n=s.querySelector('button[data-expand-header="true"]'),i=s.querySelector(".tvw-border-t");if(!n||!i)return;n.setAttribute("aria-expanded",t?"true":"false");let a=n.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let w=r.toggleTextColor||r.headerTextColor||"currentColor",g=de(t?"chevron-up":"chevron-down",16,w,2);g?d.appendChild(g):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},ms=(e,s)=>{var F;let o=e.toolCall,t=(F=s==null?void 0:s.toolCall)!=null?F:{},r=h("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),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),!o)return r;let n=nn.has(e.id),i=h("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",n?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),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 a=h("div","tvw-flex tvw-flex-col tvw-text-left"),d=h("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=dr(o),a.appendChild(d);let c=h("div","tvw-flex tvw-items-center"),w=t.toggleTextColor||t.headerTextColor||"currentColor",g=de(n?"chevron-up":"chevron-down",16,w,2);g?c.appendChild(g):c.textContent=n?"Hide":"Show";let p=h("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");p.append(c),i.append(a,p);let f=h("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(f.style.display=n?"":"none",t.contentBackgroundColor&&(f.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(f.style.color=t.contentTextColor),t.contentPaddingX&&(f.style.paddingLeft=t.contentPaddingX,f.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(f.style.paddingTop=t.contentPaddingY,f.style.paddingBottom=t.contentPaddingY),o.name){let M=h("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=o.name,f.appendChild(M)}if(o.args!==void 0){let M=h("div","tvw-space-y-1"),y=h("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let S=h("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=is(o.args),M.append(y,S),f.appendChild(M)}if(o.chunks&&o.chunks.length){let M=h("div","tvw-space-y-1"),y=h("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let S=h("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=o.chunks.join(`
16
+ `),M.append(y,S),f.appendChild(M)}if(o.status==="complete"&&o.result!==void 0){let M=h("div","tvw-space-y-1"),y=h("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let S=h("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=is(o.result),M.append(y,S),f.appendChild(M)}if(o.status==="complete"&&typeof o.duration=="number"){let M=h("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(M.style.color=t.contentTextColor),M.textContent=`Duration: ${o.duration}ms`,f.appendChild(M)}return(()=>{i.setAttribute("aria-expanded",n?"true":"false"),c.innerHTML="";let M=t.toggleTextColor||t.headerTextColor||"currentColor",y=de(n?"chevron-up":"chevron-down",16,M,2);y?c.appendChild(y):c.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),r.append(i,f),r};var xr=e=>{let s=[];return{buttons:s,render:(t,r,n,i,a)=>{if(e.innerHTML="",s.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(f=>f.role==="user"))return;let w=document.createDocumentFragment(),g=r?r.isStreaming():!1,p=f=>{switch(f){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(f=>{let m=h("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");m.type="button",m.textContent=f,m.disabled=g,a!=null&&a.fontFamily&&(m.style.fontFamily=p(a.fontFamily)),a!=null&&a.fontWeight&&(m.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(m.style.paddingLeft=a.paddingX,m.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(m.style.paddingTop=a.paddingY,m.style.paddingBottom=a.paddingY),m.addEventListener("click",()=>{!r||r.isStreaming()||(n.value="",r.sendMessage(f))}),w.appendChild(m),s.push(m)}),e.appendChild(w)}}};var Sr={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"}},hs=(e,s,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(n=>{var m,F,M;if(n.dataset.enhanced==="true")return;let i=(m=n.dataset.tvForm)!=null?m:"init";n.dataset.enhanced="true";let a=(F=Sr[i])!=null?F:Sr.init;n.classList.add("tvw-form-card","tvw-space-y-4");let d=h("div","tvw-space-y-1"),c=h("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,d.appendChild(c),a.description){let y=h("p","tvw-text-sm tvw-text-cw-muted");y.textContent=a.description,d.appendChild(y)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(y=>{var x,W;let S=h("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${s.id}-${i}-${y.name}`;let R=h("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");R.textContent=y.label,S.appendChild(R);let v=(x=y.type)!=null?x:"text",O;v==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=v),O.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",O.id=`${s.id}-${i}-${y.name}`,O.name=y.name,O.placeholder=(W=y.placeholder)!=null?W:"",y.required&&(O.required=!0),S.appendChild(O),w.appendChild(S)});let g=h("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),p=h("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),f=h("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");f.type="submit",f.textContent=(M=a.submitLabel)!=null?M:"Submit",g.appendChild(p),g.appendChild(f),w.appendChild(g),n.replaceChildren(d,w),w.addEventListener("submit",async y=>{var O,x;y.preventDefault();let S=(O=o.formEndpoint)!=null?O:"/form",R=new FormData(w),v={};R.forEach((W,Y)=>{v[Y]=W}),v.type=i,f.disabled=!0,p.textContent="Submitting\u2026";try{let W=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let Y=await W.json();p.textContent=(x=Y.message)!=null?x:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await t.sendMessage(String(Y.nextPrompt))}catch(W){p.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var fs=class{constructor(){this.plugins=new Map}register(s){var o;this.plugins.has(s.id)&&console.warn(`Plugin "${s.id}" is already registered. Overwriting.`),this.plugins.set(s.id,s),(o=s.onRegister)==null||o.call(s)}unregister(s){var t;let o=this.plugins.get(s);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(s))}getAll(){return Array.from(this.plugins.values()).sort((s,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=s.priority)!=null?r:0)})}getForInstance(s){let o=this.getAll();if(!s||s.length===0)return o;let t=new Set(s.map(n=>n.id));return[...o.filter(n=>!t.has(n.id)),...s].sort((n,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=n.priority)!=null?d:0)})}clear(){this.plugins.forEach(s=>{var o;return(o=s.onUnregister)==null?void 0:o.call(s)}),this.plugins.clear()}},Cn=new fs;var ws={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"},ys={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},Me={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:ws,darkTheme:ys,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Un(e){var s,o,t,r,n,i,a,d,c,w,g,p,f,m,F,M,y,S,R;return e?{...Me,...e,theme:{...Me.theme,...e.theme},darkTheme:{...Me.darkTheme,...e.darkTheme},launcher:{...Me.launcher,...e.launcher,clearChat:{...(s=Me.launcher)==null?void 0:s.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Me.copy,...e.copy},sendButton:{...Me.sendButton,...e.sendButton},statusIndicator:{...Me.statusIndicator,...e.statusIndicator},voiceRecognition:{...Me.voiceRecognition,...e.voiceRecognition},features:{...Me.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Me.suggestionChips,suggestionChipsConfig:{...Me.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Me.layout,...e.layout,header:{...(r=Me.layout)==null?void 0:r.header,...(n=e.layout)==null?void 0:n.header},messages:{...(i=Me.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(c=(d=Me.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(g=(w=e.layout)==null?void 0:w.messages)==null?void 0:g.avatar},timestamp:{...(f=(p=Me.layout)==null?void 0:p.messages)==null?void 0:f.timestamp,...(F=(m=e.layout)==null?void 0:m.messages)==null?void 0:F.timestamp}},slots:{...(M=Me.layout)==null?void 0:M.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Me.markdown,...e.markdown,options:{...(S=Me.markdown)==null?void 0:S.options,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Me.messageActions,...e.messageActions}}:Me}var Ar=()=>{let e=new Map,s=(r,n)=>(e.has(r)||e.set(r,new Set),e.get(r).add(n),()=>o(r,n)),o=(r,n)=>{var i;(i=e.get(r))==null||i.delete(n)};return{on:s,off:o,emit:(r,n)=>{var i;(i=e.get(r))==null||i.forEach(a=>{try{a(n)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var ri=e=>{let s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return s?s[1]:e},ii=e=>{let s=e.trim(),o=s.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<s.length;r+=1){let n=s[r];if(n==="{"&&(t+=1),n==="}"&&(t-=1,t===0))return s.slice(o,r+1)}return null},xn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let s=ri(e),o=ii(s);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...n}=t;return{type:String(r),payload:n,raw:t}}catch{return null}},vs=e=>typeof e=="string"?e:e==null?"":String(e),Xt={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:vs(e.payload.text)},messageAndClick:(e,s)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=vs(o.element);if(t&&((r=s.document)!=null&&r.querySelector)){let n=s.document.querySelector(t);n?setTimeout(()=>{n.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:vs(o.text)}}},Tr=e=>Array.isArray(e)?e.map(s=>String(s)):[],Sn=e=>{let s=new Set(Tr(e.getSessionMetadata().processedActionMessageIds)),o=()=>{s=new Set(Tr(e.getSessionMetadata().processedActionMessageIds))},t=()=>{let n=Array.from(s);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!=="assistant"||!n.text||s.has(n.message.id))return null;let i=typeof n.raw=="string"&&n.raw||typeof n.message.rawContent=="string"&&n.message.rawContent||typeof n.text=="string"&&n.text||null;!i&&typeof n.text=="string"&&n.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 a=i?e.parsers.reduce((c,w)=>c||(w==null?void 0:w({text:i,message:n.message}))||null,null):null;if(!a)return null;s.add(n.message.id),t();let d={action:a,message:n.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let w=c(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef});if(!w)continue;if(w.handled){let g=w.persistMessage!==!1;return{text:w.displayText!==void 0?w.displayText:"",persist:g}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:o}};var ai=e=>{if(!e)return null;try{return JSON.parse(e)}catch(s){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",s),null}},li=e=>e.map(s=>({...s,streaming:!1})),zn=(e="vanilla-agent-state")=>{let s=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=s();return o?ai(o.getItem(e)):null},save:o=>{let t=s();if(t)try{let r={...o,messages:o.messages?li(o.messages):void 0};t.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=s();if(o)try{o.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var bs=class{constructor(){this.components=new Map}register(s,o){this.components.has(s)&&console.warn(`[ComponentRegistry] Component "${s}" is already registered. Overwriting.`),this.components.set(s,o)}unregister(s){this.components.delete(s)}get(s){return this.components.get(s)}has(s){return this.components.has(s)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(s){Object.entries(s).forEach(([o,t])=>{this.register(o,t)})}},sn=new bs;var on=require("partial-json");function di(e){if(!e||typeof e!="object"||!("component"in e))return!1;let s=e.component;return typeof s=="string"&&s.length>0}function ci(e,s){if(!di(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:s}}function Jn(){let e=null,s=0;return{getExtractedDirective:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=s)return e;try{let r=(0,on.parse)(o,on.STR|on.OBJ),n=ci(r,o);n&&(e=n)}catch{}return s=o.length,e},reset:()=>{e=null,s=0}}}function Er(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Yn(e,s){let{config:o,message:t,onPropsUpdate:r}=s,n=sn.get(e.component);if(!n)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:o,updateProps:a=>{r&&r(a)}};try{return n(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function Mr(){let e=Jn();return{processChunk:s=>e.processChunk(s),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Kn(e){if(!e.rawContent)return!1;try{let s=JSON.parse(e.rawContent);return typeof s=="object"&&s!==null&&"component"in s&&typeof s.component=="string"}catch{return!1}}function Xn(e){if(!e.rawContent)return null;try{let s=JSON.parse(e.rawContent);if(typeof s=="object"&&s!==null&&"component"in s&&typeof s.component=="string")return{component:s.component,props:s.props&&typeof s.props=="object"&&s.props!==null?s.props:{},raw:e.rawContent}}catch{}return null}var ui=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vn(e){let{onSubmit:s,onDismiss:o,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:n="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:c=ui}=e,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-csat",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Customer satisfaction feedback");let g=null,p=document.createElement("div");p.className="tvw-feedback-content";let f=document.createElement("div");f.className="tvw-feedback-header";let m=document.createElement("h3");m.className="tvw-feedback-title",m.textContent=t,f.appendChild(m);let F=document.createElement("p");F.className="tvw-feedback-subtitle",F.textContent=r,f.appendChild(F),p.appendChild(f);let M=document.createElement("div");M.className="tvw-feedback-rating tvw-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let x=1;x<=5;x++){let W=document.createElement("button");W.type="button",W.className="tvw-feedback-rating-btn tvw-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${c[x-1]}`),W.title=c[x-1],W.dataset.rating=String(x),W.innerHTML=`
17
17
  <svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
18
18
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
19
19
  </svg>
20
- `,k.addEventListener("click",()=>{g=x,y.forEach((Y,z)=>{let j=z<x;Y.classList.toggle("selected",j),Y.setAttribute("aria-checked",z===x-1?"true":"false")})}),y.push(k),M.appendChild(k)}p.appendChild(M);let S=null;if(d){let x=document.createElement("div");x.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),x.appendChild(S),p.appendChild(x)}let R=document.createElement("div");R.className="tvw-feedback-actions";let 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(),w.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(g===null){M.classList.add("tvw-feedback-shake"),setTimeout(()=>M.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let x=(S==null?void 0:S.value.trim())||void 0;await t(g,x),w.remove()}catch(x){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),R.appendChild(v),R.appendChild(N),p.appendChild(R),w.appendChild(p),w}function Vn(n){let{onSubmit:t,onDismiss:s,title:e="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:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:w="Very likely"}=n,g=document.createElement("div");g.className="tvw-feedback-container tvw-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let p=null,f=document.createElement("div");f.className="tvw-feedback-content";let m=document.createElement("div");m.className="tvw-feedback-header";let F=document.createElement("h3");F.className="tvw-feedback-title",F.textContent=e,m.appendChild(F);let M=document.createElement("p");M.className="tvw-feedback-subtitle",M.textContent=r,m.appendChild(M),f.appendChild(m);let y=document.createElement("div");y.className="tvw-feedback-rating tvw-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="tvw-feedback-labels";let R=document.createElement("span");R.className="tvw-feedback-label-low",R.textContent=c;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=w,S.appendChild(R),S.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let x=[];for(let O=0;O<=10;O++){let q=document.createElement("button");q.type="button",q.className="tvw-feedback-rating-btn tvw-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${O} out of 10`),q.textContent=String(O),q.dataset.rating=String(O),O<=6?q.classList.add("tvw-feedback-detractor"):O<=8?q.classList.add("tvw-feedback-passive"):q.classList.add("tvw-feedback-promoter"),q.addEventListener("click",()=>{p=O,x.forEach((U,J)=>{U.classList.toggle("selected",J===O),U.setAttribute("aria-checked",J===O?"true":"false")})}),x.push(q),N.appendChild(q)}y.appendChild(S),y.appendChild(N),f.appendChild(y);let k=null;if(d){let O=document.createElement("div");O.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),O.appendChild(k),f.appendChild(O)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let z=document.createElement("button");z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-skip",z.textContent=l,z.addEventListener("click",()=>{s==null||s(),g.remove()});let j=document.createElement("button");return j.type="button",j.className="tvw-feedback-btn tvw-feedback-btn-submit",j.textContent=i,j.addEventListener("click",async()=>{if(p===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let O=(k==null?void 0:k.value.trim())||void 0;await t(p,O),g.remove()}catch(O){j.disabled=!1,j.textContent=i,console.error("[NPS Feedback] Failed to submit:",O)}}),Y.appendChild(z),Y.appendChild(j),f.appendChild(Y),g.appendChild(f),g}var on="vanilla-agent-chat-history",ii=30*1e3,bs=n=>!n||typeof n!="object"?{}:{...n},Er=n=>n.map(t=>({...t,streaming:!1})),Mr=(n,t)=>{let s=n!=null&&n.markdown?wn(n.markdown):null;return e=>{var i,l,d;let r=(i=e.text)!=null?i:"",o=(l=e.message.rawContent)!=null?l:null;if(t){let c=t.process({text:r,raw:o!=null?o:r,message:e.message,streaming:e.streaming});c!==null&&(r=c.text,c.persist||(e.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...e,text:r,raw:(d=o!=null?o:e.text)!=null?d:""}):s?s(r):Hn(r)}},Gn=(n,t,s)=>{var Ue,lt,vt,Ss,As,Ts,Es,Ms,ks,Ws,Ls,Bs,Hs,Is,Rs,Ps;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let e=qn(t),r=bn.getForInstance(e.plugins);e.components&&nn.registerAll(e.components);let o=xr(),i=(Ue=e.storageAdapter)!=null?Ue:Un(),l={},d=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")d=a;else if(a){let u=a;u.metadata&&(l=bs(u.metadata)),(lt=u.messages)!=null&&lt.length&&(e={...e,initialMessages:u.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let c=()=>l,w=a=>{var T;l=(T=a({...l}))!=null?T:{},rn()},g=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Cn],p=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Kt.message,Kt.messageAndClick],f=xn({parsers:g,handlers:p,getSessionMetadata:c,updateSessionMetadata:w,emit:o.emit,documentRef:typeof document!="undefined"?document:null});f.syncFromMetadata();let m=(Ss=(vt=e.launcher)==null?void 0:vt.enabled)!=null?Ss:!0,F=(Ts=(As=e.launcher)==null?void 0:As.autoExpand)!=null?Ts:!1,M=F,y=m,S=(Ms=(Es=e.layout)==null?void 0:Es.header)==null?void 0:Ms.layout,R=m?F:!0,v=Mr(e,f),N=(Ws=(ks=e.features)==null?void 0:ks.showReasoning)!=null?Ws:!0,x=(Bs=(Ls=e.features)==null?void 0:Ls.showToolCalls)!=null?Bs:!0,k={onCopy:a=>{var u,T;o.emit("message:copy",a),b!=null&&b.isClientTokenMode()&&b.submitMessageFeedback(a.id,"copy").catch(I=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",I)}),(T=(u=e.messageActions)==null?void 0:u.onCopy)==null||T.call(u,a)},onFeedback:a=>{var u,T;o.emit("message:feedback",a),b!=null&&b.isClientTokenMode()&&b.submitMessageFeedback(a.messageId,a.type).catch(I=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",I)}),(T=(u=e.messageActions)==null?void 0:u.onFeedback)==null||T.call(u,a)}},Y=(Hs=e.statusIndicator)!=null?Hs:{},z=a=>{var u,T,I,C;return a==="idle"?(u=Y.idleText)!=null?u:tt.idle:a==="connecting"?(T=Y.connectingText)!=null?T:tt.connecting:a==="connected"?(I=Y.connectedText)!=null?I:tt.connected:a==="error"?(C=Y.errorText)!=null?C:tt.error:tt[a]},{wrapper:j,panel:O}=mr(e),q=hr(e,m),{container:U,body:J,messagesWrapper:V,suggestions:it,textarea:se,sendButton:D,sendButtonWrapper:Ve,composerForm:nt,statusText:at,introTitle:Tt,introSubtitle:Et,closeButton:_,iconHolder:ue,headerTitle:Ge,headerSubtitle:Qe,header:_e,footer:Ze}=q,P=q.micButton,$e=q.micButtonWrapper,ut=r.find(a=>a.renderHeader);if(ut!=null&&ut.renderHeader){let a=ut.renderHeader({config:e,defaultRenderer:()=>{let u=Pt({config:e,showClose:m});return Yt(U,u,e),u.header},onClose:()=>Ye(!1,"user")});if(a){let u=U.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(a),_e=a)}}let pt=r.find(a=>a.renderComposer);if(pt!=null&&pt.renderComposer){let a=pt.renderComposer({config:e,defaultRenderer:()=>Qt({config:e}).footer,onSubmit:u=>{b&&!b.isStreaming()&&b.sendMessage(u)},disabled:!1});a&&(Ze.replaceWith(a),Ze=a)}(()=>{var I,C;let a=(C=(I=e.layout)==null?void 0:I.slots)!=null?C:{},u=G=>{switch(G){case"body-top":return U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return V;case"footer-top":return it;case"composer":return nt;case"footer-bottom":return at;default:return null}},T=(G,ae)=>{var A;switch(G){case"header-left":case"header-center":case"header-right":if(G==="header-left")_e.insertBefore(ae,_e.firstChild);else if(G==="header-right")_e.appendChild(ae);else{let X=_e.querySelector(".tvw-flex-col");X?(A=X.parentNode)==null||A.insertBefore(ae,X.nextSibling):_e.appendChild(ae)}break;case"body-top":let ee=J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ee?ee.replaceWith(ae):J.insertBefore(ae,J.firstChild);break;case"body-bottom":J.appendChild(ae);break;case"footer-top":it.replaceWith(ae);break;case"footer-bottom":at.replaceWith(ae);break;default:break}};for(let[G,ae]of Object.entries(a))if(ae)try{let A=ae({config:e,defaultContent:()=>u(G)});A&&T(G,A)}catch(A){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${G}":`,A)}})();let bt=a=>{let T=a.target.closest('button[data-expand-header="true"]');if(!T)return;let I=T.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!I)return;let C=I.getAttribute("data-message-id");if(!C)return;let G=T.getAttribute("data-bubble-type");G==="reasoning"?(en.has(C)?en.delete(C):en.add(C),yr(C,I)):G==="tool"&&(tn.has(C)?tn.delete(C):tn.add(C),vr(C,I,e))};V.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),bt(a))}),V.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),bt(a))}),O.appendChild(U),n.appendChild(j);let Ct=()=>{var le,Ne,Oe,Xe,wt,Z,Se,qt,Ut,an,ln,kn,De,Wn,dn,cn;let a=(Ne=(le=e.launcher)==null?void 0:le.sidebarMode)!=null?Ne:!1,u=a||((Xe=(Oe=e.launcher)==null?void 0:Oe.fullHeight)!=null?Xe:!1),T=(wt=e.theme)!=null?wt:{},I=(Se=(Z=e.launcher)==null?void 0:Z.position)!=null?Se:"bottom-left",C=I==="bottom-left"||I==="top-left",G=a?"none":"1px solid var(--tvw-cw-border)",ae=a?C?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",A=a?"0":"16px",ee=(qt=T.panelBorder)!=null?qt:G,X=(Ut=T.panelShadow)!=null?Ut:ae,me=(an=T.panelBorderRadius)!=null?an:A;n.style.cssText="",j.style.cssText="",O.style.cssText="",U.style.cssText="",J.style.cssText="",Ze.style.cssText="";let $=(kn=(ln=e==null?void 0:e.launcher)==null?void 0:ln.width)!=null?kn:e==null?void 0:e.launcherWidth,Pe=$!=null?$:"min(400px, calc(100vw - 24px))";a||(O.style.width=Pe,O.style.maxWidth=Pe),O.style.boxShadow=X,O.style.borderRadius=me,U.style.border=ee,U.style.borderRadius=me;let we=((De=e.launcher)==null?void 0:De.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.height="100%",we&&(j.style.overflow="hidden"),O.style.display="flex",O.style.flexDirection="column",O.style.flex="1 1 0%",O.style.minHeight="0",O.style.maxHeight="100%",O.style.height="100%",O.style.overflow="hidden",U.style.display="flex",U.style.flexDirection="column",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.maxHeight="100%",U.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Ze.style.flexShrink="0"),j.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!a&&!we&&((Wn=At[I])!=null?Wn:At["bottom-right"]).split(" ").forEach(un=>j.classList.add(un)),a){let Nt=(cn=(dn=e.launcher)==null?void 0:dn.sidebarWidth)!=null?cn:"420px";j.style.cssText=`
20
+ `,W.addEventListener("click",()=>{g=x,y.forEach((Y,z)=>{let j=z<x;Y.classList.toggle("selected",j),Y.setAttribute("aria-checked",z===x-1?"true":"false")})}),y.push(W),M.appendChild(W)}p.appendChild(M);let S=null;if(d){let x=document.createElement("div");x.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=n,S.rows=3,S.setAttribute("aria-label","Additional comments"),x.appendChild(S),p.appendChild(x)}let R=document.createElement("div");R.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=a,v.addEventListener("click",()=>{o==null||o(),w.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(g===null){M.classList.add("tvw-feedback-shake"),setTimeout(()=>M.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let x=(S==null?void 0:S.value.trim())||void 0;await s(g,x),w.remove()}catch(x){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),R.appendChild(v),R.appendChild(O),p.appendChild(R),w.appendChild(p),w}function Gn(e){let{onSubmit:s,onDismiss:o,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:n="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:w="Very likely"}=e,g=document.createElement("div");g.className="tvw-feedback-container tvw-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let p=null,f=document.createElement("div");f.className="tvw-feedback-content";let m=document.createElement("div");m.className="tvw-feedback-header";let F=document.createElement("h3");F.className="tvw-feedback-title",F.textContent=t,m.appendChild(F);let M=document.createElement("p");M.className="tvw-feedback-subtitle",M.textContent=r,m.appendChild(M),f.appendChild(m);let y=document.createElement("div");y.className="tvw-feedback-rating tvw-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="tvw-feedback-labels";let R=document.createElement("span");R.className="tvw-feedback-label-low",R.textContent=c;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=w,S.appendChild(R),S.appendChild(v);let O=document.createElement("div");O.className="tvw-feedback-numbers";let x=[];for(let N=0;N<=10;N++){let q=document.createElement("button");q.type="button",q.className="tvw-feedback-rating-btn tvw-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${N} out of 10`),q.textContent=String(N),q.dataset.rating=String(N),N<=6?q.classList.add("tvw-feedback-detractor"):N<=8?q.classList.add("tvw-feedback-passive"):q.classList.add("tvw-feedback-promoter"),q.addEventListener("click",()=>{p=N,x.forEach((U,J)=>{U.classList.toggle("selected",J===N),U.setAttribute("aria-checked",J===N?"true":"false")})}),x.push(q),O.appendChild(q)}y.appendChild(S),y.appendChild(O),f.appendChild(y);let W=null;if(d){let N=document.createElement("div");N.className="tvw-feedback-comment-container",W=document.createElement("textarea"),W.className="tvw-feedback-comment",W.placeholder=n,W.rows=3,W.setAttribute("aria-label","Additional comments"),N.appendChild(W),f.appendChild(N)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let z=document.createElement("button");z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-skip",z.textContent=a,z.addEventListener("click",()=>{o==null||o(),g.remove()});let j=document.createElement("button");return j.type="button",j.className="tvw-feedback-btn tvw-feedback-btn-submit",j.textContent=i,j.addEventListener("click",async()=>{if(p===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let N=(W==null?void 0:W.value.trim())||void 0;await s(p,N),g.remove()}catch(N){j.disabled=!1,j.textContent=i,console.error("[NPS Feedback] Failed to submit:",N)}}),Y.appendChild(z),Y.appendChild(j),f.appendChild(Y),g.appendChild(f),g}var rn="vanilla-agent-chat-history",pi=30*1e3,Cs=e=>!e||typeof e!="object"?{}:{...e},Wr=e=>e.map(s=>({...s,streaming:!1})),kr=(e,s)=>{let o=e!=null&&e.markdown?yn(e.markdown):null;return t=>{var i,a,d;let r=(i=t.text)!=null?i:"",n=(a=t.message.rawContent)!=null?a:null;if(s){let c=s.process({text:r,raw:n!=null?n:r,message:t.message,streaming:t.streaming});c!==null&&(r=c.text,c.persist||(t.message.__skipPersist=!0))}return e!=null&&e.postprocessMessage?e.postprocessMessage({...t,text:r,raw:(d=n!=null?n:t.text)!=null?d:""}):o?o(r):Pn(r)}},Qn=(e,s,o)=>{var Ue,lt,vt,Ts,Es,Ms,Ws,ks,Ls,Hs,Bs,Ps,Rs,Is,$s,Fs;(!e.id||e.id!=="vanilla-agent-root")&&(e.id="vanilla-agent-root");let t=Un(s),r=Cn.getForInstance(t.plugins);t.components&&sn.registerAll(t.components);let n=Ar(),i=(Ue=t.storageAdapter)!=null?Ue:zn(),a={},d=null;if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l;else if(l){let u=l;u.metadata&&(a=Cs(u.metadata)),(lt=u.messages)!=null&&lt.length&&(t={...t,initialMessages:u.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let c=()=>a,w=l=>{var T;a=(T=l({...a}))!=null?T:{},an()},g=t.actionParsers&&t.actionParsers.length?t.actionParsers:[xn],p=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Xt.message,Xt.messageAndClick],f=Sn({parsers:g,handlers:p,getSessionMetadata:c,updateSessionMetadata:w,emit:n.emit,documentRef:typeof document!="undefined"?document:null});f.syncFromMetadata();let m=(Ts=(vt=t.launcher)==null?void 0:vt.enabled)!=null?Ts:!0,F=(Ms=(Es=t.launcher)==null?void 0:Es.autoExpand)!=null?Ms:!1,M=F,y=m,S=(ks=(Ws=t.layout)==null?void 0:Ws.header)==null?void 0:ks.layout,R=m?F:!0,v=kr(t,f),O=(Hs=(Ls=t.features)==null?void 0:Ls.showReasoning)!=null?Hs:!0,x=(Ps=(Bs=t.features)==null?void 0:Bs.showToolCalls)!=null?Ps:!0,W={onCopy:l=>{var u,T;n.emit("message:copy",l),b!=null&&b.isClientTokenMode()&&b.submitMessageFeedback(l.id,"copy").catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",P)}),(T=(u=t.messageActions)==null?void 0:u.onCopy)==null||T.call(u,l)},onFeedback:l=>{var u,T;n.emit("message:feedback",l),b!=null&&b.isClientTokenMode()&&b.submitMessageFeedback(l.messageId,l.type).catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",P)}),(T=(u=t.messageActions)==null?void 0:u.onFeedback)==null||T.call(u,l)}},Y=(Rs=t.statusIndicator)!=null?Rs:{},z=l=>{var u,T,P,C;return l==="idle"?(u=Y.idleText)!=null?u:tt.idle:l==="connecting"?(T=Y.connectingText)!=null?T:tt.connecting:l==="connected"?(P=Y.connectedText)!=null?P:tt.connected:l==="error"?(C=Y.errorText)!=null?C:tt.error:tt[l]},{wrapper:j,panel:N}=fr(t),q=wr(t,m),{container:U,body:J,messagesWrapper:V,suggestions:it,textarea:se,sendButton:D,sendButtonWrapper:Ve,composerForm:nt,statusText:at,introTitle:Tt,introSubtitle:Et,closeButton:_,iconHolder:ue,headerTitle:Ge,headerSubtitle:Qe,header:_e,footer:Ze}=q,I=q.micButton,$e=q.micButtonWrapper,ut=r.find(l=>l.renderHeader);if(ut!=null&&ut.renderHeader){let l=ut.renderHeader({config:t,defaultRenderer:()=>{let u=It({config:t,showClose:m});return Kt(U,u,t),u.header},onClose:()=>Ye(!1,"user")});if(l){let u=U.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),_e=l)}}let pt=r.find(l=>l.renderComposer);if(pt!=null&&pt.renderComposer){let l=pt.renderComposer({config:t,defaultRenderer:()=>Zt({config:t}).footer,onSubmit:u=>{b&&!b.isStreaming()&&b.sendMessage(u)},disabled:!1});l&&(Ze.replaceWith(l),Ze=l)}(()=>{var P,C;let l=(C=(P=t.layout)==null?void 0:P.slots)!=null?C:{},u=G=>{switch(G){case"body-top":return U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return V;case"footer-top":return it;case"composer":return nt;case"footer-bottom":return at;default:return null}},T=(G,ae)=>{var A;switch(G){case"header-left":case"header-center":case"header-right":if(G==="header-left")_e.insertBefore(ae,_e.firstChild);else if(G==="header-right")_e.appendChild(ae);else{let X=_e.querySelector(".tvw-flex-col");X?(A=X.parentNode)==null||A.insertBefore(ae,X.nextSibling):_e.appendChild(ae)}break;case"body-top":let ee=J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ee?ee.replaceWith(ae):J.insertBefore(ae,J.firstChild);break;case"body-bottom":J.appendChild(ae);break;case"footer-top":it.replaceWith(ae);break;case"footer-bottom":at.replaceWith(ae);break;default:break}};for(let[G,ae]of Object.entries(l))if(ae)try{let A=ae({config:t,defaultContent:()=>u(G)});A&&T(G,A)}catch(A){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${G}":`,A)}})();let bt=l=>{let T=l.target.closest('button[data-expand-header="true"]');if(!T)return;let P=T.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!P)return;let C=P.getAttribute("data-message-id");if(!C)return;let G=T.getAttribute("data-bubble-type");G==="reasoning"?(tn.has(C)?tn.delete(C):tn.add(C),br(C,P)):G==="tool"&&(nn.has(C)?nn.delete(C):nn.add(C),Cr(C,P,t))};V.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),bt(l))}),V.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),bt(l))}),N.appendChild(U),e.appendChild(j);let Ct=()=>{var le,Oe,Ne,Xe,wt,Z,Se,Ut,zt,ln,dn,kn,De,Ln,cn,un;let l=(Oe=(le=t.launcher)==null?void 0:le.sidebarMode)!=null?Oe:!1,u=l||((Xe=(Ne=t.launcher)==null?void 0:Ne.fullHeight)!=null?Xe:!1),T=(wt=t.theme)!=null?wt:{},P=(Se=(Z=t.launcher)==null?void 0:Z.position)!=null?Se:"bottom-left",C=P==="bottom-left"||P==="top-left",G=l?"none":"1px solid var(--tvw-cw-border)",ae=l?C?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",A=l?"0":"16px",ee=(Ut=T.panelBorder)!=null?Ut:G,X=(zt=T.panelShadow)!=null?zt:ae,me=(ln=T.panelBorderRadius)!=null?ln:A;e.style.cssText="",j.style.cssText="",N.style.cssText="",U.style.cssText="",J.style.cssText="",Ze.style.cssText="";let $=(kn=(dn=t==null?void 0:t.launcher)==null?void 0:dn.width)!=null?kn:t==null?void 0:t.launcherWidth,Ie=$!=null?$:"min(400px, calc(100vw - 24px))";l||(N.style.width=Ie,N.style.maxWidth=Ie),N.style.boxShadow=X,N.style.borderRadius=me,U.style.border=ee,U.style.borderRadius=me;let we=((De=t.launcher)==null?void 0:De.enabled)===!1;if(u&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.height="100%",we&&(j.style.overflow="hidden"),N.style.display="flex",N.style.flexDirection="column",N.style.flex="1 1 0%",N.style.minHeight="0",N.style.maxHeight="100%",N.style.height="100%",N.style.overflow="hidden",U.style.display="flex",U.style.flexDirection="column",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.maxHeight="100%",U.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",Ze.style.flexShrink="0"),j.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!we&&((Ln=At[P])!=null?Ln:At["bottom-right"]).split(" ").forEach(pn=>j.classList.add(pn)),l){let Nt=(un=(cn=t.launcher)==null?void 0:cn.sidebarWidth)!=null?un:"420px";j.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
@@ -29,7 +29,7 @@
29
29
  display: flex !important;
30
30
  flex-direction: column !important;
31
31
  ${C?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
- `,O.style.cssText=`
32
+ `,N.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
35
35
  flex-direction: column !important;
@@ -42,7 +42,7 @@
42
42
  padding: 0 !important;
43
43
  box-shadow: ${X} !important;
44
44
  border-radius: ${me} !important;
45
- `,O.style.setProperty("width","100%","important"),O.style.setProperty("max-width","100%","important"),U.style.cssText=`
45
+ `,N.style.setProperty("width","100%","important"),N.style.setProperty("max-width","100%","important"),U.style.cssText=`
46
46
  display: flex !important;
47
47
  flex-direction: column !important;
48
48
  flex: 1 1 0% !important;
@@ -57,12 +57,84 @@
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!we){let Nt="max-height: -moz-available !important; max-height: stretch !important;",un=a?"":"padding-top: 1.25em !important;";j.style.cssText+=Nt+un}};Ct(),_n(n,e);let Fe=[],et=null,xt=()=>{et&&(et(),et=null),e.colorScheme==="auto"&&(et=ur(()=>{_n(n,e)}))};xt(),Fe.push(()=>{et&&(et(),et=null)});let ke=br(it),Le=null,b,Be=!1,Ee=!0,Ke=0,st=0,ot=null,gt=!1,mt=0,Mt=!1,$t=125,Xt=2e3,Ot=5,He=50,ht=new Map,pe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Ft=(Rs=(Is=e.voiceRecognition)==null?void 0:Is.autoResume)!=null?Rs:!1,Bt=a=>{o.emit("voice:state",{active:pe.active,source:a,timestamp:Date.now()})},Ht=()=>{w(a=>({...a,voiceState:{active:pe.active,timestamp:Date.now(),manuallyDeactivated:pe.manuallyDeactivated}}))},Sn=()=>{var I,C;if(((I=e.voiceRecognition)==null?void 0:I.enabled)===!1)return;let a=bs(l.voiceState),u=!!a.active,T=Number((C=a.timestamp)!=null?C:0);pe.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-T<ii&&setTimeout(()=>{pe.active||(pe.manuallyDeactivated=!1,te("restore"))},1e3)},An=()=>b?Er(b.getMessages()).filter(a=>!a.__skipPersist):[];function rn(a){if(!(i!=null&&i.save))return;let T={messages:a?Er(a):b?An():[],metadata:l};try{let I=i.save(T);I instanceof Promise&&I.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)})}catch(I){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)}}let Dt=(a=!1)=>{if(!Ee)return;let u=Date.now();gt&&u<mt&&!a||(gt&&u>=mt&&(gt=!1),!(!a&&!Be)&&(u-st<$t||(st=u,ot&&cancelAnimationFrame(ot),ot=requestAnimationFrame(()=>{gt||!Ee||(Mt=!0,J.scrollTop=J.scrollHeight,Ke=J.scrollTop,requestAnimationFrame(()=>{Mt=!1}),ot=null)}))))},It=null,Tn=()=>j.querySelector("#vanilla-agent-scroll-container")||J,En=(a,u=500)=>{let T=a.scrollTop,I=a.clientHeight,C=a.scrollHeight,G=C-T;if(T+I>=C-2||Math.abs(G)<5)return;It!==null&&(cancelAnimationFrame(It),It=null);let A=performance.now(),ee=me=>1-Math.pow(1-me,3),X=me=>{let $=a.scrollHeight;$!==C&&(C=$,G=C-T);let Pe=me-A,we=Math.min(Pe/u,1),le=ee(we),Ne=T+G*le;a.scrollTop=Ne,we<1?It=requestAnimationFrame(X):(a.scrollTop=a.scrollHeight,It=null)};It=requestAnimationFrame(X)},Mn=a=>{let u=new Map;a.forEach(T=>{let I=ht.get(T.id);u.set(T.id,{streaming:T.streaming,role:T.role}),!I&&T.role==="assistant"&&o.emit("assistant:message",T),T.role==="assistant"&&(I!=null&&I.streaming)&&T.streaming===!1&&o.emit("assistant:complete",T)}),ht.clear(),u.forEach((T,I)=>{ht.set(I,T)})},_t=(a,u,T)=>{let I=document.createElement("div");u.forEach(A=>{var Pe,we;let ee=null,X=r.find(le=>!!(A.variant==="reasoning"&&le.renderReasoning||A.variant==="tool"&&le.renderToolCall||!A.variant&&le.renderMessage)),me=(Pe=e.layout)==null?void 0:Pe.messages;if(X)if(A.variant==="reasoning"&&A.reasoning&&X.renderReasoning){if(!N)return;ee=X.renderReasoning({message:A,defaultRenderer:()=>ps(A),config:e})}else if(A.variant==="tool"&&A.toolCall&&X.renderToolCall){if(!x)return;ee=X.renderToolCall({message:A,defaultRenderer:()=>gs(A,e),config:e})}else X.renderMessage&&(ee=X.renderMessage({message:A,defaultRenderer:()=>{let le=Zt(A,T,me,e.messageActions,k);return A.role!=="user"&&ms(le,A,e,b),le},config:e}));if(!ee&&A.role==="assistant"&&!A.variant&&e.enableComponentStreaming!==!1&&Yn(A)){let Ne=Kn(A);if(Ne){let Oe=Jn(Ne,{config:e,message:A,transform:T});if(Oe){let Xe=document.createElement("div");if(Xe.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),Xe.id=`bubble-${A.id}`,Xe.setAttribute("data-message-id",A.id),A.content&&A.content.trim()){let wt=document.createElement("div");wt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",wt.innerHTML=T({text:A.content,message:A,streaming:!!A.streaming,raw:A.rawContent}),Xe.appendChild(wt)}Xe.appendChild(Oe),ee=Xe}}}if(!ee)if(A.variant==="reasoning"&&A.reasoning){if(!N)return;ee=ps(A)}else if(A.variant==="tool"&&A.toolCall){if(!x)return;ee=gs(A,e)}else{let le=(we=e.layout)==null?void 0:we.messages;le!=null&&le.renderUserMessage&&A.role==="user"?ee=le.renderUserMessage({message:A,config:e,streaming:!!A.streaming}):le!=null&&le.renderAssistantMessage&&A.role==="assistant"?ee=le.renderAssistantMessage({message:A,config:e,streaming:!!A.streaming}):ee=Zt(A,T,le,e.messageActions,k),A.role!=="user"&&ee&&ms(ee,A,e,b)}let $=document.createElement("div");$.className="tvw-flex",$.id=`wrapper-${A.id}`,$.setAttribute("data-wrapper-id",A.id),A.role==="user"&&$.classList.add("tvw-justify-end"),$.appendChild(ee),I.appendChild($)});let C=u.some(A=>A.role==="assistant"&&A.streaming),G=u[u.length-1],ae=(G==null?void 0:G.role)==="assistant"&&!G.streaming;if(Be&&u.some(A=>A.role==="user")&&!C&&!ae){let A=vn(),ee=document.createElement("div");ee.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),ee.setAttribute("data-typing-indicator","true"),ee.appendChild(A);let X=document.createElement("div");X.className="tvw-flex",X.id="wrapper-typing-indicator",X.setAttribute("data-wrapper-id","typing-indicator"),X.appendChild(ee),I.appendChild(X)}gr(a,I),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let A=Tn();En(A)})})},jt=()=>{m&&(R?(j.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-95","tvw-opacity-0"),O.classList.add("tvw-scale-100","tvw-opacity-100"),ie?ie.element.style.display="none":Q&&(Q.style.display="none")):(j.classList.add("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-100","tvw-opacity-100"),O.classList.add("tvw-scale-95","tvw-opacity-0"),ie?ie.element.style.display="":Q&&(Q.style.display="")))},Ye=(a,u="user")=>{if(!m||R===a)return;let T=R;R=a,jt(),R&&(Re(),Dt(!0));let I={open:R,source:u,timestamp:Date.now()};R&&!T?o.emit("widget:opened",I):!R&&T&&o.emit("widget:closed",I),o.emit("widget:state",{open:R,launcherEnabled:m,voiceActive:pe.active,streaming:b.isStreaming()})},B=a=>{D.disabled=a,P&&(P.disabled=a),ke.buttons.forEach(u=>{u.disabled=a})},re=()=>{var C,G,ae,A,ee,X,me,$,Pe,we,le,Ne,Oe,Xe;Tt.textContent=(G=(C=e.copy)==null?void 0:C.welcomeTitle)!=null?G:"Hello \u{1F44B}",Et.textContent=(A=(ae=e.copy)==null?void 0:ae.welcomeSubtitle)!=null?A:"Ask anything about your account or products.",se.placeholder=(X=(ee=e.copy)==null?void 0:ee.inputPlaceholder)!=null?X:"How can I help...",(($=(me=e.sendButton)==null?void 0:me.useIcon)!=null?$:!1)||(D.textContent=(we=(Pe=e.copy)==null?void 0:Pe.sendButtonLabel)!=null?we:"Send");let u=(Ne=(le=e.theme)==null?void 0:le.inputFontFamily)!=null?Ne:"sans-serif",T=(Xe=(Oe=e.theme)==null?void 0:Oe.inputFontWeight)!=null?Xe:"400",I=wt=>{switch(wt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=I(u),se.style.fontWeight=T};e.clientToken&&(e={...e,getStoredSessionId:()=>{let a=l.session_id;return typeof a=="string"?a:null},setStoredSessionId:a=>{w(u=>({...u,session_id:a}))}}),b=new Vt(e,{onMessagesChanged(a){_t(V,a,v),b&&(a.some(I=>I.role==="user")?ke.render([],b,se,a):ke.render(e.suggestionChips,b,se,a,e.suggestionChipsConfig)),Dt(!Be),Mn(a);let u=[...a].reverse().find(T=>T.role==="user");pe.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),rn(a)},onStatusChanged(a){var I;let u=(I=e.statusIndicator)!=null?I:{},T=C=>{var G,ae,A,ee;return C==="idle"?(G=u.idleText)!=null?G:tt.idle:C==="connecting"?(ae=u.connectingText)!=null?ae:tt.connecting:C==="connected"?(A=u.connectedText)!=null?A:tt.connected:C==="error"?(ee=u.errorText)!=null?ee:tt.error:tt[C]};at.textContent=T(a)},onStreamingChanged(a){Be=a,B(a),b&&_t(V,b.getMessages(),v),a||Dt(!0)}}),d&&d.then(a=>{var u;a&&(a.metadata&&(l=bs(a.metadata),f.syncFromMetadata()),(u=a.messages)!=null&&u.length&&b.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let he=a=>{a.preventDefault();let u=se.value.trim();u&&(se.value="",b.sendMessage(u))},Ie=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),D.click())},fe=null,Ae=!1,be=null,H=null,ft=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,te=(a="user")=>{var G,ae,A,ee;if(Ae||b.isStreaming())return;let u=ft();if(!u)return;fe=new u;let I=(ae=((G=e.voiceRecognition)!=null?G:{}).pauseDuration)!=null?ae:2e3;fe.continuous=!0,fe.interimResults=!0,fe.lang="en-US";let C=se.value;fe.onresult=X=>{let me="",$="";for(let we=0;we<X.results.length;we++){let le=X.results[we],Ne=le[0].transcript;le.isFinal?me+=Ne+" ":$=Ne}let Pe=C+me+$;se.value=Pe,be&&clearTimeout(be),(me||$)&&(be=window.setTimeout(()=>{let we=se.value.trim();we&&fe&&Ae&&(W(),se.value="",b.sendMessage(we,{viaVoice:!0}))},I))},fe.onerror=X=>{X.error!=="no-speech"&&W()},fe.onend=()=>{if(Ae){let X=se.value.trim();X&&X!==C.trim()&&(se.value="",b.sendMessage(X,{viaVoice:!0})),W()}};try{if(fe.start(),Ae=!0,pe.active=!0,a!=="system"&&(pe.manuallyDeactivated=!1),Bt(a),Ht(),P){H={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor};let X=(A=e.voiceRecognition)!=null?A:{},me=(ee=X.recordingBackgroundColor)!=null?ee:"#ef4444",$=X.recordingIconColor,Pe=X.recordingBorderColor;if(P.classList.add("tvw-voice-recording"),P.style.backgroundColor=me,$){P.style.color=$;let we=P.querySelector("svg");we&&we.setAttribute("stroke",$)}Pe&&(P.style.borderColor=Pe),P.setAttribute("aria-label","Stop voice recognition")}}catch{W("system")}},W=(a="user")=>{if(Ae){if(Ae=!1,be&&(clearTimeout(be),be=null),fe){try{fe.stop()}catch{}fe=null}if(pe.active=!1,Bt(a),Ht(),P){if(P.classList.remove("tvw-voice-recording"),H){P.style.backgroundColor=H.backgroundColor,P.style.color=H.color,P.style.borderColor=H.borderColor;let u=P.querySelector("svg");u&&u.setAttribute("stroke",H.color||"currentColor"),H=null}P.setAttribute("aria-label","Start voice recognition")}}},E=(a,u)=>{var Ne,Oe,Xe,wt,Z,Se,qt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let I=h("div","tvw-send-button-wrapper"),C=h("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");C.type="button",C.setAttribute("aria-label","Start voice recognition");let G=(Ne=a==null?void 0:a.iconName)!=null?Ne:"mic",ae=(Oe=u==null?void 0:u.size)!=null?Oe:"40px",A=(Xe=a==null?void 0:a.iconSize)!=null?Xe:ae,ee=parseFloat(A)||24,X=(wt=a==null?void 0:a.backgroundColor)!=null?wt:u==null?void 0:u.backgroundColor,me=(Z=a==null?void 0:a.iconColor)!=null?Z:u==null?void 0:u.textColor;C.style.width=A,C.style.height=A,C.style.minWidth=A,C.style.minHeight=A,C.style.fontSize="18px",C.style.lineHeight="1";let $=me||"currentColor",Pe=de(G,ee,$,1.5);Pe?(C.appendChild(Pe),C.style.color=$):(C.textContent="\u{1F3A4}",C.style.color=$),X?C.style.backgroundColor=X:C.classList.add("tvw-bg-cw-primary"),me?C.style.color=me:!me&&!(u!=null&&u.textColor)&&C.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(C.style.borderWidth=a.borderWidth,C.style.borderStyle="solid"),a!=null&&a.borderColor&&(C.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(C.style.paddingLeft=a.paddingX,C.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(C.style.paddingTop=a.paddingY,C.style.paddingBottom=a.paddingY),I.appendChild(C);let we=(Se=a==null?void 0:a.tooltipText)!=null?Se:"Start voice recognition";if(((qt=a==null?void 0:a.showTooltip)!=null?qt:!1)&&we){let Ut=h("div","tvw-send-button-tooltip");Ut.textContent=we,I.appendChild(Ut)}return{micButton:C,micButtonWrapper:I}},K=()=>{if(Ae){let a=se.value.trim();pe.manuallyDeactivated=!0,Ht(),W("user"),a&&(se.value="",b.sendMessage(a))}else pe.manuallyDeactivated=!1,Ht(),te("user")};P&&(P.addEventListener("click",K),Fe.push(()=>{W("system"),P&&P.removeEventListener("click",K)}));let We=o.on("assistant:complete",()=>{Ft&&(pe.active||pe.manuallyDeactivated||Ft==="assistant"&&!pe.lastUserMessageWasVoice||setTimeout(()=>{!pe.active&&!pe.manuallyDeactivated&&te("auto")},600))});Fe.push(We);let ye=()=>{Ye(!R,"user")},ie=null,Q=null;if(m){let a=r.find(u=>u.renderLauncher);if(a!=null&&a.renderLauncher){let u=a.renderLauncher({config:e,defaultRenderer:()=>yn(e,ye).element,onToggle:ye});u&&(Q=u)}Q||(ie=yn(e,ye))}ie?n.appendChild(ie.element):Q&&n.appendChild(Q),jt(),ke.render(e.suggestionChips,b,se,void 0,e.suggestionChipsConfig),re(),B(b.isStreaming()),Dt(!0),Sn();let Re=()=>{var T,I,C,G,ae,A,ee,X;let a=(I=(T=e.launcher)==null?void 0:T.sidebarMode)!=null?I:!1,u=a||((G=(C=e.launcher)==null?void 0:C.fullHeight)!=null?G:!1);if(!m){O.style.height="",O.style.width="";return}if(!a){let me=(A=(ae=e==null?void 0:e.launcher)==null?void 0:ae.width)!=null?A:e==null?void 0:e.launcherWidth,$=me!=null?me:"min(400px, calc(100vw - 24px))";O.style.width=$,O.style.maxWidth=$}if(!u){let me=window.innerHeight,$=64,Pe=(X=(ee=e.launcher)==null?void 0:ee.heightOffset)!=null?X:0,we=Math.max(200,me-$),le=Math.min(640,we),Ne=Math.max(200,le-Pe);O.style.height=`${Ne}px`}};Re(),window.addEventListener("resize",Re),Fe.push(()=>window.removeEventListener("resize",Re)),Ke=J.scrollTop;let je=()=>{let a=J.scrollTop,u=J.scrollHeight,T=J.clientHeight,I=u-a-T,C=Math.abs(a-Ke);if(Ke=a,!Mt&&!(C<=Ot)){if(!Ee&&I<He){gt=!1,Ee=!0;return}Ee&&I>He&&(gt=!0,mt=Date.now()+Xt,Ee=!1)}};J.addEventListener("scroll",je,{passive:!0}),Fe.push(()=>J.removeEventListener("scroll",je)),Fe.push(()=>{ot&&cancelAnimationFrame(ot)});let ge=()=>{_&&(Le&&(_.removeEventListener("click",Le),Le=null),m?(_.style.display="",Le=()=>{R=!1,jt()},_.addEventListener("click",Le)):_.style.display="none")};ge(),(()=>{let{clearChatButton:a}=q;a&&a.addEventListener("click",()=>{b.clearMessages();try{localStorage.removeItem(on),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let u=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",I)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}l={},f.syncFromMetadata()})})(),nt.addEventListener("submit",he),se.addEventListener("keydown",Ie),Fe.push(()=>{nt.removeEventListener("submit",he),se.removeEventListener("keydown",Ie)}),Fe.push(()=>{b.cancel()}),ie?Fe.push(()=>{ie==null||ie.destroy()}):Q&&Fe.push(()=>{Q==null||Q.remove()});let ve={update(a){var $s,Fs,Ns,Os,Ds,_s,js,qs,Us,zs,Js,Ys,Ks,Xs,Vs,Gs,Qs,Zs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Eo,Mo,ko,Wo,Lo,Bo,Ho,Io,Ro,Po,$o,Fo,No,Oo,Do,_o,jo,qo,Uo,zo,Jo,Yo,Ko,Xo,Vo,Go,Qo;let u=e.toolCall,T=e.colorScheme;e={...e,...a},Ct(),_n(n,e),e.colorScheme!==T&&xt();let I=bn.getForInstance(e.plugins);if(r.length=0,r.push(...I),m=(Fs=($s=e.launcher)==null?void 0:$s.enabled)!=null?Fs:!0,F=(Os=(Ns=e.launcher)==null?void 0:Ns.autoExpand)!=null?Os:!1,N=(_s=(Ds=e.features)==null?void 0:Ds.showReasoning)!=null?_s:!0,x=(qs=(js=e.features)==null?void 0:js.showToolCalls)!=null?qs:!0,((Us=e.launcher)==null?void 0:Us.enabled)===!1&&ie&&(ie.destroy(),ie=null),((zs=e.launcher)==null?void 0:zs.enabled)===!1&&Q&&(Q.remove(),Q=null),((Js=e.launcher)==null?void 0:Js.enabled)!==!1&&!ie&&!Q){let L=r.find(ce=>ce.renderLauncher);if(L!=null&&L.renderLauncher){let ce=L.renderLauncher({config:e,defaultRenderer:()=>yn(e,ye).element,onToggle:ye});ce&&(Q=ce,n.appendChild(Q))}Q||(ie=yn(e,ye),n.appendChild(ie.element))}ie&&ie.update(e),Ge&&((Ys=e.launcher)==null?void 0:Ys.title)!==void 0&&(Ge.textContent=e.launcher.title),Qe&&((Ks=e.launcher)==null?void 0:Ks.subtitle)!==void 0&&(Qe.textContent=e.launcher.subtitle);let C=(Xs=e.layout)==null?void 0:Xs.header;if((C==null?void 0:C.layout)!==S&&_e){let L=C?Gt(e,C,{showClose:m,onClose:()=>Ye(!1,"user")}):Pt({config:e,showClose:m,onClose:()=>Ye(!1,"user")});_e.replaceWith(L.header),_e=L.header,ue=L.iconHolder,Ge=L.headerTitle,Qe=L.headerSubtitle,_=L.closeButton,S=C==null?void 0:C.layout}else if(C&&(ue&&(ue.style.display=C.showIcon===!1?"none":""),Ge&&(Ge.style.display=C.showTitle===!1?"none":""),Qe&&(Qe.style.display=C.showSubtitle===!1?"none":""),_&&(_.style.display=C.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let L=C.showClearChat;if(L!==void 0){q.clearChatButtonWrapper.style.display=L?"":"none";let{closeButtonWrapper:ce}=q;ce&&!ce.classList.contains("tvw-absolute")&&(L?ce.classList.remove("tvw-ml-auto"):ce.classList.add("tvw-ml-auto"))}}let ae=((Vs=e.layout)==null?void 0:Vs.showHeader)!==!1;_e&&(_e.style.display=ae?"":"none");let A=((Gs=e.layout)==null?void 0:Gs.showFooter)!==!1;Ze&&(Ze.style.display=A?"":"none"),m!==y?m?Ye(F,"auto"):(R=!0,jt()):F!==M&&Ye(F,"auto"),M=F,y=m,Re(),ge(),JSON.stringify(a.toolCall)!==JSON.stringify(u)&&b&&_t(V,b.getMessages(),v);let $=(Qs=e.launcher)!=null?Qs:{},Pe=(Zs=$.headerIconHidden)!=null?Zs:!1,we=(to=(eo=e.layout)==null?void 0:eo.header)==null?void 0:to.showIcon,le=Pe||we===!1,Ne=$.headerIconName,Oe=(no=$.headerIconSize)!=null?no:"48px";if(ue){let L=U.querySelector(".tvw-border-b-cw-divider"),ce=L==null?void 0:L.querySelector(".tvw-flex-col");if(le)ue.style.display="none",L&&ce&&!L.contains(ce)&&L.insertBefore(ce,L.firstChild);else{if(ue.style.display="",ue.style.height=Oe,ue.style.width=Oe,L&&ce&&(L.contains(ue)?ue.nextSibling!==ce&&(ue.remove(),L.insertBefore(ue,ce)):L.insertBefore(ue,ce)),Ne){let ne=parseFloat(Oe)||24,Te=de(Ne,ne*.6,"#ffffff",2);Te?ue.replaceChildren(Te):ue.textContent=(so=$.agentIconText)!=null?so:"\u{1F4AC}"}else if($.iconUrl){let ne=ue.querySelector("img");if(ne)ne.src=$.iconUrl,ne.style.height=Oe,ne.style.width=Oe;else{let Te=document.createElement("img");Te.src=$.iconUrl,Te.alt="",Te.className="tvw-rounded-xl tvw-object-cover",Te.style.height=Oe,Te.style.width=Oe,ue.replaceChildren(Te)}}else{let ne=ue.querySelector("svg"),Te=ue.querySelector("img");(ne||Te)&&ue.replaceChildren(),ue.textContent=(oo=$.agentIconText)!=null?oo:"\u{1F4AC}"}let qe=ue.querySelector("img");qe&&(qe.style.height=Oe,qe.style.width=Oe)}}let Xe=(io=(ro=e.layout)==null?void 0:ro.header)==null?void 0:io.showTitle,wt=(lo=(ao=e.layout)==null?void 0:ao.header)==null?void 0:lo.showSubtitle;if(Ge&&(Ge.style.display=Xe===!1?"none":""),Qe&&(Qe.style.display=wt===!1?"none":""),_){((uo=(co=e.layout)==null?void 0:co.header)==null?void 0:uo.showCloseButton)===!1?_.style.display="none":_.style.display="";let ce=(po=$.closeButtonSize)!=null?po:"32px",qe=(go=$.closeButtonPlacement)!=null?go:"inline";_.style.height=ce,_.style.width=ce;let{closeButtonWrapper:ne}=q,Te=qe==="top-right",dt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&Te!==dt)if(ne.remove(),Te)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",U.style.position="relative",U.appendChild(ne);else{let oe=(ho=(mo=$.clearChat)==null?void 0:mo.placement)!=null?ho:"inline",Je=(wo=(fo=$.clearChat)==null?void 0:fo.enabled)!=null?wo:!0;ne.className=Je&&oe==="inline"?"":"tvw-ml-auto";let ct=U.querySelector(".tvw-border-b-cw-divider");ct&&ct.appendChild(ne)}if($.closeButtonColor?(_.style.color=$.closeButtonColor,_.classList.remove("tvw-text-cw-muted")):(_.style.color="",_.classList.add("tvw-text-cw-muted")),$.closeButtonBackgroundColor?(_.style.backgroundColor=$.closeButtonBackgroundColor,_.classList.remove("hover:tvw-bg-gray-100")):(_.style.backgroundColor="",_.classList.add("hover:tvw-bg-gray-100")),$.closeButtonBorderWidth||$.closeButtonBorderColor){let oe=$.closeButtonBorderWidth||"0px",Je=$.closeButtonBorderColor||"transparent";_.style.border=`${oe} solid ${Je}`,_.classList.remove("tvw-border-none")}else _.style.border="",_.classList.add("tvw-border-none");$.closeButtonBorderRadius?(_.style.borderRadius=$.closeButtonBorderRadius,_.classList.remove("tvw-rounded-full")):(_.style.borderRadius="",_.classList.add("tvw-rounded-full")),$.closeButtonPaddingX?(_.style.paddingLeft=$.closeButtonPaddingX,_.style.paddingRight=$.closeButtonPaddingX):(_.style.paddingLeft="",_.style.paddingRight=""),$.closeButtonPaddingY?(_.style.paddingTop=$.closeButtonPaddingY,_.style.paddingBottom=$.closeButtonPaddingY):(_.style.paddingTop="",_.style.paddingBottom="");let rt=(yo=$.closeButtonIconName)!=null?yo:"x",Wt=(vo=$.closeButtonIconText)!=null?vo:"\xD7";_.innerHTML="";let yt=de(rt,"20px",$.closeButtonColor||"",2);yt?_.appendChild(yt):_.textContent=Wt;let ze=(bo=$.closeButtonTooltipText)!=null?bo:"Close chat",St=(Co=$.closeButtonShowTooltip)!=null?Co:!0;if(_.setAttribute("aria-label",ze),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),St&&ze)){let oe=null,Je=()=>{if(oe||!_)return;oe=h("div","tvw-clear-chat-tooltip"),oe.textContent=ze;let hn=h("div");hn.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(hn);let zt=_.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${zt.left+zt.width/2}px`,oe.style.top=`${zt.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},ct=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};ne.addEventListener("mouseenter",Je),ne.addEventListener("mouseleave",ct),_.addEventListener("focus",Je),_.addEventListener("blur",ct),ne._cleanupTooltip=()=>{ct(),ne&&(ne.removeEventListener("mouseenter",Je),ne.removeEventListener("mouseleave",ct)),_&&(_.removeEventListener("focus",Je),_.removeEventListener("blur",ct))}}}let{clearChatButton:Z,clearChatButtonWrapper:Se}=q;if(Z){let L=(xo=$.clearChat)!=null?xo:{},ce=(So=L.enabled)!=null?So:!0,qe=(To=(Ao=e.layout)==null?void 0:Ao.header)==null?void 0:To.showClearChat,ne=qe!==void 0?qe:ce,Te=(Eo=L.placement)!=null?Eo:"inline";if(Se){Se.style.display=ne?"":"none";let{closeButtonWrapper:dt}=q;dt&&!dt.classList.contains("tvw-absolute")&&(ne?dt.classList.remove("tvw-ml-auto"):dt.classList.add("tvw-ml-auto"));let rt=Te==="top-right",Wt=Se.classList.contains("tvw-absolute");if(rt!==Wt&&ne){if(Se.remove(),rt)Se.className="tvw-absolute tvw-top-4 tvw-z-50",Se.style.right="48px",U.style.position="relative",U.appendChild(Se);else{Se.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Se.style.right="";let ze=U.querySelector(".tvw-border-b-cw-divider"),St=q.closeButtonWrapper;ze&&St&&St.parentElement===ze?ze.insertBefore(Se,St):ze&&ze.appendChild(Se)}let yt=q.closeButtonWrapper;yt&&!yt.classList.contains("tvw-absolute")&&(rt?yt.classList.add("tvw-ml-auto"):yt.classList.remove("tvw-ml-auto"))}}if(ne){let dt=(Mo=L.size)!=null?Mo:"32px";Z.style.height=dt,Z.style.width=dt;let rt=(ko=L.iconName)!=null?ko:"refresh-cw",Wt=(Wo=L.iconColor)!=null?Wo:"";Z.innerHTML="";let yt=de(rt,"20px",Wt||"",2);if(yt&&Z.appendChild(yt),Wt?(Z.style.color=Wt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),L.backgroundColor?(Z.style.backgroundColor=L.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let oe=L.borderWidth||"0px",Je=L.borderColor||"transparent";Z.style.border=`${oe} solid ${Je}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");L.borderRadius?(Z.style.borderRadius=L.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),L.paddingX?(Z.style.paddingLeft=L.paddingX,Z.style.paddingRight=L.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),L.paddingY?(Z.style.paddingTop=L.paddingY,Z.style.paddingBottom=L.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let ze=(Lo=L.tooltipText)!=null?Lo:"Clear chat",St=(Bo=L.showTooltip)!=null?Bo:!0;if(Z.setAttribute("aria-label",ze),Se&&(Se._cleanupTooltip&&(Se._cleanupTooltip(),delete Se._cleanupTooltip),St&&ze)){let oe=null,Je=()=>{if(oe||!Z)return;oe=h("div","tvw-clear-chat-tooltip"),oe.textContent=ze;let hn=h("div");hn.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(hn);let zt=Z.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${zt.left+zt.width/2}px`,oe.style.top=`${zt.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},ct=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};Se.addEventListener("mouseenter",Je),Se.addEventListener("mouseleave",ct),Z.addEventListener("focus",Je),Z.addEventListener("blur",ct),Se._cleanupTooltip=()=>{ct(),Se&&(Se.removeEventListener("mouseenter",Je),Se.removeEventListener("mouseleave",ct)),Z&&(Z.removeEventListener("focus",Je),Z.removeEventListener("blur",ct))}}}}let qt=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Cn],Ut=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Kt.message,Kt.messageAndClick];f=xn({parsers:qt,handlers:Ut,getSessionMetadata:c,updateSessionMetadata:w,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),v=Mr(e,f),b.updateConfig(e),_t(V,b.getMessages(),v),ke.render(e.suggestionChips,b,se,void 0,e.suggestionChipsConfig),re(),B(b.isStreaming());let an=((Ho=e.voiceRecognition)==null?void 0:Ho.enabled)===!0,ln=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),kn=an&&ln;if(nt.classList.remove("tvw-gap-1","tvw-gap-3"),nt.classList.add(kn?"tvw-gap-1":"tvw-gap-3"),an&&ln)if(!P||!$e){let L=E(e.voiceRecognition,e.sendButton);L&&(P=L.micButton,$e=L.micButtonWrapper,nt.insertBefore($e,Ve),P.addEventListener("click",K),P.disabled=b.isStreaming())}else{let L=(Io=e.voiceRecognition)!=null?Io:{},ce=(Ro=e.sendButton)!=null?Ro:{},qe=(Po=L.iconName)!=null?Po:"mic",ne=($o=ce.size)!=null?$o:"40px",Te=(Fo=L.iconSize)!=null?Fo:ne,dt=parseFloat(Te)||24;P.style.width=Te,P.style.height=Te,P.style.minWidth=Te,P.style.minHeight=Te;let rt=(Oo=(No=L.iconColor)!=null?No:ce.textColor)!=null?Oo:"currentColor";P.innerHTML="";let Wt=de(qe,dt,rt,2);Wt?P.appendChild(Wt):P.textContent="\u{1F3A4}";let yt=(Do=L.backgroundColor)!=null?Do:ce.backgroundColor;yt?(P.style.backgroundColor=yt,P.classList.remove("tvw-bg-cw-primary")):(P.style.backgroundColor="",P.classList.add("tvw-bg-cw-primary")),rt?(P.style.color=rt,P.classList.remove("tvw-text-white")):!rt&&!ce.textColor&&(P.style.color="",P.classList.add("tvw-text-white")),L.borderWidth?(P.style.borderWidth=L.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),L.borderColor?P.style.borderColor=L.borderColor:P.style.borderColor="",L.paddingX?(P.style.paddingLeft=L.paddingX,P.style.paddingRight=L.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),L.paddingY?(P.style.paddingTop=L.paddingY,P.style.paddingBottom=L.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let ze=$e==null?void 0:$e.querySelector(".tvw-send-button-tooltip"),St=(_o=L.tooltipText)!=null?_o:"Start voice recognition";if(((jo=L.showTooltip)!=null?jo:!1)&&St)if(ze)ze.textContent=St,ze.style.display="";else{let Je=document.createElement("div");Je.className="tvw-send-button-tooltip",Je.textContent=St,$e==null||$e.insertBefore(Je,P)}else ze&&(ze.style.display="none");$e.style.display="",P.disabled=b.isStreaming()}else P&&$e&&($e.style.display="none",Ae&&W());let De=(qo=e.sendButton)!=null?qo:{},Wn=(Uo=De.useIcon)!=null?Uo:!1,dn=(zo=De.iconText)!=null?zo:"\u2191",cn=De.iconName,Nt=(Jo=De.tooltipText)!=null?Jo:"Send message",un=(Yo=De.showTooltip)!=null?Yo:!1,pn=(Ko=De.size)!=null?Ko:"40px",Ln=De.backgroundColor,kt=De.textColor;if(Wn){if(D.style.width=pn,D.style.height=pn,D.style.minWidth=pn,D.style.minHeight=pn,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",cn){let L=parseFloat(pn)||24,ce=kt&&typeof kt=="string"&&kt.trim()?kt.trim():"currentColor",qe=de(cn,L,ce,2);qe?(D.appendChild(qe),D.style.color=ce):(D.textContent=dn,kt?D.style.color=kt:D.classList.add("tvw-text-white"))}else D.textContent=dn,kt?D.style.color=kt:D.classList.add("tvw-text-white");D.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Ln?(D.style.backgroundColor=Ln,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Vo=(Xo=e.copy)==null?void 0:Xo.sendButtonLabel)!=null?Vo:"Send",D.style.width="",D.style.height="",D.style.minWidth="",D.style.minHeight="",D.style.fontSize="",D.style.lineHeight="",D.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Ln?(D.style.backgroundColor=Ln,D.classList.remove("tvw-bg-cw-accent")):D.classList.add("tvw-bg-cw-accent"),kt?D.style.color=kt:D.classList.add("tvw-text-white");De.borderWidth?(D.style.borderWidth=De.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),De.borderColor?D.style.borderColor=De.borderColor:D.style.borderColor="",De.paddingX?(D.style.paddingLeft=De.paddingX,D.style.paddingRight=De.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),De.paddingY?(D.style.paddingTop=De.paddingY,D.style.paddingBottom=De.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let gn=Ve==null?void 0:Ve.querySelector(".tvw-send-button-tooltip");if(un&&Nt)if(gn)gn.textContent=Nt,gn.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=Nt,Ve==null||Ve.insertBefore(L,D)}else gn&&(gn.style.display="none");let mn=(Go=e.statusIndicator)!=null?Go:{},Br=(Qo=mn.visible)!=null?Qo:!0;if(at.style.display=Br?"":"none",b){let L=b.getStatus(),ce=qe=>{var ne,Te,dt,rt;return qe==="idle"?(ne=mn.idleText)!=null?ne:tt.idle:qe==="connecting"?(Te=mn.connectingText)!=null?Te:tt.connecting:qe==="connected"?(dt=mn.connectedText)!=null?dt:tt.connected:qe==="error"?(rt=mn.errorText)!=null?rt:tt.error:tt[qe]};at.textContent=ce(L)}},open(){m&&Ye(!0,"api")},close(){m&&Ye(!1,"api")},toggle(){m&&Ye(!R,"api")},clearChat(){b.clearMessages();try{localStorage.removeItem(on),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}l={},f.syncFromMetadata()},setMessage(a){return!se||b.isStreaming()?!1:(!R&&m&&Ye(!0,"system"),se.value=a,se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(b.isStreaming())return!1;let u=(a==null?void 0:a.trim())||se.value.trim();return u?(!R&&m&&Ye(!0,"system"),se.value="",b.sendMessage(u),!0):!1},startVoiceRecognition(){return Ae||b.isStreaming()||!ft()?!1:(!R&&m&&Ye(!0,"system"),pe.manuallyDeactivated=!1,Ht(),te("user"),!0)},stopVoiceRecognition(){return Ae?(pe.manuallyDeactivated=!0,Ht(),W("user"),!0):!1},injectTestMessage(a){!R&&m&&Ye(!0,"system"),b.injectTestEvent(a)},getMessages(){return b.getMessages()},getStatus(){return b.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){w(a)},on(a,u){return o.on(a,u)},off(a,u){o.off(a,u)},isOpen(){return m&&R},isVoiceActive(){return pe.active},getState(){return{open:m&&R,launcherEnabled:m,voiceActive:pe.active,streaming:b.isStreaming()}},showCSATFeedback(a){!R&&m&&Ye(!0,"system");let u=V.querySelector(".tvw-feedback-container");u&&u.remove();let T=Xn({onSubmit:async(I,C)=>{var G;b.isClientTokenMode()&&await b.submitCSATFeedback(I,C),(G=a==null?void 0:a.onSubmit)==null||G.call(a,I,C)},onDismiss:a==null?void 0:a.onDismiss,...a});V.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!R&&m&&Ye(!0,"system");let u=V.querySelector(".tvw-feedback-container");u&&u.remove();let T=Vn({onSubmit:async(I,C)=>{var G;b.isClientTokenMode()&&await b.submitNPSFeedback(I,C),(G=a==null?void 0:a.onSubmit)==null||G.call(a,I,C)},onDismiss:a==null?void 0:a.onDismiss,...a});V.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return b.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return b.submitNPSFeedback(a,u)},destroy(){Fe.forEach(a=>a()),j.remove(),ie==null||ie.destroy(),Q==null||Q.remove(),Le&&_.removeEventListener("click",Le)}};if((((Ps=s==null?void 0:s.debugTools)!=null?Ps:!1)||!!e.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,u={controller:ve,getMessages:ve.getMessages,getStatus:ve.getStatus,getMetadata:ve.getPersistentMetadata,updateMetadata:ve.updatePersistentMetadata,clearHistory:()=>ve.clearChat(),setVoiceActive:T=>T?ve.startVoiceRecognition():ve.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Fe.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}return ve};var Cs={},ai=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},li=()=>{try{if(typeof Cs!="undefined"&&Cs.url)return new URL("../widget.css",Cs.url).href}catch{}return null},kr=n=>{let t=li(),s=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let r=e.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-vanilla-agent","true"),n.insertBefore(e,n.firstChild)}else s();else if(!document.head.querySelector("link[data-vanilla-agent]")&&t){let r=document.createElement("link");r.rel="stylesheet",r.href=t,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},xs=n=>{var c,w,g,p;let t=ai(n.target),s=document.createElement("div");s.className="vanilla-agent-host";let e=(g=(w=(c=n.config)==null?void 0:c.launcher)==null?void 0:w.enabled)!=null?g:!0;e||(s.style.height="100%"),t.appendChild(s);let r=n.useShadowDom===!0,o,i;if(r){let f=s.attachShadow({mode:"open"});i=f,o=document.createElement("div"),o.id="vanilla-agent-root",e||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),f.appendChild(o),kr(f)}else i=s,o=document.createElement("div"),o.id="vanilla-agent-root",e||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),s.appendChild(o),kr(s);let l=Gn(o,n.config,{debugTools:n.debugTools});(p=n.onReady)==null||p.call(n);let d={...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]=d),d};function di(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Qn(n){var t,s;return(s=(t=n.parserType)!=null?t:di(n.streamParser))!=null?s:"plain"}function Zn(n,t){let s=[];return n.toolCall&&(s.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,r])=>{typeof r=="string"&&s.push(`${t} ${e}: "${r}",`)}),s.push(`${t}},`)),s}function es(n,t){let s=[];return n.messageActions&&Object.entries(n.messageActions).some(([r,o])=>r!=="onFeedback"&&r!=="onCopy"&&o!==void 0)&&(s.push(`${t}messageActions: {`),Object.entries(n.messageActions).forEach(([r,o])=>{r==="onFeedback"||r==="onCopy"||(typeof o=="string"?s.push(`${t} ${r}: "${o}",`):typeof o=="boolean"&&s.push(`${t} ${r}: ${o},`))}),s.push(`${t}},`)),s}function ts(n,t){let s=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,r=n.markdown.disableDefaultStyles!==void 0;(e||r)&&(s.push(`${t}markdown: {`),e&&(s.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([o,i])=>{typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`)}),s.push(`${t} },`)),r&&s.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),s.push(`${t}},`))}return s}function ns(n,t){let s=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(o=>o!=="render"),r=n.layout.messages&&Object.keys(n.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(e||r)&&(s.push(`${t}layout: {`),e&&(s.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([o,i])=>{o!=="render"&&(typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`))}),s.push(`${t} },`)),r&&(s.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([o,i])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof i=="object"&&i!==null?(s.push(`${t} avatar: {`),Object.entries(i).forEach(([l,d])=>{typeof d=="string"?s.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&s.push(`${t} ${l}: ${d},`)}),s.push(`${t} },`)):o==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(s.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?s.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&s.push(`${t} ${d}: ${c},`))}),s.push(`${t} },`)):typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`))}),s.push(`${t} },`)),s.push(`${t}},`))}return s}function Wr(n,t="esm"){let s={...n};return delete s.postprocessMessage,delete s.initialMessages,t==="esm"?ci(s):t==="script-installer"?gi(s):t==="script-advanced"?hi(s):t==="react-component"?ui(s):t==="react-advanced"?pi(s):mi(s)}function ci(n){let t=Qn(n),s=t!=="plain",e=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),s&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"?e.push(` ${r}: ${o},`):typeof o=="number"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{e.push(` ${r}: ${o},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...Zn(n," ")),e.push(...es(n," ")),e.push(...ts(n," ")),e.push(...ns(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push("});"),e.join(`
61
- `)}function ui(n){let t=Qn(n),s=t!=="plain",e=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),s&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"?e.push(` ${r}: ${o},`):typeof o=="number"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{e.push(` ${r}: ${o},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...Zn(n," ")),e.push(...es(n," ")),e.push(...ts(n," ")),e.push(...ns(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage in your app:"),e.push("// import { ChatWidget } from './components/ChatWidget';"),e.push("//"),e.push("// export default function App() {"),e.push("// return ("),e.push("// <div>"),e.push("// {/* Your app content */}"),e.push("// <ChatWidget />"),e.push("// </div>"),e.push("// );"),e.push("// }"),e.join(`
62
- `)}function pi(n){let t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([s,e])=>{t.push(` ${s}: "${e}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,e])=>{typeof e=="string"?t.push(` ${s}: "${e}",`):typeof e=="boolean"&&t.push(` ${s}: ${e},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([s,e])=>{t.push(` ${s}: "${e}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,e])=>{typeof e=="string"?t.push(` ${s}: "${e}",`):typeof e=="boolean"&&t.push(` ${s}: ${e},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,e])=>{typeof e=="string"?t.push(` ${s}: "${e}",`):typeof e=="boolean"?t.push(` ${s}: ${e},`):typeof e=="number"&&t.push(` ${s}: ${e},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,e])=>{typeof e=="string"?t.push(` ${s}: "${e}",`):typeof e=="boolean"&&t.push(` ${s}: ${e},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([s,e])=>{t.push(` ${s}: ${e},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{t.push(` "${s}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...Zn(n," ")),t.push(...es(n," ")),t.push(...ts(n," ")),t.push(...ns(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" initialMessages: loadSavedMessages(),"),t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),t.push(" if (!parsed || typeof parsed !== 'object') return null;"),t.push(" // Extract display text based on action type"),t.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),t.push(" if (parsed.action === 'message') return parsed.text || '';"),t.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),t.push(" return parsed.text || null;"),t.push(" }),"),t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Custom parser for markdown-wrapped JSON"),t.push(" ({ text, message }: any) => {"),t.push(" const jsonSource = (message as any).rawContent || text || message.content;"),t.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),t.push(" // Strip markdown code fences"),t.push(" let cleanJson = jsonSource"),t.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),t.push(" .replace(/\\n?```\\s*$/, '')"),t.push(" .trim();"),t.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),t.push(" try {"),t.push(" const parsed = JSON.parse(cleanJson);"),t.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),t.push(" } catch (e) { return null; }"),t.push(" return null;"),t.push(" }"),t.push(" ],"),t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(" (action: any, context: any) => {"),t.push(" if (action.type !== 'nav_then_click') return;"),t.push(" const payload = action.payload || action.raw || {};"),t.push(" const url = payload?.page;"),t.push(" const text = payload?.on_load_text || 'Navigating...';"),t.push(" if (!url) return { handled: true, displayText: text };"),t.push(" // Check if already processed"),t.push(" const messageId = context.message?.id;"),t.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),t.push(" const actionKey = `nav_${messageId}_${url}`;"),t.push(" if (processedActions.includes(actionKey)) {"),t.push(" return { handled: true, displayText: text };"),t.push(" }"),t.push(" processedActions.push(actionKey);"),t.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),t.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),t.push(" window.location.href = targetUrl;"),t.push(" return { handled: true, displayText: text };"),t.push(" }"),t.push(" ],"),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
63
- `)}function Lr(n){var r;let t=Qn(n),s=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.flowId&&(e.flowId=n.flowId),s&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((r=n.suggestionChips)==null?void 0:r.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let o={};Object.entries(n.toolCall).forEach(([i,l])=>{typeof l=="string"&&(o[i]=l)}),Object.keys(o).length>0&&(e.toolCall=o)}if(n.messageActions){let o={};Object.entries(n.messageActions).forEach(([i,l])=>{i!=="onFeedback"&&i!=="onCopy"&&l!==void 0&&(typeof l=="string"||typeof l=="boolean")&&(o[i]=l)}),Object.keys(o).length>0&&(e.messageActions=o)}if(n.markdown){let o={};n.markdown.options&&(o.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(o).length>0&&(e.markdown=o)}if(n.layout){let o={};if(n.layout.header){let i={};Object.entries(n.layout.header).forEach(([l,d])=>{l!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[l]=d)}),Object.keys(i).length>0&&(o.header=i)}if(n.layout.messages){let i={};Object.entries(n.layout.messages).forEach(([l,d])=>{if(l!=="renderUserMessage"&&l!=="renderAssistantMessage")if(l==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(l==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([w,g])=>{w!=="format"&&(typeof g=="string"||typeof g=="boolean")&&(c[w]=g)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(i[l]=d)}),Object.keys(i).length>0&&(o.messages=i)}Object.keys(o).length>0&&(e.layout=o)}return e}function gi(n){let t=Lr(n);return`<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js" data-config='${JSON.stringify(t,null,0).replace(/'/g,"&#39;")}'></script>`}function mi(n){let t=Qn(n),s=t!=="plain",e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),s&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"?e.push(` ${r}: ${o},`):typeof o=="number"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{e.push(` ${r}: ${o},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...Zn(n," ")),e.push(...es(n," ")),e.push(...ts(n," ")),e.push(...ns(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),e.push(" }"),e.push(" });"),e.push("</script>"),e.join(`
64
- `)}function hi(n){let t=Lr(n);return["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
65
- `).map((r,o)=>o===0?r:" "+r).join(`
66
- `)};`,""," // Constants"," var CDN_BASE = 'https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist';"," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-vanilla-agent]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-vanilla-agent', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""," // Flexible JSON stream parser for handling structured actions"," widgetConfig.streamParser = function() {"," return agentWidget.createFlexibleJsonStreamParser(function(parsed) {"," if (!parsed || typeof parsed !== 'object') return null;"," if (parsed.action === 'nav_then_click') return 'Navigating...';"," if (parsed.action === 'message') return parsed.text || '';"," if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"," return parsed.text || null;"," });"," };",""," // Action parsers to detect JSON actions in responses"," widgetConfig.actionParsers = ["," agentWidget.defaultJsonActionParser,"," function(ctx) {"," var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;"," if (!jsonSource || typeof jsonSource !== 'string') return null;"," var cleanJson = jsonSource"," .replace(/^```(?:json)?\\s*\\n?/, '')"," .replace(/\\n?```\\s*$/, '')"," .trim();"," if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"," try {"," var parsed = JSON.parse(cleanJson);"," if (parsed.action) return { type: parsed.action, payload: parsed };"," } catch (e) { return null; }"," return null;"," }"," ];",""," // Action handlers for navigation and other actions"," widgetConfig.actionHandlers = ["," agentWidget.defaultActionHandlers.message,"," agentWidget.defaultActionHandlers.messageAndClick,"," function(action, context) {"," if (action.type !== 'nav_then_click') return;"," var payload = action.payload || action.raw || {};"," var url = payload.page;"," var text = payload.on_load_text || 'Navigating...';"," if (!url) return { handled: true, displayText: text };"," var messageId = context.message ? context.message.id : null;"," var processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"," var actionKey = 'nav_' + messageId + '_' + url;"," if (processedActions.includes(actionKey)) {"," return { handled: true, displayText: text };"," }"," processedActions.push(actionKey);"," localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"," var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"," window.location.href = targetUrl;"," return { handled: true, displayText: text };"," }"," ];",""," // Send DOM context with each request"," widgetConfig.requestMiddleware = function(ctx) {"," return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"," };",""," // Markdown postprocessor"," widgetConfig.postprocessMessage = function(ctx) {"," return agentWidget.markdownPostprocessor(ctx.text);"," };",""," return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('vanilla-agent:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('vanilla-agent:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"].join(`
67
- `)}var fi=xs;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,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});
60
+ `}if(!we){let Nt="max-height: -moz-available !important; max-height: stretch !important;",pn=l?"":"padding-top: 1.25em !important;";j.style.cssText+=Nt+pn}};Ct(),jn(e,t);let Fe=[],et=null,xt=()=>{et&&(et(),et=null),t.colorScheme==="auto"&&(et=gr(()=>{jn(e,t)}))};xt(),Fe.push(()=>{et&&(et(),et=null)});let We=xr(it),Le=null,b,He=!1,Ee=!0,Ke=0,st=0,ot=null,gt=!1,mt=0,Mt=!1,Ft=125,Vt=2e3,Dt=5,Be=50,ht=new Map,pe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Ot=($s=(Is=t.voiceRecognition)==null?void 0:Is.autoResume)!=null?$s:!1,Ht=l=>{n.emit("voice:state",{active:pe.active,source:l,timestamp:Date.now()})},Bt=()=>{w(l=>({...l,voiceState:{active:pe.active,timestamp:Date.now(),manuallyDeactivated:pe.manuallyDeactivated}}))},An=()=>{var P,C;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let l=Cs(a.voiceState),u=!!l.active,T=Number((C=l.timestamp)!=null?C:0);pe.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-T<pi&&setTimeout(()=>{pe.active||(pe.manuallyDeactivated=!1,te("restore"))},1e3)},Tn=()=>b?Wr(b.getMessages()).filter(l=>!l.__skipPersist):[];function an(l){if(!(i!=null&&i.save))return;let T={messages:l?Wr(l):b?Tn():[],metadata:a};try{let P=i.save(T);P instanceof Promise&&P.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)})}catch(P){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)}}let _t=(l=!1)=>{if(!Ee)return;let u=Date.now();gt&&u<mt&&!l||(gt&&u>=mt&&(gt=!1),!(!l&&!He)&&(u-st<Ft||(st=u,ot&&cancelAnimationFrame(ot),ot=requestAnimationFrame(()=>{gt||!Ee||(Mt=!0,J.scrollTop=J.scrollHeight,Ke=J.scrollTop,requestAnimationFrame(()=>{Mt=!1}),ot=null)}))))},Pt=null,En=()=>j.querySelector("#vanilla-agent-scroll-container")||J,Mn=(l,u=500)=>{let T=l.scrollTop,P=l.clientHeight,C=l.scrollHeight,G=C-T;if(T+P>=C-2||Math.abs(G)<5)return;Pt!==null&&(cancelAnimationFrame(Pt),Pt=null);let A=performance.now(),ee=me=>1-Math.pow(1-me,3),X=me=>{let $=l.scrollHeight;$!==C&&(C=$,G=C-T);let Ie=me-A,we=Math.min(Ie/u,1),le=ee(we),Oe=T+G*le;l.scrollTop=Oe,we<1?Pt=requestAnimationFrame(X):(l.scrollTop=l.scrollHeight,Pt=null)};Pt=requestAnimationFrame(X)},Wn=l=>{let u=new Map;l.forEach(T=>{let P=ht.get(T.id);u.set(T.id,{streaming:T.streaming,role:T.role}),!P&&T.role==="assistant"&&n.emit("assistant:message",T),T.role==="assistant"&&(P!=null&&P.streaming)&&T.streaming===!1&&n.emit("assistant:complete",T)}),ht.clear(),u.forEach((T,P)=>{ht.set(P,T)})},jt=(l,u,T)=>{let P=document.createElement("div");u.forEach(A=>{var Ie,we;let ee=null,X=r.find(le=>!!(A.variant==="reasoning"&&le.renderReasoning||A.variant==="tool"&&le.renderToolCall||!A.variant&&le.renderMessage)),me=(Ie=t.layout)==null?void 0:Ie.messages;if(X)if(A.variant==="reasoning"&&A.reasoning&&X.renderReasoning){if(!O)return;ee=X.renderReasoning({message:A,defaultRenderer:()=>gs(A),config:t})}else if(A.variant==="tool"&&A.toolCall&&X.renderToolCall){if(!x)return;ee=X.renderToolCall({message:A,defaultRenderer:()=>ms(A,t),config:t})}else X.renderMessage&&(ee=X.renderMessage({message:A,defaultRenderer:()=>{let le=en(A,T,me,t.messageActions,W);return A.role!=="user"&&hs(le,A,t,b),le},config:t}));if(!ee&&A.role==="assistant"&&!A.variant&&t.enableComponentStreaming!==!1&&Kn(A)){let Oe=Xn(A);if(Oe){let Ne=Yn(Oe,{config:t,message:A,transform:T});if(Ne){let Xe=document.createElement("div");if(Xe.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),Xe.id=`bubble-${A.id}`,Xe.setAttribute("data-message-id",A.id),A.content&&A.content.trim()){let wt=document.createElement("div");wt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",wt.innerHTML=T({text:A.content,message:A,streaming:!!A.streaming,raw:A.rawContent}),Xe.appendChild(wt)}Xe.appendChild(Ne),ee=Xe}}}if(!ee)if(A.variant==="reasoning"&&A.reasoning){if(!O)return;ee=gs(A)}else if(A.variant==="tool"&&A.toolCall){if(!x)return;ee=ms(A,t)}else{let le=(we=t.layout)==null?void 0:we.messages;le!=null&&le.renderUserMessage&&A.role==="user"?ee=le.renderUserMessage({message:A,config:t,streaming:!!A.streaming}):le!=null&&le.renderAssistantMessage&&A.role==="assistant"?ee=le.renderAssistantMessage({message:A,config:t,streaming:!!A.streaming}):ee=en(A,T,le,t.messageActions,W),A.role!=="user"&&ee&&hs(ee,A,t,b)}let $=document.createElement("div");$.className="tvw-flex",$.id=`wrapper-${A.id}`,$.setAttribute("data-wrapper-id",A.id),A.role==="user"&&$.classList.add("tvw-justify-end"),$.appendChild(ee),P.appendChild($)});let C=u.some(A=>A.role==="assistant"&&A.streaming),G=u[u.length-1],ae=(G==null?void 0:G.role)==="assistant"&&!G.streaming;if(He&&u.some(A=>A.role==="user")&&!C&&!ae){let A=bn(),ee=document.createElement("div");ee.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),ee.setAttribute("data-typing-indicator","true"),ee.appendChild(A);let X=document.createElement("div");X.className="tvw-flex",X.id="wrapper-typing-indicator",X.setAttribute("data-wrapper-id","typing-indicator"),X.appendChild(ee),P.appendChild(X)}hr(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let A=En();Mn(A)})})},qt=()=>{m&&(R?(j.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),N.classList.remove("tvw-scale-95","tvw-opacity-0"),N.classList.add("tvw-scale-100","tvw-opacity-100"),ie?ie.element.style.display="none":Q&&(Q.style.display="none")):(j.classList.add("tvw-pointer-events-none","tvw-opacity-0"),N.classList.remove("tvw-scale-100","tvw-opacity-100"),N.classList.add("tvw-scale-95","tvw-opacity-0"),ie?ie.element.style.display="":Q&&(Q.style.display="")))},Ye=(l,u="user")=>{if(!m||R===l)return;let T=R;R=l,qt(),R&&(Re(),_t(!0));let P={open:R,source:u,timestamp:Date.now()};R&&!T?n.emit("widget:opened",P):!R&&T&&n.emit("widget:closed",P),n.emit("widget:state",{open:R,launcherEnabled:m,voiceActive:pe.active,streaming:b.isStreaming()})},H=l=>{D.disabled=l,I&&(I.disabled=l),We.buttons.forEach(u=>{u.disabled=l})},re=()=>{var C,G,ae,A,ee,X,me,$,Ie,we,le,Oe,Ne,Xe;Tt.textContent=(G=(C=t.copy)==null?void 0:C.welcomeTitle)!=null?G:"Hello \u{1F44B}",Et.textContent=(A=(ae=t.copy)==null?void 0:ae.welcomeSubtitle)!=null?A:"Ask anything about your account or products.",se.placeholder=(X=(ee=t.copy)==null?void 0:ee.inputPlaceholder)!=null?X:"How can I help...",(($=(me=t.sendButton)==null?void 0:me.useIcon)!=null?$:!1)||(D.textContent=(we=(Ie=t.copy)==null?void 0:Ie.sendButtonLabel)!=null?we:"Send");let u=(Oe=(le=t.theme)==null?void 0:le.inputFontFamily)!=null?Oe:"sans-serif",T=(Xe=(Ne=t.theme)==null?void 0:Ne.inputFontWeight)!=null?Xe:"400",P=wt=>{switch(wt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=P(u),se.style.fontWeight=T};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{w(u=>({...u,session_id:l}))}}),b=new Gt(t,{onMessagesChanged(l){jt(V,l,v),b&&(l.some(P=>P.role==="user")?We.render([],b,se,l):We.render(t.suggestionChips,b,se,l,t.suggestionChipsConfig)),_t(!He),Wn(l);let u=[...l].reverse().find(T=>T.role==="user");pe.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),an(l)},onStatusChanged(l){var P;let u=(P=t.statusIndicator)!=null?P:{},T=C=>{var G,ae,A,ee;return C==="idle"?(G=u.idleText)!=null?G:tt.idle:C==="connecting"?(ae=u.connectingText)!=null?ae:tt.connecting:C==="connected"?(A=u.connectedText)!=null?A:tt.connected:C==="error"?(ee=u.errorText)!=null?ee:tt.error:tt[C]};at.textContent=T(l)},onStreamingChanged(l){He=l,H(l),b&&jt(V,b.getMessages(),v),l||_t(!0)}}),d&&d.then(l=>{var u;l&&(l.metadata&&(a=Cs(l.metadata),f.syncFromMetadata()),(u=l.messages)!=null&&u.length&&b.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let he=l=>{l.preventDefault();let u=se.value.trim();u&&(se.value="",b.sendMessage(u))},Pe=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),D.click())},fe=null,Ae=!1,be=null,B=null,ft=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,te=(l="user")=>{var G,ae,A,ee;if(Ae||b.isStreaming())return;let u=ft();if(!u)return;fe=new u;let P=(ae=((G=t.voiceRecognition)!=null?G:{}).pauseDuration)!=null?ae:2e3;fe.continuous=!0,fe.interimResults=!0,fe.lang="en-US";let C=se.value;fe.onresult=X=>{let me="",$="";for(let we=0;we<X.results.length;we++){let le=X.results[we],Oe=le[0].transcript;le.isFinal?me+=Oe+" ":$=Oe}let Ie=C+me+$;se.value=Ie,be&&clearTimeout(be),(me||$)&&(be=window.setTimeout(()=>{let we=se.value.trim();we&&fe&&Ae&&(k(),se.value="",b.sendMessage(we,{viaVoice:!0}))},P))},fe.onerror=X=>{X.error!=="no-speech"&&k()},fe.onend=()=>{if(Ae){let X=se.value.trim();X&&X!==C.trim()&&(se.value="",b.sendMessage(X,{viaVoice:!0})),k()}};try{if(fe.start(),Ae=!0,pe.active=!0,l!=="system"&&(pe.manuallyDeactivated=!1),Ht(l),Bt(),I){B={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor};let X=(A=t.voiceRecognition)!=null?A:{},me=(ee=X.recordingBackgroundColor)!=null?ee:"#ef4444",$=X.recordingIconColor,Ie=X.recordingBorderColor;if(I.classList.add("tvw-voice-recording"),I.style.backgroundColor=me,$){I.style.color=$;let we=I.querySelector("svg");we&&we.setAttribute("stroke",$)}Ie&&(I.style.borderColor=Ie),I.setAttribute("aria-label","Stop voice recognition")}}catch{k("system")}},k=(l="user")=>{if(Ae){if(Ae=!1,be&&(clearTimeout(be),be=null),fe){try{fe.stop()}catch{}fe=null}if(pe.active=!1,Ht(l),Bt(),I){if(I.classList.remove("tvw-voice-recording"),B){I.style.backgroundColor=B.backgroundColor,I.style.color=B.color,I.style.borderColor=B.borderColor;let u=I.querySelector("svg");u&&u.setAttribute("stroke",B.color||"currentColor"),B=null}I.setAttribute("aria-label","Start voice recognition")}}},E=(l,u)=>{var Oe,Ne,Xe,wt,Z,Se,Ut;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=h("div","tvw-send-button-wrapper"),C=h("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");C.type="button",C.setAttribute("aria-label","Start voice recognition");let G=(Oe=l==null?void 0:l.iconName)!=null?Oe:"mic",ae=(Ne=u==null?void 0:u.size)!=null?Ne:"40px",A=(Xe=l==null?void 0:l.iconSize)!=null?Xe:ae,ee=parseFloat(A)||24,X=(wt=l==null?void 0:l.backgroundColor)!=null?wt:u==null?void 0:u.backgroundColor,me=(Z=l==null?void 0:l.iconColor)!=null?Z:u==null?void 0:u.textColor;C.style.width=A,C.style.height=A,C.style.minWidth=A,C.style.minHeight=A,C.style.fontSize="18px",C.style.lineHeight="1";let $=me||"currentColor",Ie=de(G,ee,$,1.5);Ie?(C.appendChild(Ie),C.style.color=$):(C.textContent="\u{1F3A4}",C.style.color=$),X?C.style.backgroundColor=X:C.classList.add("tvw-bg-cw-primary"),me?C.style.color=me:!me&&!(u!=null&&u.textColor)&&C.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(C.style.borderWidth=l.borderWidth,C.style.borderStyle="solid"),l!=null&&l.borderColor&&(C.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(C.style.paddingLeft=l.paddingX,C.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(C.style.paddingTop=l.paddingY,C.style.paddingBottom=l.paddingY),P.appendChild(C);let we=(Se=l==null?void 0:l.tooltipText)!=null?Se:"Start voice recognition";if(((Ut=l==null?void 0:l.showTooltip)!=null?Ut:!1)&&we){let zt=h("div","tvw-send-button-tooltip");zt.textContent=we,P.appendChild(zt)}return{micButton:C,micButtonWrapper:P}},K=()=>{if(Ae){let l=se.value.trim();pe.manuallyDeactivated=!0,Bt(),k("user"),l&&(se.value="",b.sendMessage(l))}else pe.manuallyDeactivated=!1,Bt(),te("user")};I&&(I.addEventListener("click",K),Fe.push(()=>{k("system"),I&&I.removeEventListener("click",K)}));let ke=n.on("assistant:complete",()=>{Ot&&(pe.active||pe.manuallyDeactivated||Ot==="assistant"&&!pe.lastUserMessageWasVoice||setTimeout(()=>{!pe.active&&!pe.manuallyDeactivated&&te("auto")},600))});Fe.push(ke);let ye=()=>{Ye(!R,"user")},ie=null,Q=null;if(m){let l=r.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:t,defaultRenderer:()=>vn(t,ye).element,onToggle:ye});u&&(Q=u)}Q||(ie=vn(t,ye))}ie?e.appendChild(ie.element):Q&&e.appendChild(Q),qt(),We.render(t.suggestionChips,b,se,void 0,t.suggestionChipsConfig),re(),H(b.isStreaming()),_t(!0),An();let Re=()=>{var T,P,C,G,ae,A,ee,X;let l=(P=(T=t.launcher)==null?void 0:T.sidebarMode)!=null?P:!1,u=l||((G=(C=t.launcher)==null?void 0:C.fullHeight)!=null?G:!1);if(!m){N.style.height="",N.style.width="";return}if(!l){let me=(A=(ae=t==null?void 0:t.launcher)==null?void 0:ae.width)!=null?A:t==null?void 0:t.launcherWidth,$=me!=null?me:"min(400px, calc(100vw - 24px))";N.style.width=$,N.style.maxWidth=$}if(!u){let me=window.innerHeight,$=64,Ie=(X=(ee=t.launcher)==null?void 0:ee.heightOffset)!=null?X:0,we=Math.max(200,me-$),le=Math.min(640,we),Oe=Math.max(200,le-Ie);N.style.height=`${Oe}px`}};Re(),window.addEventListener("resize",Re),Fe.push(()=>window.removeEventListener("resize",Re)),Ke=J.scrollTop;let je=()=>{let l=J.scrollTop,u=J.scrollHeight,T=J.clientHeight,P=u-l-T,C=Math.abs(l-Ke);if(Ke=l,!Mt&&!(C<=Dt)){if(!Ee&&P<Be){gt=!1,Ee=!0;return}Ee&&P>Be&&(gt=!0,mt=Date.now()+Vt,Ee=!1)}};J.addEventListener("scroll",je,{passive:!0}),Fe.push(()=>J.removeEventListener("scroll",je)),Fe.push(()=>{ot&&cancelAnimationFrame(ot)});let ge=()=>{_&&(Le&&(_.removeEventListener("click",Le),Le=null),m?(_.style.display="",Le=()=>{R=!1,qt()},_.addEventListener("click",Le)):_.style.display="none")};ge(),(()=>{let{clearChatButton:l}=q;l&&l.addEventListener("click",()=>{b.clearMessages();try{localStorage.removeItem(rn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rn}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==rn)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(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",P)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}a={},f.syncFromMetadata()})})(),nt.addEventListener("submit",he),se.addEventListener("keydown",Pe),Fe.push(()=>{nt.removeEventListener("submit",he),se.removeEventListener("keydown",Pe)}),Fe.push(()=>{b.cancel()}),ie?Fe.push(()=>{ie==null||ie.destroy()}):Q&&Fe.push(()=>{Q==null||Q.remove()});let ve={update(l){var Os,Ns,Ds,_s,js,qs,Us,zs,Js,Ys,Ks,Xs,Vs,Gs,Qs,Zs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Eo,Mo,Wo,ko,Lo,Ho,Bo,Po,Ro,Io,$o,Fo,Oo,No,Do,_o,jo,qo,Uo,zo,Jo,Yo,Ko,Xo,Vo,Go,Qo,Zo,er;let u=t.toolCall,T=t.colorScheme;t={...t,...l},Ct(),jn(e,t),t.colorScheme!==T&&xt();let P=Cn.getForInstance(t.plugins);if(r.length=0,r.push(...P),m=(Ns=(Os=t.launcher)==null?void 0:Os.enabled)!=null?Ns:!0,F=(_s=(Ds=t.launcher)==null?void 0:Ds.autoExpand)!=null?_s:!1,O=(qs=(js=t.features)==null?void 0:js.showReasoning)!=null?qs:!0,x=(zs=(Us=t.features)==null?void 0:Us.showToolCalls)!=null?zs:!0,((Js=t.launcher)==null?void 0:Js.enabled)===!1&&ie&&(ie.destroy(),ie=null),((Ys=t.launcher)==null?void 0:Ys.enabled)===!1&&Q&&(Q.remove(),Q=null),((Ks=t.launcher)==null?void 0:Ks.enabled)!==!1&&!ie&&!Q){let L=r.find(ce=>ce.renderLauncher);if(L!=null&&L.renderLauncher){let ce=L.renderLauncher({config:t,defaultRenderer:()=>vn(t,ye).element,onToggle:ye});ce&&(Q=ce,e.appendChild(Q))}Q||(ie=vn(t,ye),e.appendChild(ie.element))}ie&&ie.update(t),Ge&&((Xs=t.launcher)==null?void 0:Xs.title)!==void 0&&(Ge.textContent=t.launcher.title),Qe&&((Vs=t.launcher)==null?void 0:Vs.subtitle)!==void 0&&(Qe.textContent=t.launcher.subtitle);let C=(Gs=t.layout)==null?void 0:Gs.header;if((C==null?void 0:C.layout)!==S&&_e){let L=C?Qt(t,C,{showClose:m,onClose:()=>Ye(!1,"user")}):It({config:t,showClose:m,onClose:()=>Ye(!1,"user")});_e.replaceWith(L.header),_e=L.header,ue=L.iconHolder,Ge=L.headerTitle,Qe=L.headerSubtitle,_=L.closeButton,S=C==null?void 0:C.layout}else if(C&&(ue&&(ue.style.display=C.showIcon===!1?"none":""),Ge&&(Ge.style.display=C.showTitle===!1?"none":""),Qe&&(Qe.style.display=C.showSubtitle===!1?"none":""),_&&(_.style.display=C.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let L=C.showClearChat;if(L!==void 0){q.clearChatButtonWrapper.style.display=L?"":"none";let{closeButtonWrapper:ce}=q;ce&&!ce.classList.contains("tvw-absolute")&&(L?ce.classList.remove("tvw-ml-auto"):ce.classList.add("tvw-ml-auto"))}}let ae=((Qs=t.layout)==null?void 0:Qs.showHeader)!==!1;_e&&(_e.style.display=ae?"":"none");let A=((Zs=t.layout)==null?void 0:Zs.showFooter)!==!1;Ze&&(Ze.style.display=A?"":"none"),m!==y?m?Ye(F,"auto"):(R=!0,qt()):F!==M&&Ye(F,"auto"),M=F,y=m,Re(),ge(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&b&&jt(V,b.getMessages(),v);let $=(eo=t.launcher)!=null?eo:{},Ie=(to=$.headerIconHidden)!=null?to:!1,we=(so=(no=t.layout)==null?void 0:no.header)==null?void 0:so.showIcon,le=Ie||we===!1,Oe=$.headerIconName,Ne=(oo=$.headerIconSize)!=null?oo:"48px";if(ue){let L=U.querySelector(".tvw-border-b-cw-divider"),ce=L==null?void 0:L.querySelector(".tvw-flex-col");if(le)ue.style.display="none",L&&ce&&!L.contains(ce)&&L.insertBefore(ce,L.firstChild);else{if(ue.style.display="",ue.style.height=Ne,ue.style.width=Ne,L&&ce&&(L.contains(ue)?ue.nextSibling!==ce&&(ue.remove(),L.insertBefore(ue,ce)):L.insertBefore(ue,ce)),Oe){let ne=parseFloat(Ne)||24,Te=de(Oe,ne*.6,"#ffffff",2);Te?ue.replaceChildren(Te):ue.textContent=(ro=$.agentIconText)!=null?ro:"\u{1F4AC}"}else if($.iconUrl){let ne=ue.querySelector("img");if(ne)ne.src=$.iconUrl,ne.style.height=Ne,ne.style.width=Ne;else{let Te=document.createElement("img");Te.src=$.iconUrl,Te.alt="",Te.className="tvw-rounded-xl tvw-object-cover",Te.style.height=Ne,Te.style.width=Ne,ue.replaceChildren(Te)}}else{let ne=ue.querySelector("svg"),Te=ue.querySelector("img");(ne||Te)&&ue.replaceChildren(),ue.textContent=(io=$.agentIconText)!=null?io:"\u{1F4AC}"}let qe=ue.querySelector("img");qe&&(qe.style.height=Ne,qe.style.width=Ne)}}let Xe=(lo=(ao=t.layout)==null?void 0:ao.header)==null?void 0:lo.showTitle,wt=(uo=(co=t.layout)==null?void 0:co.header)==null?void 0:uo.showSubtitle;if(Ge&&(Ge.style.display=Xe===!1?"none":""),Qe&&(Qe.style.display=wt===!1?"none":""),_){((go=(po=t.layout)==null?void 0:po.header)==null?void 0:go.showCloseButton)===!1?_.style.display="none":_.style.display="";let ce=(mo=$.closeButtonSize)!=null?mo:"32px",qe=(ho=$.closeButtonPlacement)!=null?ho:"inline";_.style.height=ce,_.style.width=ce;let{closeButtonWrapper:ne}=q,Te=qe==="top-right",dt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&Te!==dt)if(ne.remove(),Te)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",U.style.position="relative",U.appendChild(ne);else{let oe=(wo=(fo=$.clearChat)==null?void 0:fo.placement)!=null?wo:"inline",Je=(vo=(yo=$.clearChat)==null?void 0:yo.enabled)!=null?vo:!0;ne.className=Je&&oe==="inline"?"":"tvw-ml-auto";let ct=U.querySelector(".tvw-border-b-cw-divider");ct&&ct.appendChild(ne)}if($.closeButtonColor?(_.style.color=$.closeButtonColor,_.classList.remove("tvw-text-cw-muted")):(_.style.color="",_.classList.add("tvw-text-cw-muted")),$.closeButtonBackgroundColor?(_.style.backgroundColor=$.closeButtonBackgroundColor,_.classList.remove("hover:tvw-bg-gray-100")):(_.style.backgroundColor="",_.classList.add("hover:tvw-bg-gray-100")),$.closeButtonBorderWidth||$.closeButtonBorderColor){let oe=$.closeButtonBorderWidth||"0px",Je=$.closeButtonBorderColor||"transparent";_.style.border=`${oe} solid ${Je}`,_.classList.remove("tvw-border-none")}else _.style.border="",_.classList.add("tvw-border-none");$.closeButtonBorderRadius?(_.style.borderRadius=$.closeButtonBorderRadius,_.classList.remove("tvw-rounded-full")):(_.style.borderRadius="",_.classList.add("tvw-rounded-full")),$.closeButtonPaddingX?(_.style.paddingLeft=$.closeButtonPaddingX,_.style.paddingRight=$.closeButtonPaddingX):(_.style.paddingLeft="",_.style.paddingRight=""),$.closeButtonPaddingY?(_.style.paddingTop=$.closeButtonPaddingY,_.style.paddingBottom=$.closeButtonPaddingY):(_.style.paddingTop="",_.style.paddingBottom="");let rt=(bo=$.closeButtonIconName)!=null?bo:"x",kt=(Co=$.closeButtonIconText)!=null?Co:"\xD7";_.innerHTML="";let yt=de(rt,"20px",$.closeButtonColor||"",2);yt?_.appendChild(yt):_.textContent=kt;let ze=(xo=$.closeButtonTooltipText)!=null?xo:"Close chat",St=(So=$.closeButtonShowTooltip)!=null?So:!0;if(_.setAttribute("aria-label",ze),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),St&&ze)){let oe=null,Je=()=>{if(oe||!_)return;oe=h("div","tvw-clear-chat-tooltip"),oe.textContent=ze;let fn=h("div");fn.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(fn);let Jt=_.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${Jt.left+Jt.width/2}px`,oe.style.top=`${Jt.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},ct=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};ne.addEventListener("mouseenter",Je),ne.addEventListener("mouseleave",ct),_.addEventListener("focus",Je),_.addEventListener("blur",ct),ne._cleanupTooltip=()=>{ct(),ne&&(ne.removeEventListener("mouseenter",Je),ne.removeEventListener("mouseleave",ct)),_&&(_.removeEventListener("focus",Je),_.removeEventListener("blur",ct))}}}let{clearChatButton:Z,clearChatButtonWrapper:Se}=q;if(Z){let L=(Ao=$.clearChat)!=null?Ao:{},ce=(To=L.enabled)!=null?To:!0,qe=(Mo=(Eo=t.layout)==null?void 0:Eo.header)==null?void 0:Mo.showClearChat,ne=qe!==void 0?qe:ce,Te=(Wo=L.placement)!=null?Wo:"inline";if(Se){Se.style.display=ne?"":"none";let{closeButtonWrapper:dt}=q;dt&&!dt.classList.contains("tvw-absolute")&&(ne?dt.classList.remove("tvw-ml-auto"):dt.classList.add("tvw-ml-auto"));let rt=Te==="top-right",kt=Se.classList.contains("tvw-absolute");if(rt!==kt&&ne){if(Se.remove(),rt)Se.className="tvw-absolute tvw-top-4 tvw-z-50",Se.style.right="48px",U.style.position="relative",U.appendChild(Se);else{Se.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Se.style.right="";let ze=U.querySelector(".tvw-border-b-cw-divider"),St=q.closeButtonWrapper;ze&&St&&St.parentElement===ze?ze.insertBefore(Se,St):ze&&ze.appendChild(Se)}let yt=q.closeButtonWrapper;yt&&!yt.classList.contains("tvw-absolute")&&(rt?yt.classList.add("tvw-ml-auto"):yt.classList.remove("tvw-ml-auto"))}}if(ne){let dt=(ko=L.size)!=null?ko:"32px";Z.style.height=dt,Z.style.width=dt;let rt=(Lo=L.iconName)!=null?Lo:"refresh-cw",kt=(Ho=L.iconColor)!=null?Ho:"";Z.innerHTML="";let yt=de(rt,"20px",kt||"",2);if(yt&&Z.appendChild(yt),kt?(Z.style.color=kt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),L.backgroundColor?(Z.style.backgroundColor=L.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let oe=L.borderWidth||"0px",Je=L.borderColor||"transparent";Z.style.border=`${oe} solid ${Je}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");L.borderRadius?(Z.style.borderRadius=L.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),L.paddingX?(Z.style.paddingLeft=L.paddingX,Z.style.paddingRight=L.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),L.paddingY?(Z.style.paddingTop=L.paddingY,Z.style.paddingBottom=L.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let ze=(Bo=L.tooltipText)!=null?Bo:"Clear chat",St=(Po=L.showTooltip)!=null?Po:!0;if(Z.setAttribute("aria-label",ze),Se&&(Se._cleanupTooltip&&(Se._cleanupTooltip(),delete Se._cleanupTooltip),St&&ze)){let oe=null,Je=()=>{if(oe||!Z)return;oe=h("div","tvw-clear-chat-tooltip"),oe.textContent=ze;let fn=h("div");fn.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(fn);let Jt=Z.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${Jt.left+Jt.width/2}px`,oe.style.top=`${Jt.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},ct=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};Se.addEventListener("mouseenter",Je),Se.addEventListener("mouseleave",ct),Z.addEventListener("focus",Je),Z.addEventListener("blur",ct),Se._cleanupTooltip=()=>{ct(),Se&&(Se.removeEventListener("mouseenter",Je),Se.removeEventListener("mouseleave",ct)),Z&&(Z.removeEventListener("focus",Je),Z.removeEventListener("blur",ct))}}}}let Ut=t.actionParsers&&t.actionParsers.length?t.actionParsers:[xn],zt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Xt.message,Xt.messageAndClick];f=Sn({parsers:Ut,handlers:zt,getSessionMetadata:c,updateSessionMetadata:w,emit:n.emit,documentRef:typeof document!="undefined"?document:null}),v=kr(t,f),b.updateConfig(t),jt(V,b.getMessages(),v),We.render(t.suggestionChips,b,se,void 0,t.suggestionChipsConfig),re(),H(b.isStreaming());let ln=((Ro=t.voiceRecognition)==null?void 0:Ro.enabled)===!0,dn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),kn=ln&&dn;if(nt.classList.remove("tvw-gap-1","tvw-gap-3"),nt.classList.add(kn?"tvw-gap-1":"tvw-gap-3"),ln&&dn)if(!I||!$e){let L=E(t.voiceRecognition,t.sendButton);L&&(I=L.micButton,$e=L.micButtonWrapper,nt.insertBefore($e,Ve),I.addEventListener("click",K),I.disabled=b.isStreaming())}else{let L=(Io=t.voiceRecognition)!=null?Io:{},ce=($o=t.sendButton)!=null?$o:{},qe=(Fo=L.iconName)!=null?Fo:"mic",ne=(Oo=ce.size)!=null?Oo:"40px",Te=(No=L.iconSize)!=null?No:ne,dt=parseFloat(Te)||24;I.style.width=Te,I.style.height=Te,I.style.minWidth=Te,I.style.minHeight=Te;let rt=(_o=(Do=L.iconColor)!=null?Do:ce.textColor)!=null?_o:"currentColor";I.innerHTML="";let kt=de(qe,dt,rt,2);kt?I.appendChild(kt):I.textContent="\u{1F3A4}";let yt=(jo=L.backgroundColor)!=null?jo:ce.backgroundColor;yt?(I.style.backgroundColor=yt,I.classList.remove("tvw-bg-cw-primary")):(I.style.backgroundColor="",I.classList.add("tvw-bg-cw-primary")),rt?(I.style.color=rt,I.classList.remove("tvw-text-white")):!rt&&!ce.textColor&&(I.style.color="",I.classList.add("tvw-text-white")),L.borderWidth?(I.style.borderWidth=L.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),L.borderColor?I.style.borderColor=L.borderColor:I.style.borderColor="",L.paddingX?(I.style.paddingLeft=L.paddingX,I.style.paddingRight=L.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),L.paddingY?(I.style.paddingTop=L.paddingY,I.style.paddingBottom=L.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let ze=$e==null?void 0:$e.querySelector(".tvw-send-button-tooltip"),St=(qo=L.tooltipText)!=null?qo:"Start voice recognition";if(((Uo=L.showTooltip)!=null?Uo:!1)&&St)if(ze)ze.textContent=St,ze.style.display="";else{let Je=document.createElement("div");Je.className="tvw-send-button-tooltip",Je.textContent=St,$e==null||$e.insertBefore(Je,I)}else ze&&(ze.style.display="none");$e.style.display="",I.disabled=b.isStreaming()}else I&&$e&&($e.style.display="none",Ae&&k());let De=(zo=t.sendButton)!=null?zo:{},Ln=(Jo=De.useIcon)!=null?Jo:!1,cn=(Yo=De.iconText)!=null?Yo:"\u2191",un=De.iconName,Nt=(Ko=De.tooltipText)!=null?Ko:"Send message",pn=(Xo=De.showTooltip)!=null?Xo:!1,gn=(Vo=De.size)!=null?Vo:"40px",Hn=De.backgroundColor,Wt=De.textColor;if(Ln){if(D.style.width=gn,D.style.height=gn,D.style.minWidth=gn,D.style.minHeight=gn,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",un){let L=parseFloat(gn)||24,ce=Wt&&typeof Wt=="string"&&Wt.trim()?Wt.trim():"currentColor",qe=de(un,L,ce,2);qe?(D.appendChild(qe),D.style.color=ce):(D.textContent=cn,Wt?D.style.color=Wt:D.classList.add("tvw-text-white"))}else D.textContent=cn,Wt?D.style.color=Wt:D.classList.add("tvw-text-white");D.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Hn?(D.style.backgroundColor=Hn,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Qo=(Go=t.copy)==null?void 0:Go.sendButtonLabel)!=null?Qo:"Send",D.style.width="",D.style.height="",D.style.minWidth="",D.style.minHeight="",D.style.fontSize="",D.style.lineHeight="",D.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Hn?(D.style.backgroundColor=Hn,D.classList.remove("tvw-bg-cw-accent")):D.classList.add("tvw-bg-cw-accent"),Wt?D.style.color=Wt:D.classList.add("tvw-text-white");De.borderWidth?(D.style.borderWidth=De.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),De.borderColor?D.style.borderColor=De.borderColor:D.style.borderColor="",De.paddingX?(D.style.paddingLeft=De.paddingX,D.style.paddingRight=De.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),De.paddingY?(D.style.paddingTop=De.paddingY,D.style.paddingBottom=De.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let mn=Ve==null?void 0:Ve.querySelector(".tvw-send-button-tooltip");if(pn&&Nt)if(mn)mn.textContent=Nt,mn.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=Nt,Ve==null||Ve.insertBefore(L,D)}else mn&&(mn.style.display="none");let hn=(Zo=t.statusIndicator)!=null?Zo:{},Fr=(er=hn.visible)!=null?er:!0;if(at.style.display=Fr?"":"none",b){let L=b.getStatus(),ce=qe=>{var ne,Te,dt,rt;return qe==="idle"?(ne=hn.idleText)!=null?ne:tt.idle:qe==="connecting"?(Te=hn.connectingText)!=null?Te:tt.connecting:qe==="connected"?(dt=hn.connectedText)!=null?dt:tt.connected:qe==="error"?(rt=hn.errorText)!=null?rt:tt.error:tt[qe]};at.textContent=ce(L)}},open(){m&&Ye(!0,"api")},close(){m&&Ye(!1,"api")},toggle(){m&&Ye(!R,"api")},clearChat(){b.clearMessages();try{localStorage.removeItem(rn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rn}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==rn)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 l=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),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)}a={},f.syncFromMetadata()},setMessage(l){return!se||b.isStreaming()?!1:(!R&&m&&Ye(!0,"system"),se.value=l,se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(b.isStreaming())return!1;let u=(l==null?void 0:l.trim())||se.value.trim();return u?(!R&&m&&Ye(!0,"system"),se.value="",b.sendMessage(u),!0):!1},startVoiceRecognition(){return Ae||b.isStreaming()||!ft()?!1:(!R&&m&&Ye(!0,"system"),pe.manuallyDeactivated=!1,Bt(),te("user"),!0)},stopVoiceRecognition(){return Ae?(pe.manuallyDeactivated=!0,Bt(),k("user"),!0):!1},injectTestMessage(l){!R&&m&&Ye(!0,"system"),b.injectTestEvent(l)},getMessages(){return b.getMessages()},getStatus(){return b.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){w(l)},on(l,u){return n.on(l,u)},off(l,u){n.off(l,u)},isOpen(){return m&&R},isVoiceActive(){return pe.active},getState(){return{open:m&&R,launcherEnabled:m,voiceActive:pe.active,streaming:b.isStreaming()}},showCSATFeedback(l){!R&&m&&Ye(!0,"system");let u=V.querySelector(".tvw-feedback-container");u&&u.remove();let T=Vn({onSubmit:async(P,C)=>{var G;b.isClientTokenMode()&&await b.submitCSATFeedback(P,C),(G=l==null?void 0:l.onSubmit)==null||G.call(l,P,C)},onDismiss:l==null?void 0:l.onDismiss,...l});V.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!R&&m&&Ye(!0,"system");let u=V.querySelector(".tvw-feedback-container");u&&u.remove();let T=Gn({onSubmit:async(P,C)=>{var G;b.isClientTokenMode()&&await b.submitNPSFeedback(P,C),(G=l==null?void 0:l.onSubmit)==null||G.call(l,P,C)},onDismiss:l==null?void 0:l.onDismiss,...l});V.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return b.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return b.submitNPSFeedback(l,u)},destroy(){Fe.forEach(l=>l()),j.remove(),ie==null||ie.destroy(),Q==null||Q.remove(),Le&&_.removeEventListener("click",Le)}};if((((Fs=o==null?void 0:o.debugTools)!=null?Fs:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:ve,getMessages:ve.getMessages,getStatus:ve.getStatus,getMetadata:ve.getPersistentMetadata,updateMetadata:ve.updatePersistentMetadata,clearHistory:()=>ve.clearChat(),setVoiceActive:T=>T?ve.startVoiceRecognition():ve.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Fe.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}return ve};var xs={},gi=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let s=document.querySelector(e);if(!s)throw new Error(`Chat widget target "${e}" was not found`);return s}return e},mi=()=>{try{if(typeof xs!="undefined"&&xs.url)return new URL("../widget.css",xs.url).href}catch{}return null},Lr=e=>{let s=mi(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let r=t.cloneNode(!0);e.insertBefore(r,e.firstChild)};if(e instanceof ShadowRoot)if(s){let t=document.createElement("link");t.rel="stylesheet",t.href=s,t.setAttribute("data-vanilla-agent","true"),e.insertBefore(t,e.firstChild)}else o();else if(!document.head.querySelector("link[data-vanilla-agent]")&&s){let r=document.createElement("link");r.rel="stylesheet",r.href=s,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},Ss=e=>{var c,w,g,p;let s=gi(e.target),o=document.createElement("div");o.className="vanilla-agent-host";let t=(g=(w=(c=e.config)==null?void 0:c.launcher)==null?void 0:w.enabled)!=null?g:!0;t||(o.style.height="100%"),s.appendChild(o);let r=e.useShadowDom===!0,n,i;if(r){let f=o.attachShadow({mode:"open"});i=f,n=document.createElement("div"),n.id="vanilla-agent-root",t||(n.style.height="100%",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1",n.style.minHeight="0"),f.appendChild(n),Lr(f)}else i=o,n=document.createElement("div"),n.id="vanilla-agent-root",t||(n.style.height="100%",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1",n.style.minHeight="0"),o.appendChild(n),Lr(o);let a=Qn(n,e.config,{debugTools:e.debugTools});(p=e.onReady)==null||p.call(e);let d={...a,host:o,destroy(){a.destroy(),o.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};function $t(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(s=>s.toString()).join(", ")}]`:e.toString()}function hi(e){if(e)return{getHeaders:$t(e.getHeaders),onFeedback:$t(e.onFeedback),onCopy:$t(e.onCopy),requestMiddleware:$t(e.requestMiddleware),actionHandlers:$t(e.actionHandlers),actionParsers:$t(e.actionParsers),postprocessMessage:$t(e.postprocessMessage),contextProviders:$t(e.contextProviders),streamParser:$t(e.streamParser)}}var Hr=`({ text, message }: any) => {
61
+ const jsonSource = (message as any).rawContent || text || message.content;
62
+ if (!jsonSource || typeof jsonSource !== 'string') return null;
63
+ let cleanJson = jsonSource
64
+ .replace(/^\`\`\`(?:json)?\\s*\\n?/, '')
65
+ .replace(/\\n?\`\`\`\\s*$/, '')
66
+ .trim();
67
+ if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;
68
+ try {
69
+ const parsed = JSON.parse(cleanJson);
70
+ if (parsed.action) return { type: parsed.action, payload: parsed };
71
+ } catch (e) { return null; }
72
+ return null;
73
+ }`,Br=`function(ctx) {
74
+ var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
75
+ if (!jsonSource || typeof jsonSource !== 'string') return null;
76
+ var cleanJson = jsonSource
77
+ .replace(/^\`\`\`(?:json)?\\s*\\n?/, '')
78
+ .replace(/\\n?\`\`\`\\s*$/, '')
79
+ .trim();
80
+ if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;
81
+ try {
82
+ var parsed = JSON.parse(cleanJson);
83
+ if (parsed.action) return { type: parsed.action, payload: parsed };
84
+ } catch (e) { return null; }
85
+ return null;
86
+ }`,Pr=`(action: any, context: any) => {
87
+ if (action.type !== 'nav_then_click') return;
88
+ const payload = action.payload || action.raw || {};
89
+ const url = payload?.page;
90
+ const text = payload?.on_load_text || 'Navigating...';
91
+ if (!url) return { handled: true, displayText: text };
92
+ const messageId = context.message?.id;
93
+ const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');
94
+ const actionKey = \`nav_\${messageId}_\${url}\`;
95
+ if (processedActions.includes(actionKey)) {
96
+ return { handled: true, displayText: text };
97
+ }
98
+ processedActions.push(actionKey);
99
+ localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));
100
+ const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
101
+ window.location.href = targetUrl;
102
+ return { handled: true, displayText: text };
103
+ }`,Rr=`function(action, context) {
104
+ if (action.type !== 'nav_then_click') return;
105
+ var payload = action.payload || action.raw || {};
106
+ var url = payload.page;
107
+ var text = payload.on_load_text || 'Navigating...';
108
+ if (!url) return { handled: true, displayText: text };
109
+ var messageId = context.message ? context.message.id : null;
110
+ var processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');
111
+ var actionKey = 'nav_' + messageId + '_' + url;
112
+ if (processedActions.includes(actionKey)) {
113
+ return { handled: true, displayText: text };
114
+ }
115
+ processedActions.push(actionKey);
116
+ localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));
117
+ var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
118
+ window.location.href = targetUrl;
119
+ return { handled: true, displayText: text };
120
+ }`,fi=`(parsed: any) => {
121
+ if (!parsed || typeof parsed !== 'object') return null;
122
+ if (parsed.action === 'nav_then_click') return 'Navigating...';
123
+ if (parsed.action === 'message') return parsed.text || '';
124
+ if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
125
+ return parsed.text || null;
126
+ }`,wi=`function(parsed) {
127
+ if (!parsed || typeof parsed !== 'object') return null;
128
+ if (parsed.action === 'nav_then_click') return 'Navigating...';
129
+ if (parsed.action === 'message') return parsed.text || '';
130
+ if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
131
+ return parsed.text || null;
132
+ }`;function yi(e){if(!e)return null;let s=e.toString();return s.includes("createJsonStreamParser")||s.includes("partial-json")?"json":s.includes("createRegexJsonParser")||s.includes("regex")?"regex-json":s.includes("createXmlParser")||s.includes("<text>")?"xml":null}function Zn(e){var s,o;return(o=(s=e.parserType)!=null?s:yi(e.streamParser))!=null?o:"plain"}function es(e,s){let o=[];return e.toolCall&&(o.push(`${s}toolCall: {`),Object.entries(e.toolCall).forEach(([t,r])=>{typeof r=="string"&&o.push(`${s} ${t}: "${r}",`)}),o.push(`${s}},`)),o}function ts(e,s,o){let t=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),n=(o==null?void 0:o.onFeedback)||(o==null?void 0:o.onCopy);return(r||n)&&(t.push(`${s}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?t.push(`${s} ${i}: "${a}",`):typeof a=="boolean"&&t.push(`${s} ${i}: ${a},`))}),o!=null&&o.onFeedback&&t.push(`${s} onFeedback: ${o.onFeedback},`),o!=null&&o.onCopy&&t.push(`${s} onCopy: ${o.onCopy},`),t.push(`${s}},`)),t}function ns(e,s){let o=[];if(e.markdown){let t=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(t||r)&&(o.push(`${s}markdown: {`),t&&(o.push(`${s} options: {`),Object.entries(e.markdown.options).forEach(([n,i])=>{typeof i=="string"?o.push(`${s} ${n}: "${i}",`):typeof i=="boolean"&&o.push(`${s} ${n}: ${i},`)}),o.push(`${s} },`)),r&&o.push(`${s} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),o.push(`${s}},`))}return o}function ss(e,s){let o=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(n=>n!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(n=>n!=="renderUserMessage"&&n!=="renderAssistantMessage");(t||r)&&(o.push(`${s}layout: {`),t&&(o.push(`${s} header: {`),Object.entries(e.layout.header).forEach(([n,i])=>{n!=="render"&&(typeof i=="string"?o.push(`${s} ${n}: "${i}",`):typeof i=="boolean"&&o.push(`${s} ${n}: ${i},`))}),o.push(`${s} },`)),r&&(o.push(`${s} messages: {`),Object.entries(e.layout.messages).forEach(([n,i])=>{n==="renderUserMessage"||n==="renderAssistantMessage"||(n==="avatar"&&typeof i=="object"&&i!==null?(o.push(`${s} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?o.push(`${s} ${a}: "${d}",`):typeof d=="boolean"&&o.push(`${s} ${a}: ${d},`)}),o.push(`${s} },`)):n==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(o.push(`${s} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?o.push(`${s} ${d}: "${c}",`):typeof c=="boolean"&&o.push(`${s} ${d}: ${c},`))}),o.push(`${s} },`)):typeof i=="string"?o.push(`${s} ${n}: "${i}",`):typeof i=="boolean"&&o.push(`${s} ${n}: ${i},`))}),o.push(`${s} },`)),o.push(`${s}},`))}return o}function As(e,s){let o=[];return e&&(e.getHeaders&&o.push(`${s}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&o.push(`${s}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&o.push(`${s}actionParsers: ${e.actionParsers},`),e.actionHandlers&&o.push(`${s}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&o.push(`${s}contextProviders: ${e.contextProviders},`),e.streamParser&&o.push(`${s}streamParser: ${e.streamParser},`)),o}function Ir(e,s="esm",o){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let r=o?{...o,hooks:hi(o.hooks)}:void 0;return s==="esm"?vi(t,r):s==="script-installer"?xi(t):s==="script-advanced"?Ai(t,r):s==="react-component"?bi(t,r):s==="react-advanced"?Ci(t,r):Si(t,r)}function vi(e,s){let o=s==null?void 0:s.hooks,t=Zn(e),r=t!=="plain",n=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),r&&n.push(` parserType: "${t}",`),e.theme&&(n.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{n.push(` ${i}: "${a}",`)}),n.push(" },")),e.launcher&&(n.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{n.push(` ${i}: "${a}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"?n.push(` ${i}: ${a},`):typeof a=="number"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{n.push(` ${i}: ${a},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{n.push(` "${i}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...es(e," ")),n.push(...ts(e," ",o)),n.push(...ns(e," ")),n.push(...ss(e," ")),n.push(...As(o," ")),e.debug&&n.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?n.push(` postprocessMessage: ${o.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),n.push(" }"),n.push("});"),n.join(`
133
+ `)}function bi(e,s){let o=s==null?void 0:s.hooks,t=Zn(e),r=t!=="plain",n=["// 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 e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),r&&n.push(` parserType: "${t}",`),e.theme&&(n.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{n.push(` ${i}: "${a}",`)}),n.push(" },")),e.launcher&&(n.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{n.push(` ${i}: "${a}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"?n.push(` ${i}: ${a},`):typeof a=="number"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{n.push(` ${i}: ${a},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{n.push(` "${i}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...es(e," ")),n.push(...ts(e," ",o)),n.push(...ns(e," ")),n.push(...ss(e," ")),n.push(...As(o," ")),e.debug&&n.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?n.push(` postprocessMessage: ${o.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage in your app:"),n.push("// import { ChatWidget } from './components/ChatWidget';"),n.push("//"),n.push("// export default function App() {"),n.push("// return ("),n.push("// <div>"),n.push("// {/* Your app content */}"),n.push("// <ChatWidget />"),n.push("// </div>"),n.push("// );"),n.push("// }"),n.join(`
134
+ `)}function Ci(e,s){let o=s==null?void 0:s.hooks,t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),e.theme&&(t.push(" theme: {"),Object.entries(e.theme).forEach(([r,n])=>{t.push(` ${r}: "${n}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([r,n])=>{typeof n=="string"?t.push(` ${r}: "${n}",`):typeof n=="boolean"&&t.push(` ${r}: ${n},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([r,n])=>{t.push(` ${r}: "${n}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,n])=>{typeof n=="string"?t.push(` ${r}: "${n}",`):typeof n=="boolean"&&t.push(` ${r}: ${n},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,n])=>{typeof n=="string"?t.push(` ${r}: "${n}",`):typeof n=="boolean"?t.push(` ${r}: ${n},`):typeof n=="number"&&t.push(` ${r}: ${n},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,n])=>{typeof n=="string"?t.push(` ${r}: "${n}",`):typeof n=="boolean"&&t.push(` ${r}: ${n},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([r,n])=>{t.push(` ${r}: ${n},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...es(e," ")),t.push(...ts(e," ",o)),t.push(...ns(e," ")),t.push(...ss(e," ")),o!=null&&o.getHeaders&&t.push(` getHeaders: ${o.getHeaders},`),o!=null&&o.contextProviders&&t.push(` contextProviders: ${o.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),o!=null&&o.streamParser?t.push(` streamParser: ${o.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${fi}),`)),o!=null&&o.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${o.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${Hr}`),t.push(" ],")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Parser for markdown-wrapped JSON"),t.push(` ${Hr}`),t.push(" ],")),o!=null&&o.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${o.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${Pr}`),t.push(" ],")):(t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(` ${Pr}`),t.push(" ],")),o!=null&&o.postprocessMessage?t.push(` postprocessMessage: ${o.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),o!=null&&o.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${o.requestMiddleware})({ payload, config });`),t.push(" const merged = customResult || payload;"),t.push(" return {"),t.push(" ...merged,"),t.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),t.push(" };"),t.push(" }")):(t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }")),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
135
+ `)}function $r(e){var r;let s=Zn(e),o=s!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.flowId&&(t.flowId=e.flowId),o&&(t.parserType=s),e.theme&&(t.theme=e.theme),e.launcher&&(t.launcher=e.launcher),e.copy&&(t.copy=e.copy),e.sendButton&&(t.sendButton=e.sendButton),e.voiceRecognition&&(t.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(t.statusIndicator=e.statusIndicator),e.features&&(t.features=e.features),((r=e.suggestionChips)==null?void 0:r.length)>0&&(t.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(t.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(t.debug=e.debug),e.toolCall){let n={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(n[i]=a)}),Object.keys(n).length>0&&(t.toolCall=n)}if(e.messageActions){let n={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(n[i]=a)}),Object.keys(n).length>0&&(t.messageActions=n)}if(e.markdown){let n={};e.markdown.options&&(n.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(n.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(n).length>0&&(t.markdown=n)}if(e.layout){let n={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,d])=>{a!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(n.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,d])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(a==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([w,g])=>{w!=="format"&&(typeof g=="string"||typeof g=="boolean")&&(c[w]=g)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(n.messages=i)}Object.keys(n).length>0&&(t.layout=n)}return t}function xi(e){let s=$r(e);return`<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js" data-config='${JSON.stringify(s,null,0).replace(/'/g,"&#39;")}'></script>`}function Si(e,s){let o=s==null?void 0:s.hooks,t=Zn(e),r=t!=="plain",n=["<!-- 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 e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),r&&n.push(` parserType: "${t}",`),e.theme&&(n.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{n.push(` ${i}: "${a}",`)}),n.push(" },")),e.launcher&&(n.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{n.push(` ${i}: "${a}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"?n.push(` ${i}: ${a},`):typeof a=="number"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?n.push(` ${i}: "${a}",`):typeof a=="boolean"&&n.push(` ${i}: ${a},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{n.push(` ${i}: ${a},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{n.push(` "${i}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...es(e," ")),n.push(...ts(e," ",o)),n.push(...ns(e," ")),n.push(...ss(e," ")),n.push(...As(o," ")),e.debug&&n.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?n.push(` postprocessMessage: ${o.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
136
+ `)}function Ai(e,s){let o=s==null?void 0:s.hooks,t=$r(e),n=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
137
+ `).map((i,a)=>a===0?i:" "+i).join(`
138
+ `)};`,""," // Constants"," var CDN_BASE = 'https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist';"," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-vanilla-agent]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-vanilla-agent', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return o!=null&&o.getHeaders&&(n.push(` widgetConfig.getHeaders = ${o.getHeaders};`),n.push("")),o!=null&&o.contextProviders&&(n.push(` widgetConfig.contextProviders = ${o.contextProviders};`),n.push("")),o!=null&&o.streamParser?n.push(` widgetConfig.streamParser = ${o.streamParser};`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(" widgetConfig.streamParser = function() {"),n.push(` return agentWidget.createFlexibleJsonStreamParser(${wi});`),n.push(" };")),n.push(""),o!=null&&o.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` var customParsers = ${o.actionParsers};`),n.push(" widgetConfig.actionParsers = customParsers.concat(["),n.push(" agentWidget.defaultJsonActionParser,"),n.push(` ${Br}`),n.push(" ]);")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" widgetConfig.actionParsers = ["),n.push(" agentWidget.defaultJsonActionParser,"),n.push(` ${Br}`),n.push(" ];")),n.push(""),o!=null&&o.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` var customHandlers = ${o.actionHandlers};`),n.push(" widgetConfig.actionHandlers = customHandlers.concat(["),n.push(" agentWidget.defaultActionHandlers.message,"),n.push(" agentWidget.defaultActionHandlers.messageAndClick,"),n.push(` ${Rr}`),n.push(" ]);")):(n.push(" // Action handlers for navigation and other actions"),n.push(" widgetConfig.actionHandlers = ["),n.push(" agentWidget.defaultActionHandlers.message,"),n.push(" agentWidget.defaultActionHandlers.messageAndClick,"),n.push(` ${Rr}`),n.push(" ];")),n.push(""),o!=null&&o.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" widgetConfig.requestMiddleware = function(ctx) {"),n.push(` var customResult = (${o.requestMiddleware})(ctx);`),n.push(" var merged = customResult || ctx.payload;"),n.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),n.push(" };")):(n.push(" // Send DOM context with each request"),n.push(" widgetConfig.requestMiddleware = function(ctx) {"),n.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),n.push(" };")),n.push(""),o!=null&&o.postprocessMessage?n.push(` widgetConfig.postprocessMessage = ${o.postprocessMessage};`):(n.push(" // Markdown postprocessor"),n.push(" widgetConfig.postprocessMessage = function(ctx) {"),n.push(" return agentWidget.markdownPostprocessor(ctx.text);"),n.push(" };")),n.push(""),(o!=null&&o.onFeedback||o!=null&&o.onCopy)&&(n.push(" // Message action callbacks"),n.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),o!=null&&o.onFeedback&&n.push(` widgetConfig.messageActions.onFeedback = ${o.onFeedback};`),o!=null&&o.onCopy&&n.push(` widgetConfig.messageActions.onCopy = ${o.onCopy};`),n.push("")),n.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('vanilla-agent:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('vanilla-agent:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),n.join(`
139
+ `)}var Ti=Ss;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,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});
68
140
  //# sourceMappingURL=index.cjs.map