vanilla-agent 1.32.0 → 1.34.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 vi=Object.create;var Rn=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var Ci=Object.getOwnPropertyNames;var xi=Object.getPrototypeOf,Si=Object.prototype.hasOwnProperty;var Ai=(e,n)=>{for(var o in n)Rn(e,o,{get:n[o],enumerable:!0})},Tr=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Ci(n))!Si.call(e,r)&&r!==o&&Rn(e,r,{get:()=>n[r],enumerable:!(t=bi(n,r))||t.enumerable});return e};var Ti=(e,n,o)=>(o=e!=null?vi(xi(e)):{},Tr(n||!e||!e.__esModule?Rn(o,"default",{value:e,enumerable:!0}):o,e)),Ei=e=>Tr(Rn({},"__esModule",{value:!0}),e);var pa={};Ai(pa,{AgentWidgetClient:()=>Gt,AgentWidgetSession:()=>nn,AttachmentManager:()=>Qt,DEFAULT_DARK_THEME:()=>As,DEFAULT_LIGHT_THEME:()=>Ss,DEFAULT_WIDGET_CONFIG:()=>Be,attachHeaderToContainer:()=>Zt,buildComposer:()=>on,buildDefaultHeader:()=>ms,buildExpandedHeader:()=>fs,buildHeader:()=>qt,buildHeaderWithLayout:()=>sn,buildMinimalHeader:()=>hs,componentRegistry:()=>dn,createActionManager:()=>Wn,createAgentExperience:()=>os,createBubbleWithLayout:()=>ei,createCSATFeedback:()=>ns,createComponentMiddleware:()=>li,createComponentStreamParser:()=>Qn,createDirectivePostprocessor:()=>kr,createFlexibleJsonStreamParser:()=>Ir,createImagePart:()=>_r,createJsonStreamParser:()=>_n,createLocalStorageAdapter:()=>Gn,createMarkdownProcessor:()=>xn,createMarkdownProcessorFromConfig:()=>Sn,createMessageActions:()=>ys,createNPSFeedback:()=>ss,createPlainTextParser:()=>On,createRegexJsonParser:()=>Dn,createStandardBubble:()=>rn,createTextPart:()=>Un,createTypingIndicator:()=>Tn,createXmlParser:()=>jn,default:()=>ua,defaultActionHandlers:()=>en,defaultJsonActionParser:()=>Mn,directivePostprocessor:()=>Pr,escapeHtml:()=>Fn,extractComponentDirectiveFromMessage:()=>ts,fileToImagePart:()=>jr,generateAssistantMessageId:()=>zn,generateCodeSnippet:()=>fi,generateMessageId:()=>Fr,generateUserMessageId:()=>qn,getDisplayText:()=>Nr,getHeaderLayout:()=>ws,getImageParts:()=>Dr,hasComponentDirective:()=>es,hasImages:()=>Or,headerLayouts:()=>Xn,initAgentWidget:()=>Ls,isComponentDirectiveType:()=>ai,markdownPostprocessor:()=>us,mergeWithDefaults:()=>Vn,normalizeContent:()=>$r,pluginRegistry:()=>En,renderComponentDirective:()=>Zn,validateImageFile:()=>qr});module.exports=Ei(pa);var Mr=require("marked"),Mi=e=>{if(e)return e},xn=e=>{var r,s;let n=e==null?void 0:e.markedOptions,o=new Mr.Marked({gfm:(r=n==null?void 0:n.gfm)!=null?r:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),t=Mi(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},Sn=e=>e?xn({markedOptions:e.options,renderer:e.renderer}):xn(),Wi=xn(),us=e=>Wi(e),Fn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Wr=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Er=e=>`%%FORM_PLACEHOLDER_${e}%%`,Lr=(e,n)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Er(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let s=Er(n.length);return n.push({token:s,type:r}),s}),o},kr=e=>{let n=Sn(e);return o=>{let t=[],r=Lr(o,t),s=n(r);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${Wr(a)}"></div>`;s=s.replace(d,f)}),s}},Pr=e=>{let n=[],o=Lr(e,n),t=us(o);return n.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Wr(s)}"></div>`;t=t.replace(i,d)}),t};var jt=require("partial-json"),$n=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ps=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)}},Li=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),o=(a=e.startedAt)!=null?a:n,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Hr=e=>e.status==="complete"?Li(e):e.status==="pending"?"Waiting":"",ki=e=>{var r,s,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=(s=e.startedAt)!=null?s: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 Br=e=>e.status==="complete"?ki(e):"Using tool...",Pi=()=>{let e=null,n=0,o=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,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<=n)return e!==null?{text:e,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},Nn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},On=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Dn=()=>{var n;let e=Pi();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(o)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},_n=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,jt.parse)(o,jt.STR|jt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?$n(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=$n(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Ir=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?$n(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$n(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=o)return n!==null?{text:n,raw:s}:null;try{let a=(0,jt.parse)(s,jt.STR|jt.OBJ),d=r(a);d!==null&&(n=d)}catch{}return o=s.length,{text:n||"",raw:s}},close:()=>{}}},jn=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Hi="https://api.travrse.ai/v1/dispatch",Rr="https://api.travrse.ai";function Bi(e){switch(e){case"json":return _n;case"regex-json":return Dn;case"xml":return jn;case"plain":default:return On}}var Gt=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=n.apiUrl)!=null?o:Hi,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Bi(n.parserType),this.contextProviders=(r=n.contextProviders)!=null?r:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(n){var t;let o=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Rr;return n==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,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=(n=this.config).onSessionInit)==null||o.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,o={token:this.config.clientToken,...this.config.flowId&&{flow_id:this.config.flowId},...n&&{session_id:n}},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$/,""))||Rr}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.message_id)throw new Error(`message_id is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,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:n,type:o})}async submitCSATFeedback(n,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:n,comment:o})}async submitNPSFeedback(n,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:n,comment:o})}async dispatch(n,o){return this.isClientTokenMode()?this.dispatchClientToken(n,o):this.dispatchProxy(n,o)}async dispatchClientToken(n,o){var r,s,i,a;let t=new AbortController;n.signal&&n.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,(s=(r=this.config).onSessionExpired)==null||s.call(r);let w=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:w}),w}let p=await this.buildPayload(n.messages),f=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([w])=>w!=="session_id")):void 0,m={session_id:d.sessionId,messages:n.messages.map(w=>{var h,R;return{id:w.id,role:w.role,content:(R=(h=w.contentParts)!=null?h:w.rawContent)!=null?R:w.content}}),...n.assistantMessageId&&{assistant_message_id:n.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...p.context&&{context:p.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",m);let g=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m),signal:t.signal});if(!g.ok){let w=await g.json().catch(()=>({error:"Chat request failed"}));if(g.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let R=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:R}),R}if(g.status===429){let R=new Error(w.hint||"Message limit reached for this session.");throw o({type:"error",error:R}),R}let h=new Error(w.error||"Failed to send message");throw o({type:"error",error:h}),h}if(!g.body){let w=new Error("No response body received");throw o({type:"error",error:w}),w}o({type:"status",status:"connected"});try{await this.streamResponse(g.body,o,n.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let p=d instanceof Error?d:new Error(String(d));throw!p.message.includes("Session expired")&&!p.message.includes("Message limit")&&o({type:"error",error:p}),p}}async dispatchProxy(n,o){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...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:s,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:s,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(n){let t={messages:n.slice().sort((r,s)=>{let i=new Date(r.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(r=>{var s,i;return{role:r.role,content:(i=(s=r.contentParts)!=null?s:r.rawContent)!=null?i:r.content,createdAt:r.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,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(n,o,t,r,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);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:s()};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(n,o,t){var Pe,V,_,tt,at,lt,kt,Ft,q,we,dt,ct,Ue,ut,$t,Pt,Ht,F,Oe,me,nt,he,st,Te,xt,St,ae,Je,Qe,He,Ye,Wt,ft,ot,$,wt,yt,At,te,ye,Re,vt,Ze,Bt,It,Nt,tn,Ot,Le,pn,gn,Dt,Ln,kn,mn,Yt;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,p=()=>a+d++,f=k=>{let le=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,Se=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,De=k.tools?k.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...k,reasoning:le,toolCall:Se,tools:De}},m=k=>{o({type:"message",message:f(k)})},g=null,w={current:null},h=new Map,R=new Map,M={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},S=k=>{if(k==null)return null;try{return String(k)}catch{return null}},I=k=>{var le,Se,De,et,Ke;return S((Ke=(et=(De=(Se=(le=k.stepId)!=null?le:k.step_id)!=null?Se:k.step)!=null?De:k.parentId)!=null?et:k.flowStepId)!=null?Ke:k.flow_step_id)},v=k=>{var le,Se,De,et,Ke,ke,L;return S((L=(ke=(Ke=(et=(De=(Se=(le=k.callId)!=null?le:k.call_id)!=null?Se:k.requestId)!=null?De:k.request_id)!=null?et:k.toolCallId)!=null?Ke:k.tool_call_id)!=null?ke:k.stepId)!=null?L:k.step_id)},O=()=>g||(g={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p()},m(g),g),C=(k,le)=>{M.lastId=le,k&&M.byStep.set(k,le)},W=(k,le)=>{var Ke;let Se=(Ke=k.reasoningId)!=null?Ke:k.id,De=I(k);if(Se){let ke=String(Se);return C(De,ke),ke}if(De){let ke=M.byStep.get(De);if(ke)return M.lastId=ke,ke}if(M.lastId&&!le)return M.lastId;if(!le)return null;let et=`reason-${p()}`;return C(De,et),et},K=k=>{let le=h.get(k);if(le)return le;let Se={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:k,status:"streaming",chunks:[]}};return h.set(k,Se),m(Se),Se},J=(k,le)=>{y.lastId=le,k&&y.byCall.set(k,le)},U=(k,le)=>{var Ke;let Se=(Ke=k.toolId)!=null?Ke:k.id,De=v(k);if(Se){let ke=String(Se);return J(De,ke),ke}if(De){let ke=y.byCall.get(De);if(ke)return y.lastId=ke,ke}if(y.lastId&&!le)return y.lastId;if(!le)return null;let et=`tool-${p()}`;return J(De,et),et},j=k=>{let le=R.get(k);if(le)return le;let Se={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:k,status:"pending"}};return R.set(k,Se),m(Se),Se},D=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let le=Number(k);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let Se=Date.parse(k);if(!Number.isNaN(Se))return Se}return Date.now()},Y=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},H=new Map,X=new Map;for(;;){let{done:k,value:le}=await r.read();if(k)break;i+=s.decode(le,{stream:!0});let Se=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=(Pe=Se.pop())!=null?Pe:"";for(let De of Se){let et=De.split(`
7
+ `),Ke="message",ke="";for(let oe of et)oe.startsWith("event:")?Ke=oe.replace("event:","").trim():oe.startsWith("data:")&&(ke+=oe.replace("data:","").trim());if(!ke)continue;let L;try{L=JSON.parse(ke)}catch(oe){o({type:"error",error:oe instanceof Error?oe:new Error("Failed to parse chat stream payload")});continue}let bt=Ke!=="message"?Ke:(V=L.type)!=null?V:"message";if(this.parseSSEEvent){w.current=g;let oe=await this.handleCustomSSEEvent(L,o,w,m,p);if(w.current&&!g&&(g=w.current),oe)continue}if(bt==="reason_start"){let oe=(_=W(L,!0))!=null?_:`reason-${p()}`,B=K(oe);B.reasoning=(tt=B.reasoning)!=null?tt:{id:oe,status:"streaming",chunks:[]},B.reasoning.startedAt=(lt=B.reasoning.startedAt)!=null?lt:D((at=L.startedAt)!=null?at:L.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",m(B)}else if(bt==="reason_chunk"){let oe=(Ft=(kt=W(L,!1))!=null?kt:W(L,!0))!=null?Ft:`reason-${p()}`,B=K(oe);B.reasoning=(q=B.reasoning)!=null?q:{id:oe,status:"streaming",chunks:[]},B.reasoning.startedAt=(dt=B.reasoning.startedAt)!=null?dt:D((we=L.startedAt)!=null?we:L.timestamp);let E=(ut=(Ue=(ct=L.reasoningText)!=null?ct:L.text)!=null?Ue:L.delta)!=null?ut:"";if(E&&L.hidden!==!0&&B.reasoning.chunks.push(String(E)),B.reasoning.status=L.done?"complete":"streaming",L.done){B.reasoning.completedAt=D(($t=L.completedAt)!=null?$t:L.timestamp);let z=(Pt=B.reasoning.startedAt)!=null?Pt:Date.now();B.reasoning.durationMs=Math.max(0,((Ht=B.reasoning.completedAt)!=null?Ht:Date.now())-z)}B.streaming=B.reasoning.status!=="complete",m(B)}else if(bt==="reason_complete"){let oe=(Oe=(F=W(L,!1))!=null?F:W(L,!0))!=null?Oe:`reason-${p()}`,B=h.get(oe);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=D((me=L.completedAt)!=null?me:L.timestamp);let z=(nt=B.reasoning.startedAt)!=null?nt:Date.now();B.reasoning.durationMs=Math.max(0,((he=B.reasoning.completedAt)!=null?he:Date.now())-z),B.streaming=!1,m(B)}let E=I(L);E&&M.byStep.delete(E)}else if(bt==="tool_start"){let oe=(st=U(L,!0))!=null?st:`tool-${p()}`,B=j(oe),E=(Te=B.toolCall)!=null?Te:{id:oe,status:"pending"};E.name=(xt=L.toolName)!=null?xt:E.name,E.status="running",L.args!==void 0&&(E.args=L.args),E.startedAt=(ae=E.startedAt)!=null?ae:D((St=L.startedAt)!=null?St:L.timestamp),E.completedAt=void 0,E.durationMs=void 0,B.toolCall=E,B.streaming=!0,m(B)}else if(bt==="tool_chunk"){let oe=(Qe=(Je=U(L,!1))!=null?Je:U(L,!0))!=null?Qe:`tool-${p()}`,B=j(oe),E=(He=B.toolCall)!=null?He:{id:oe,status:"running"};E.startedAt=(Wt=E.startedAt)!=null?Wt:D((Ye=L.startedAt)!=null?Ye:L.timestamp);let z=($=(ot=(ft=L.text)!=null?ft:L.delta)!=null?ot:L.message)!=null?$:"";z&&(E.chunks=(wt=E.chunks)!=null?wt:[],E.chunks.push(String(z))),E.status="running",B.toolCall=E,B.streaming=!0,m(B)}else if(bt==="tool_complete"){let oe=(At=(yt=U(L,!1))!=null?yt:U(L,!0))!=null?At:`tool-${p()}`,B=j(oe),E=(te=B.toolCall)!=null?te:{id:oe,status:"running"};if(E.status="complete",L.result!==void 0&&(E.result=L.result),typeof L.duration=="number"&&(E.duration=L.duration),E.completedAt=D((ye=L.completedAt)!=null?ye:L.timestamp),typeof L.duration=="number")E.durationMs=L.duration;else{let fe=(Re=E.startedAt)!=null?Re:Date.now();E.durationMs=Math.max(0,((vt=E.completedAt)!=null?vt:Date.now())-fe)}B.toolCall=E,B.streaming=!1,m(B);let z=v(L);z&&y.byCall.delete(z)}else if(bt==="step_chunk"){let oe=L.stepType,B=L.executionType;if(oe==="tool"||B==="context")continue;let E=O(),z=(Nt=(It=(Bt=(Ze=L.text)!=null?Ze:L.delta)!=null?Bt:L.content)!=null?It:L.chunk)!=null?Nt:"";if(z){let Ee=((tn=X.get(E.id))!=null?tn:"")+z;E.rawContent=Ee,H.has(E.id)||H.set(E.id,this.createStreamParser());let Xe=H.get(E.id),Ie=Ee.trim().startsWith("{")||Ee.trim().startsWith("[");if(Ie&&X.set(E.id,Ee),Xe.__isPlainTextParser===!0){E.content+=z,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,m(E);continue}let We=Xe.processChunk(Ee);if(We instanceof Promise)We.then(Ce=>{var Ve;let xe=typeof Ce=="string"?Ce:(Ve=Ce==null?void 0:Ce.text)!=null?Ve:null;if(xe!==null&&xe.trim()!==""){let ce=g;ce&&ce.id===E.id&&(ce.content=xe,m(ce))}else if(!Ie&&!Ee.trim().startsWith("<")){let ce=g;ce&&ce.id===E.id&&(ce.content+=z,X.delete(ce.id),H.delete(ce.id),ce.rawContent=void 0,m(ce))}}).catch(()=>{E.content+=z,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,m(E)});else{let Ce=typeof We=="string"?We:(Ot=We==null?void 0:We.text)!=null?Ot:null;Ce!==null&&Ce.trim()!==""?(E.content=Ce,m(E)):!Ie&&!Ee.trim().startsWith("<")&&(E.content+=z,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,m(E))}}if(L.isComplete){let fe=(pn=(Le=L.result)==null?void 0:Le.response)!=null?pn:E.content;if(fe){let Ee=X.get(E.id),Xe=Ee!=null?Ee:Y(fe);E.rawContent=Xe;let Ie=H.get(E.id),_e=null,We=!1;if(Ie&&(_e=Ie.getExtractedText(),_e===null&&(_e=Nn(Xe)),_e===null)){let Ce=Ie.processChunk(Xe);Ce instanceof Promise?(We=!0,Ce.then(xe=>{var ce;let Ve=typeof xe=="string"?xe:(ce=xe==null?void 0:xe.text)!=null?ce:null;if(Ve!==null){let se=g;se&&se.id===E.id&&(se.content=Ve,se.streaming=!1,H.delete(se.id),X.delete(se.id),m(se))}})):_e=typeof Ce=="string"?Ce:(gn=Ce==null?void 0:Ce.text)!=null?gn:null}if(!We){_e!==null&&_e.trim()!==""?E.content=_e:X.has(E.id)||(E.content=Y(fe));let Ce=H.get(E.id);if(Ce){let xe=(Dt=Ce.close)==null?void 0:Dt.call(Ce);xe instanceof Promise&&xe.catch(()=>{}),H.delete(E.id)}X.delete(E.id),E.streaming=!1,m(E)}}}}else if(bt==="step_complete"){let oe=L.stepType,B=L.executionType;if(oe==="tool"||B==="context")continue;let E=(Ln=L.result)==null?void 0:Ln.response,z=O();if(E!=null){let fe=H.get(z.id),Ee=!1,Xe=!1;if(fe){let Ie=fe.getExtractedText(),_e=X.get(z.id),We=_e!=null?_e:Y(E);if(z.rawContent=We,Ie!==null&&Ie.trim()!=="")z.content=Ie,Ee=!0;else{let Ce=Nn(We);if(Ce!==null)z.content=Ce,Ee=!0;else{let xe=fe.processChunk(We);if(xe instanceof Promise)Xe=!0,xe.then(Ve=>{var se;let ce=typeof Ve=="string"?Ve:(se=Ve==null?void 0:Ve.text)!=null?se:null;if(ce!==null&&ce.trim()!==""){let de=g;de&&de.id===z.id&&(de.content=ce,de.streaming=!1,H.delete(de.id),X.delete(de.id),m(de))}else{let de=fe.getExtractedText(),mt=g;mt&&mt.id===z.id&&(de!==null&&de.trim()!==""?mt.content=de:X.has(mt.id)||(mt.content=Y(E)),mt.streaming=!1,H.delete(mt.id),X.delete(mt.id),m(mt))}});else{let Ve=typeof xe=="string"?xe:(kn=xe==null?void 0:xe.text)!=null?kn:null;if(Ve!==null&&Ve.trim()!=="")z.content=Ve,Ee=!0;else{let ce=fe.getExtractedText();ce!==null&&ce.trim()!==""&&(z.content=ce,Ee=!0)}}}}}if(!Xe){if(!z.rawContent){let Ie=X.get(z.id);z.rawContent=Ie!=null?Ie:Y(E)}if(!Ee&&!X.has(z.id)&&(z.content=Y(E)),fe){let Ie=(mn=fe.close)==null?void 0:mn.call(fe);Ie instanceof Promise&&Ie.catch(()=>{})}H.delete(z.id),X.delete(z.id),z.streaming=!1,m(z)}}else H.delete(z.id),X.delete(z.id),z.streaming=!1,m(z)}else if(bt==="flow_complete"){let oe=(Yt=L.result)==null?void 0:Yt.response;if(oe!=null){let B=O(),E=X.get(B.id),z=E!=null?E:Y(oe);B.rawContent=z;let fe=Y(oe),Ee=H.get(B.id);if(Ee){let _e=Nn(z);if(_e!==null)fe=_e;else{let We=Ee.processChunk(z);We instanceof Promise&&We.then(xe=>{var ce;let Ve=typeof xe=="string"?xe:(ce=xe==null?void 0:xe.text)!=null?ce:null;if(Ve!==null){let se=g;se&&se.id===B.id&&(se.content=Ve,se.streaming=!1,m(se))}});let Ce=Ee.getExtractedText();Ce!==null&&(fe=Ce)}}H.delete(B.id),X.delete(B.id);let Xe=fe!==B.content,Ie=B.streaming!==!1;Xe&&(B.content=fe),B.streaming=!1,(Xe||Ie)&&m(B)}else if(g!==null){let B=g;H.delete(B.id),X.delete(B.id),B.streaming!==!1&&(B.streaming=!1,m(B))}o({type:"status",status:"idle"})}else bt==="error"&&L.error&&o({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};function Fr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function qn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function zn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var nn=class{constructor(n={},o){this.config=n;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=n=>{var o,t;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Gt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var n,o;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(o=(n=this.callbacks).onError)==null||o.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,o){return this.client.submitMessageFeedback(n,o)}async submitCSATFeedback(n,o){return this.client.submitCSATFeedback(n,o)}async submitNPSFeedback(n,o){return this.client.submitNPSFeedback(n,o)}updateConfig(n){this.config={...this.config,...n},this.client=new Gt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}async sendMessage(n,o){var p,f,m,g,w;let t=n.trim();if(!t&&(!(o!=null&&o.contentParts)||o.contentParts.length===0))return;(p=this.abortController)==null||p.abort();let r=qn(),s=zn(),i={id:r,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1,...(o==null?void 0:o.contentParts)&&o.contentParts.length>0&&{contentParts:o.contentParts}};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:s},this.handleEvent)}catch(h){let R={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(R),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h instanceof Error?(m=(f=this.callbacks).onError)==null||m.call(f,h):(w=(g=this.callbacks).onError)==null||w.call(g,new Error(String(h)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(n.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(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let o=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let o=this.ensureSequence(n),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((o,t)=>{var d,p;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,a=(p=t.sequence)!=null?p:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var u=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var Ii=Ti(require("lucide"),1),re=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ii[r];return s?Ri(s,n,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 Ri(e,n,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(n)),r.setAttribute("height",String(n)),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(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([p,f])=>{p!=="stroke"&&d.setAttribute(p,String(f))}),r.appendChild(d)}}}),r}function $r(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Nr(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Or(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Dr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Un(e){return{type:"text",text:e}}function _r(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function jr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;n({type:"image",image:r,mimeType:e.type,alt:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function qr(e,n=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var zr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Fi=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Jt=[...zr,...Fi];function $i(e){return zr.includes(e)||e.startsWith("image/")}function Jn(e){return $i(e.type)}async function Ur(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Jn(e)?n({type:"image",image:r,mimeType:e.type,alt:e.name}):n({type:"file",data:r,mimeType:e.type,filename:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Jr(e,n=Jt,o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ni(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Yr(e,n){let o=Ni(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var Yn={allowedTypes:Jt,maxFileSize:10*1024*1024,maxFiles:4};function Oi(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Di(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Qt=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var o,t,r;this.config={allowedTypes:(o=n.allowedTypes)!=null?o:Yn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Yn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Yn.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Yn.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,r,s,i,a,d,p;if(!n||n.length===0)return;let o=Array.from(n);for(let f of o){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,f,"count");continue}let m=Jr(f,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let g=(s=m.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,g);continue}try{let g=await Ur(f),w=Jn(f)?URL.createObjectURL(f):null,h={id:Oi(),file:f,previewUrl:w,contentPart:g};this.attachments.push(h),this.renderPreview(h)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(p=(d=this.config).onAttachmentsChange)==null||p.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let o=this.attachments.findIndex(d=>d.id===n);if(o===-1)return;let t=this.attachments[o];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(o,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,o;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(o=(n=this.config).onAttachmentsChange)==null||o.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let o=Jn(n.file),t=u("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",o&&n.previewUrl){let i=u("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=u("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Di(n.file.type),d=re(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let p=u("span");p.textContent=Yr(n.file.type,n.file.name),p.style.fontSize="8px",p.style.fontWeight="600",p.style.color="var(--cw-muted, #6b7280)",p.style.textTransform="uppercase",p.style.lineHeight="1",i.appendChild(p),t.appendChild(i)}let r=u("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="rgba(0, 0, 0, 0.6)",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=re("x",10,"#ffffff",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="#ffffff",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(r),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,o){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:o})}};var gs=()=>{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"},_i=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",o=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:o;return n==="light"?o:n==="dark"||gs()==="dark"?t:o},Kr=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(gs())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(gs());o.addEventListener?(o.addEventListener("change",t),n.push(()=>o.removeEventListener("change",t))):o.addListener&&(o.addListener(t),n.push(()=>o.removeListener(t)))}return()=>{n.forEach(o=>o())}},Kn=(e,n)=>{let o=_i(n);Object.entries(o).forEach(([t,r])=>{if(r==null||r==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(r))})};var Xr=require("idiomorph"),Vr=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;Xr.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&t&&r.classList.contains("tvw-animate-typing"))return!1}}})};var gt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Lt={"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 An=(e,n)=>{let o=u("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,24 +12,24 @@
12
12
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,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",n);let t=s=>{var y,S,I,v,O,C,W,K,J,U,j,D;let i=(y=s.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=(I=i.subtitle)!=null?I:"Get answers fast");let p=o.querySelector(".tvw-flex-col");p&&(i.textHidden?p.style.display="none":p.style.display="");let f=o.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let Y=(v=i.agentIconSize)!=null?v:"40px";if(f.style.height=Y,f.style.width=Y,f.innerHTML="",i.agentIconName){let H=parseFloat(Y)||24,X=re(i.agentIconName,H*.6,"#ffffff",2);X?(f.appendChild(X),f.style.display=""):(f.textContent=(O=i.agentIconText)!=null?O:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(C=i.agentIconText)!=null?C:"\u{1F4AC}",f.style.display="")}let m=o.querySelector("[data-role='launcher-image']");if(m){let Y=(W=i.agentIconSize)!=null?W:"40px";m.style.height=Y,m.style.width=Y,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(m.src=i.iconUrl,m.style.display="block"):m.style.display="none"}let g=o.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let Y=(K=i.callToActionIconSize)!=null?K:"32px";g.style.height=Y,g.style.width=Y,i.callToActionIconBackgroundColor?(g.style.backgroundColor=i.callToActionIconBackgroundColor,g.classList.remove("tvw-bg-cw-primary")):(g.style.backgroundColor="",g.classList.add("tvw-bg-cw-primary"));let H=0;if(i.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=i.callToActionIconPadding,H=(parseFloat(i.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),i.callToActionIconHidden)g.style.display="none";else if(g.style.display="",g.innerHTML="",i.callToActionIconName){let X=parseFloat(Y)||24,Pe=Math.max(X-H,8),V=re(i.callToActionIconName,Pe,"currentColor",2);V?g.appendChild(V):g.textContent=(J=i.callToActionIconText)!=null?J:"\u2197"}else g.textContent=(U=i.callToActionIconText)!=null?U:"\u2197"}let w=i.position&&Lt[i.position]?Lt[i.position]:Lt["bottom-right"],h="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${h} ${w}`;let R="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=(j=i.border)!=null?j:R,o.style.boxShadow=(D=i.shadow)!=null?D:M},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var qt=e=>{var U,j,D,Y,H,X,Pe,V,_,tt,at,lt,kt,Ft,q,we,dt,ct,Ue,ut,$t,Pt,Ht,F,Oe,me,nt,he,st,Te,xt,St;let{config:n,showClose:o=!0}=e,t=u("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=(U=n==null?void 0:n.launcher)!=null?U:{},s=(j=r.headerIconSize)!=null?j:"48px",i=(D=r.closeButtonSize)!=null?D:"32px",a=(Y=r.closeButtonPlacement)!=null?Y:"inline",d=(H=r.headerIconHidden)!=null?H:!1,p=r.headerIconName,f=u("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=s,f.style.width=s,!d)if(p){let ae=parseFloat(s)||24,Je=re(p,ae*.6,"#ffffff",2);Je?f.replaceChildren(Je):f.textContent=(Pe=(X=n==null?void 0:n.launcher)==null?void 0:X.agentIconText)!=null?Pe:"\u{1F4AC}"}else if((V=n==null?void 0:n.launcher)!=null&&V.iconUrl){let ae=u("img");ae.src=n.launcher.iconUrl,ae.alt="",ae.className="tvw-rounded-xl tvw-object-cover",ae.style.height=s,ae.style.width=s,f.replaceChildren(ae)}else f.textContent=(tt=(_=n==null?void 0:n.launcher)==null?void 0:_.agentIconText)!=null?tt:"\u{1F4AC}";let m=u("div","tvw-flex tvw-flex-col"),g=u("span","tvw-text-base tvw-font-semibold");g.textContent=(lt=(at=n==null?void 0:n.launcher)==null?void 0:at.title)!=null?lt:"Chat Assistant";let w=u("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(Ft=(kt=n==null?void 0:n.launcher)==null?void 0:kt.subtitle)!=null?Ft:"Here to help you get answers fast",m.append(g,w),d?t.append(m):t.append(f,m);let h=(q=r.clearChat)!=null?q:{},R=(we=h.enabled)!=null?we:!0,M=(dt=h.placement)!=null?dt:"inline",y=null,S=null;if(R){let ae=(ct=h.size)!=null?ct:"32px",Je=(Ue=h.iconName)!=null?Ue:"refresh-cw",Qe=(ut=h.iconColor)!=null?ut:"",He=($t=h.backgroundColor)!=null?$t:"",Ye=(Pt=h.borderWidth)!=null?Pt:"",Wt=(Ht=h.borderColor)!=null?Ht:"",ft=(F=h.borderRadius)!=null?F:"",ot=(Oe=h.paddingX)!=null?Oe:"",$=(me=h.paddingY)!=null?me:"",wt=(nt=h.tooltipText)!=null?nt:"Clear chat",yt=(he=h.showTooltip)!=null?he:!0;S=u("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=u("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),y.style.height=ae,y.style.width=ae,y.type="button",y.setAttribute("aria-label",wt);let At=re(Je,"20px",Qe||"",2);if(At&&y.appendChild(At),Qe&&(y.style.color=Qe,y.classList.remove("tvw-text-cw-muted")),He&&(y.style.backgroundColor=He,y.classList.remove("hover:tvw-bg-gray-100")),Ye||Wt){let te=Ye||"0px",ye=Wt||"transparent";y.style.border=`${te} solid ${ye}`,y.classList.remove("tvw-border-none")}if(ft&&(y.style.borderRadius=ft,y.classList.remove("tvw-rounded-full")),ot?(y.style.paddingLeft=ot,y.style.paddingRight=ot):(y.style.paddingLeft="",y.style.paddingRight=""),$?(y.style.paddingTop=$,y.style.paddingBottom=$):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),yt&&wt&&y&&S){let te=null,ye=()=>{if(te||!y)return;te=u("div","tvw-clear-chat-tooltip"),te.textContent=wt;let vt=u("div");vt.className="tvw-clear-chat-tooltip-arrow",te.appendChild(vt);let Ze=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${Ze.left+Ze.width/2}px`,te.style.top=`${Ze.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Re=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};S.addEventListener("mouseenter",ye),S.addEventListener("mouseleave",Re),y.addEventListener("focus",ye),y.addEventListener("blur",Re),S._cleanupTooltip=()=>{Re(),S&&(S.removeEventListener("mouseenter",ye),S.removeEventListener("mouseleave",Re)),y&&(y.removeEventListener("focus",ye),y.removeEventListener("blur",Re))}}M==="inline"&&t.appendChild(S)}let I=u("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":R&&M==="inline"?"":"tvw-ml-auto"),v=u("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let O=(st=r.closeButtonTooltipText)!=null?st:"Close chat",C=(Te=r.closeButtonShowTooltip)!=null?Te:!0;v.setAttribute("aria-label",O),v.style.display=o?"":"none";let W=(xt=r.closeButtonIconName)!=null?xt:"x",K=(St=r.closeButtonIconText)!=null?St:"\xD7",J=re(W,"20px",r.closeButtonColor||"",2);if(J?v.appendChild(J):v.textContent=K,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 ae=r.closeButtonBorderWidth||"0px",Je=r.closeButtonBorderColor||"transparent";v.style.border=`${ae} solid ${Je}`,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=""),I.appendChild(v),C&&O){let ae=null,Je=()=>{if(ae)return;ae=u("div","tvw-clear-chat-tooltip"),ae.textContent=O;let He=u("div");He.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(He);let Ye=v.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Ye.left+Ye.width/2}px`,ae.style.top=`${Ye.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},Qe=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};I.addEventListener("mouseenter",Je),I.addEventListener("mouseleave",Qe),v.addEventListener("focus",Je),v.addEventListener("blur",Qe),I._cleanupTooltip=()=>{Qe(),I.removeEventListener("mouseenter",Je),I.removeEventListener("mouseleave",Qe),v.removeEventListener("focus",Je),v.removeEventListener("blur",Qe)}}return a!=="top-right"&&t.appendChild(I),{header:t,iconHolder:f,headerTitle:g,headerSubtitle:w,closeButton:v,closeButtonWrapper:I,clearChatButton:y,clearChatButtonWrapper:S}},Zt=(e,n,o)=>{var i,a,d,p;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(p=(d=t.clearChat)==null?void 0:d.placement)!=null?p:"inline";e.appendChild(n.header),r==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var ms=e=>qt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),hs=e=>{var h,R,M,y;let{config:n,showClose:o=!0,onClose:t}=e,r=(h=n==null?void 0:n.launcher)!=null?h:{},s=u("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=u("span","tvw-text-base tvw-font-semibold");i.textContent=(R=r.title)!=null?R:"Chat Assistant",s.appendChild(i);let a=(M=r.closeButtonSize)!=null?M:"32px",d=u("div",""),p=u("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");p.style.height=a,p.style.width=a,p.type="button",p.setAttribute("aria-label","Close chat"),p.style.display=o?"":"none";let f=(y=r.closeButtonIconName)!=null?y:"x",m=re(f,"20px",r.closeButtonColor||"",2);m?p.appendChild(m):p.textContent="\xD7",t&&p.addEventListener("click",t),d.appendChild(p),s.appendChild(d);let g=u("div");g.style.display="none";let w=u("span");return w.style.display="none",{header:s,iconHolder:g,headerTitle:i,headerSubtitle:w,closeButton:p,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},fs=e=>{var v,O,C,W,K,J,U,j;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(v=n==null?void 0:n.launcher)!=null?v:{},i=u("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=u("div","tvw-flex tvw-items-center tvw-gap-3"),d=(O=s.headerIconSize)!=null?O:"56px",p=u("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");p.style.height=d,p.style.width=d;let f=s.headerIconName;if(f){let D=parseFloat(d)||24,Y=re(f,D*.5,"#ffffff",2);Y?p.replaceChildren(Y):p.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let D=u("img");D.src=s.iconUrl,D.alt="",D.className="tvw-rounded-xl tvw-object-cover",D.style.height=d,D.style.width=d,p.replaceChildren(D)}else p.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}";let m=u("div","tvw-flex tvw-flex-col tvw-flex-1"),g=u("span","tvw-text-lg tvw-font-semibold");g.textContent=(K=s.title)!=null?K:"Chat Assistant";let w=u("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(J=s.subtitle)!=null?J:"Here to help you get answers fast",m.append(g,w),a.append(p,m);let h=(U=s.closeButtonSize)!=null?U:"32px",R=u("div",""),M=u("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");M.style.height=h,M.style.width=h,M.type="button",M.setAttribute("aria-label","Close chat"),M.style.display=o?"":"none";let y=(j=s.closeButtonIconName)!=null?j:"x",S=re(y,"20px",s.closeButtonColor||"",2);S?M.appendChild(S):M.textContent="\xD7",t&&M.addEventListener("click",t),R.appendChild(M),a.appendChild(R),i.appendChild(a);let I=u("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return I.textContent="Online and ready to help",i.appendChild(I),{header:i,iconHolder:p,headerTitle:g,headerSubtitle:w,closeButton:M,closeButtonWrapper:R,clearChatButton:null,clearChatButtonWrapper:null}},Xn={default:ms,minimal:hs,expanded:fs},ws=e=>{var n;return(n=Xn[e])!=null?n:Xn.default},sn=(e,n,o)=>{var i,a,d;if(n!=null&&n.render){let p=n.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=u("div");f.style.display="none";let m=u("span"),g=u("span"),w=u("button");w.style.display="none";let h=u("div");return h.style.display="none",{header:p,iconHolder:f,headerTitle:m,headerSubtitle:g,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=ws(t)({config:e,showClose:(d=(a=n==null?void 0:n.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 n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ji=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'}},on=e=>{var q,we,dt,ct,Ue,ut,$t,Pt,Ht,F,Oe,me,nt,he,st,Te,xt,St,ae,Je,Qe,He,Ye,Wt,ft,ot,$,wt,yt,At;let{config:n}=e,o=u("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=u("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=u("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");r.style.outline="none";let s=u("textarea");s.placeholder=(we=(q=n==null?void 0:n.copy)==null?void 0:q.inputPlaceholder)!=null?we:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",s.rows=1;let i=(ct=(dt=n==null?void 0:n.theme)==null?void 0:dt.inputFontFamily)!=null?ct:"sans-serif",a=(ut=(Ue=n==null?void 0:n.theme)==null?void 0:Ue.inputFontWeight)!=null?ut:"400";s.style.fontFamily=ji(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let m=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",m),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let g=($t=n==null?void 0:n.sendButton)!=null?$t:{},w=(Pt=g.useIcon)!=null?Pt:!1,h=(Ht=g.iconText)!=null?Ht:"\u2191",R=g.iconName,M=(F=g.tooltipText)!=null?F:"Send message",y=(Oe=g.showTooltip)!=null?Oe:!1,S=(me=g.size)!=null?me:"40px",I=g.backgroundColor,v=g.textColor,O=u("div","tvw-send-button-wrapper"),C=u("button",w?"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(C.type="submit",w){if(C.style.width=S,C.style.height=S,C.style.minWidth=S,C.style.minHeight=S,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",R){let te=parseFloat(S)||24,ye=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Re=re(R,te,ye,2);Re?(C.appendChild(Re),C.style.color=ye):(C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white"))}else C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white");I?C.style.backgroundColor=I:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(he=(nt=n==null?void 0:n.copy)==null?void 0:nt.sendButtonLabel)!=null?he:"Send",v?C.style.color=v:C.classList.add("tvw-text-white");if(g.borderWidth&&(C.style.borderWidth=g.borderWidth,C.style.borderStyle="solid"),g.borderColor&&(C.style.borderColor=g.borderColor),g.paddingX?(C.style.paddingLeft=g.paddingX,C.style.paddingRight=g.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),g.paddingY?(C.style.paddingTop=g.paddingY,C.style.paddingBottom=g.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),y&&M){let te=u("div","tvw-send-button-tooltip");te.textContent=M,O.appendChild(te)}O.appendChild(C);let W=(st=n==null?void 0:n.voiceRecognition)!=null?st:{},K=W.enabled===!0,J=null,U=null,j=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(K&&j){U=u("div","tvw-send-button-wrapper"),J=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),J.type="button",J.setAttribute("aria-label","Start voice recognition");let te=(Te=W.iconName)!=null?Te:"mic",ye=(xt=W.iconSize)!=null?xt:S,Re=parseFloat(ye)||24,vt=(St=W.backgroundColor)!=null?St:I,Ze=(ae=W.iconColor)!=null?ae:v;J.style.width=ye,J.style.height=ye,J.style.minWidth=ye,J.style.minHeight=ye,J.style.fontSize="18px",J.style.lineHeight="1";let Bt=Ze||"currentColor",It=re(te,Re,Bt,1.5);It?(J.appendChild(It),J.style.color=Bt):(J.textContent="\u{1F3A4}",J.style.color=Bt),vt?J.style.backgroundColor=vt:J.classList.add("tvw-bg-cw-primary"),Ze?J.style.color=Ze:!Ze&&!v&&J.classList.add("tvw-text-white"),W.borderWidth&&(J.style.borderWidth=W.borderWidth,J.style.borderStyle="solid"),W.borderColor&&(J.style.borderColor=W.borderColor),W.paddingX&&(J.style.paddingLeft=W.paddingX,J.style.paddingRight=W.paddingX),W.paddingY&&(J.style.paddingTop=W.paddingY,J.style.paddingBottom=W.paddingY),U.appendChild(J);let Nt=(Je=W.tooltipText)!=null?Je:"Start voice recognition";if(((Qe=W.showTooltip)!=null?Qe:!1)&&Nt){let Ot=u("div","tvw-send-button-tooltip");Ot.textContent=Nt,U.appendChild(Ot)}}let D=(He=n==null?void 0:n.attachments)!=null?He:{},Y=D.enabled===!0,H=null,X=null,Pe=null,V=null;if(Y){V=u("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),V.style.display="none",Pe=u("input"),Pe.type="file",Pe.accept=((Ye=D.allowedTypes)!=null?Ye:Jt).join(","),Pe.multiple=((Wt=D.maxFiles)!=null?Wt:4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),X=u("div","tvw-send-button-wrapper"),H=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),H.type="button",H.setAttribute("aria-label",(ft=D.buttonTooltipText)!=null?ft:"Attach file");let te=(ot=D.buttonIconName)!=null?ot:"paperclip",ye=S,Re=parseFloat(ye)||40,vt=Math.round(Re*.6);H.style.width=ye,H.style.height=ye,H.style.minWidth=ye,H.style.minHeight=ye,H.style.fontSize="18px",H.style.lineHeight="1",H.style.backgroundColor="transparent",H.style.color="var(--cw-primary, #111827)",H.style.border="none",H.style.borderRadius="6px",H.style.transition="background-color 0.15s ease",H.addEventListener("mouseenter",()=>{H.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),H.addEventListener("mouseleave",()=>{H.style.backgroundColor="transparent"});let Ze=re(te,vt,"currentColor",1.5);Ze?H.appendChild(Ze):H.textContent="\u{1F4CE}",H.addEventListener("click",Nt=>{Nt.preventDefault(),Pe==null||Pe.click()}),X.appendChild(H);let Bt=($=D.buttonTooltipText)!=null?$:"Attach file",It=u("div","tvw-send-button-tooltip");It.textContent=Bt,X.appendChild(It)}r.addEventListener("click",te=>{te.target!==C&&te.target!==O&&te.target!==J&&te.target!==U&&te.target!==H&&te.target!==X&&s.focus()}),V&&(V.style.gap="8px",r.append(V)),Pe&&r.append(Pe),r.append(s);let _=u("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),tt=u("div","tvw-flex tvw-items-center tvw-gap-2");X&&tt.append(X);let at=u("div","tvw-flex tvw-items-center tvw-gap-1");U&&at.append(U),at.append(O),_.append(tt,at),r.append(_);let lt=u("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),kt=(wt=n==null?void 0:n.statusIndicator)!=null?wt:{},Ft=(yt=kt.visible)!=null?yt:!0;return lt.style.display=Ft?"":"none",lt.textContent=(At=kt.idleText)!=null?At:"Online",o.append(t,r,lt),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:O,micButton:J,micButtonWrapper:U,statusText:lt,attachmentButton:H,attachmentButtonWrapper:X,attachmentInput:Pe,attachmentPreviewsContainer:V,actionsRow:_,leftActions:tt,rightActions:at}};var Gr=e=>{var d,p,f,m,g,w,h;if(!((p=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?p:!0)){let R=u("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),M=u("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?m:"100%";return R.style.width=y,M.style.width="100%",R.appendChild(M),{wrapper:R,panel:M}}let o=(g=e==null?void 0:e.launcher)!=null?g:{},t=o.position&&Lt[o.position]?Lt[o.position]:Lt["bottom-right"],r=u("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=u("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(h=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?h:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,r.appendChild(s),{wrapper:r,panel:s}},Qr=(e,n=!0)=>{var w,h,R,M,y,S,I;let o=u("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=e==null?void 0:e.layout)==null?void 0:w.header,r=((h=e==null?void 0:e.layout)==null?void 0:h.showHeader)!==!1,s=t?sn(e,t,{showClose:n}):qt({config:e,showClose:n}),i=u("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=u("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=u("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(M=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?M:"Hello \u{1F44B}";let p=u("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");p.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,p);let f=u("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let m=on({config:e}),g=((I=e==null?void 0:e.layout)==null?void 0:I.showFooter)!==!1;return r?Zt(o,s,e):(s.header.style.display="none",Zt(o,s,e)),o.append(i),g||(m.footer.style.display="none"),o.append(m.footer),{container:o,body:i,messagesWrapper:f,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions}};var Tn=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let 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(n),e.appendChild(o),e.appendChild(t),e.appendChild(r),e},qi=(e,n)=>{let o=u("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=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=u("img");r.src=t,r.alt=n==="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(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=n==="user"?"U":"A",o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},Zr=(e,n)=>{let o=u("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?o.textContent=n.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},zi=(e,n="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){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},ys=(e,n,o)=>{var h,R,M,y,S,I;let t=(h=n.showCopy)!=null?h:!0,r=(R=n.showUpvote)!=null?R:!0,s=(M=n.showDownvote)!=null?M:!0,i=(y=n.visibility)!=null?y:"hover",a=(S=n.align)!=null?S:"right",d=(I=n.layout)!=null?I:"pill-inside",p={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],m=u("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${p} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let g=null,w=(v,O,C,W)=>{let K=document.createElement("button");K.className="tvw-message-action-btn",K.setAttribute("aria-label",O),K.setAttribute("title",O),W&&K.setAttribute("data-action",W);let J=re(v,14,"currentColor",2);return J&&K.appendChild(J),K.addEventListener("click",U=>{U.preventDefault(),U.stopPropagation(),C()}),K};if(t){let v=w("copy","Copy message",()=>{let O=e.content||"";navigator.clipboard.writeText(O).then(()=>{v.classList.add("tvw-message-action-success");let C=re("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let W=re("copy",14,"currentColor",2);W&&(v.innerHTML="",v.appendChild(W))},2e3)}).catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",C)}),o!=null&&o.onCopy&&o.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");m.appendChild(v)}if(r){let v=w("thumbs-up","Upvote",()=>{if(g==="upvote")g=null,v.classList.remove("tvw-message-action-active");else{let C=m.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),g="upvote",v.classList.add("tvw-message-action-active");let W={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(W),n.onFeedback&&n.onFeedback(W)}},"upvote");m.appendChild(v)}if(s){let v=w("thumbs-down","Downvote",()=>{if(g==="downvote")g=null,v.classList.remove("tvw-message-action-active");else{let C=m.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),g="downvote",v.classList.add("tvw-message-action-active");let W={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(W),n.onFeedback&&n.onFeedback(W)}},"downvote");m.appendChild(v)}return m},rn=(e,n,o,t,r)=>{var I,v,O,C,W;let s=o!=null?o:{},i=(I=s.layout)!=null?I:"bubble",a=s.avatar,d=s.timestamp,p=(v=a==null?void 0:a.show)!=null?v:!1,f=(O=d==null?void 0:d.show)!=null?O:!1,m=(C=a==null?void 0:a.position)!=null?C:"left",g=(W=d==null?void 0:d.position)!=null?W:"below",w=zi(e.role,i),h=u("div",w.join(" "));h.id=`bubble-${e.id}`,h.setAttribute("data-message-id",e.id);let R=document.createElement("div");if(R.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),f&&g==="inline"&&e.createdAt){let K=Zr(e,d);K.classList.add("tvw-ml-2","tvw-inline"),R.appendChild(K)}if(h.appendChild(R),f&&g==="below"&&e.createdAt){let K=Zr(e,d);K.classList.add("tvw-mt-1"),h.appendChild(K)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let K=Tn();h.appendChild(K)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let K=ys(e,t,r);h.appendChild(K)}if(!p||e.role==="system")return h;let y=u("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),S=qi(a,e.role);return m==="right"||m==="left"&&e.role==="user"?y.append(h,S):y.append(S,h),h.classList.remove("tvw-max-w-[85%]"),h.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},ei=(e,n,o,t,r)=>{let s=o!=null?o:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):rn(e,n,o,t,r)};var an=new Set,ti=(e,n)=>{let o=an.has(e),t=n.querySelector('button[data-expand-header="true"]'),r=n.querySelector(".tvw-border-t");if(!t||!r)return;t.setAttribute("aria-expanded",o?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=re(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},vs=e=>{let n=e.reasoning,o=u("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let t=an.has(e.id),r=u("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("data-expand-header","true"),r.setAttribute("data-bubble-type","reasoning");let s=u("div","tvw-flex tvw-flex-col tvw-text-left"),i=u("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=u("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Hr(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=u("div","tvw-flex tvw-items-center"),f=re(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let m=u("div","tvw-flex tvw-items-center tvw-ml-auto");m.append(d),r.append(s,m);let g=u("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");g.style.display=t?"":"none";let w=n.chunks.join(""),h=u("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return h.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),g.appendChild(h),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=re(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",g.style.display=t?"":"none"})(),o.append(r,g),o};var ln=new Set,ni=(e,n,o)=>{var p;let t=ln.has(e),r=(p=o==null?void 0:o.toolCall)!=null?p:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",t?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let f=r.toggleTextColor||r.headerTextColor||"currentColor",m=re(t?"chevron-up":"chevron-down",16,f,2);m?d.appendChild(m):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},bs=(e,n)=>{var R;let o=e.toolCall,t=(R=n==null?void 0:n.toolCall)!=null?R:{},r=u("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(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 s=ln.has(e.id),i=u("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"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=u("div","tvw-flex tvw-flex-col tvw-text-left"),d=u("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Br(o),a.appendChild(d);let p=u("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",m=re(s?"chevron-up":"chevron-down",16,f,2);m?p.appendChild(m):p.textContent=s?"Hide":"Show";let g=u("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");g.append(p),i.append(a,g);let w=u("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",t.contentBackgroundColor&&(w.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(w.style.color=t.contentTextColor),t.contentPaddingX&&(w.style.paddingLeft=t.contentPaddingX,w.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(w.style.paddingTop=t.contentPaddingY,w.style.paddingBottom=t.contentPaddingY),o.name){let M=u("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,w.appendChild(M)}if(o.args!==void 0){let M=u("div","tvw-space-y-1"),y=u("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let S=u("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");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=ps(o.args),M.append(y,S),w.appendChild(M)}if(o.chunks&&o.chunks.length){let M=u("div","tvw-space-y-1"),y=u("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let S=u("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");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),w.appendChild(M)}if(o.status==="complete"&&o.result!==void 0){let M=u("div","tvw-space-y-1"),y=u("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let S=u("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");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=ps(o.result),M.append(y,S),w.appendChild(M)}if(o.status==="complete"&&typeof o.duration=="number"){let M=u("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(M.style.color=t.contentTextColor),M.textContent=`Duration: ${o.duration}ms`,w.appendChild(M)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),p.innerHTML="";let M=t.toggleTextColor||t.headerTextColor||"currentColor",y=re(s?"chevron-up":"chevron-down",16,M,2);y?p.appendChild(y):p.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var si=e=>{let n=[];return{buttons:n,render:(t,r,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(w=>w.role==="user"))return;let f=document.createDocumentFragment(),m=r?r.isStreaming():!1,g=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(w=>{let h=u("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");h.type="button",h.textContent=w,h.disabled=m,a!=null&&a.fontFamily&&(h.style.fontFamily=g(a.fontFamily)),a!=null&&a.fontWeight&&(h.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(h.style.paddingLeft=a.paddingX,h.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(h.style.paddingTop=a.paddingY,h.style.paddingBottom=a.paddingY),h.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(w))}),f.appendChild(h),n.push(h)}),e.appendChild(f)}}};var oi={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"}},Cs=(e,n,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var h,R,M;if(s.dataset.enhanced==="true")return;let i=(h=s.dataset.tvForm)!=null?h:"init";s.dataset.enhanced="true";let a=(R=oi[i])!=null?R:oi.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=u("div","tvw-space-y-1"),p=u("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(p.textContent=a.title,d.appendChild(p),a.description){let y=u("p","tvw-text-sm tvw-text-cw-muted");y.textContent=a.description,d.appendChild(y)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(y=>{var C,W;let S=u("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${n.id}-${i}-${y.name}`;let I=u("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=y.label,S.appendChild(I);let v=(C=y.type)!=null?C:"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=`${n.id}-${i}-${y.name}`,O.name=y.name,O.placeholder=(W=y.placeholder)!=null?W:"",y.required&&(O.required=!0),S.appendChild(O),f.appendChild(S)});let m=u("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),g=u("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=u("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(M=a.submitLabel)!=null?M:"Submit",m.appendChild(g),m.appendChild(w),f.appendChild(m),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var O,C;y.preventDefault();let S=(O=o.formEndpoint)!=null?O:"/form",I=new FormData(f),v={};I.forEach((W,K)=>{v[K]=W}),v.type=i,w.disabled=!0,g.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 K=await W.json();g.textContent=(C=K.message)!=null?C:"Thanks! We'll be in touch soon.",K.success&&K.nextPrompt&&await t.sendMessage(String(K.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var xs=class{constructor(){this.plugins=new Map}register(n){var o;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(o=n.onRegister)==null||o.call(n)}unregister(n){var t;let o=this.plugins.get(n);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=n.priority)!=null?r:0)})}getForInstance(n){let o=this.getAll();if(!n||n.length===0)return o;let t=new Set(n.map(s=>s.id));return[...o.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var o;return(o=n.onUnregister)==null?void 0:o.call(n)}),this.plugins.clear()}},En=new xs;var Ss={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"},As={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"},Be={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ss,darkTheme:As,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Vn(e){var n,o,t,r,s,i,a,d,p,f,m,g,w,h,R,M,y,S,I;return e?{...Be,...e,theme:{...Be.theme,...e.theme},darkTheme:{...Be.darkTheme,...e.darkTheme},launcher:{...Be.launcher,...e.launcher,clearChat:{...(n=Be.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Be.copy,...e.copy},sendButton:{...Be.sendButton,...e.sendButton},statusIndicator:{...Be.statusIndicator,...e.statusIndicator},voiceRecognition:{...Be.voiceRecognition,...e.voiceRecognition},features:{...Be.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Be.suggestionChips,suggestionChipsConfig:{...Be.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Be.layout,...e.layout,header:{...(r=Be.layout)==null?void 0:r.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Be.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(p=(d=Be.layout)==null?void 0:d.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(w=(g=Be.layout)==null?void 0:g.messages)==null?void 0:w.timestamp,...(R=(h=e.layout)==null?void 0:h.messages)==null?void 0:R.timestamp}},slots:{...(M=Be.layout)==null?void 0:M.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Be.markdown,...e.markdown,options:{...(S=Be.markdown)==null?void 0:S.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var ri=()=>{let e=new Map,n=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=e.get(r))==null||i.delete(s)};return{on:n,off:o,emit:(r,s)=>{var i;(i=e.get(r))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ui=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Ji=e=>{let n=e.trim(),o=n.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<n.length;r+=1){let s=n[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(o,r+1)}return null},Mn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Ui(e),o=Ji(n);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Ts=e=>typeof e=="string"?e:e==null?"":String(e),en={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ts(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Ts(o.element);if(t&&((r=n.document)!=null&&r.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Ts(o.text)}}},ii=e=>Array.isArray(e)?e.map(n=>String(n)):[],Wn=e=>{let n=new Set(ii(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(ii(e.getSessionMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(n);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?e.parsers.reduce((p,f)=>p||(f==null?void 0:f({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),t();let d={action:a,message:s.message};e.emit("action:detected",d);for(let p of e.handlers)if(p)try{let f=p(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef});if(!f)continue;if(f.handled){let m=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:m}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var Yi=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Ki=e=>e.map(n=>({...n,streaming:!1})),Gn=(e="vanilla-agent-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?Yi(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?Ki(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=n();if(o)try{o.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Es=class{constructor(){this.components=new Map}register(n,o){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,o)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([o,t])=>{this.register(o,t)})}},dn=new Es;var cn=require("partial-json");function Xi(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Vi(e,n){if(!Xi(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:n}}function Qn(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e;try{let r=(0,cn.parse)(o,cn.STR|cn.OBJ),s=Vi(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function ai(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Zn(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=dn.get(e.component);if(!s)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 s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function li(){let e=Qn();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function es(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ts(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var Gi=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ns(e){let{onSubmit:n,onDismiss:o,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:p=Gi}=e,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let h=document.createElement("h3");h.className="tvw-feedback-title",h.textContent=t,w.appendChild(h);let R=document.createElement("p");R.className="tvw-feedback-subtitle",R.textContent=r,w.appendChild(R),g.appendChild(w);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 C=1;C<=5;C++){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",`${C} star${C>1?"s":""}: ${p[C-1]}`),W.title=p[C-1],W.dataset.rating=String(C),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",()=>{m=C,y.forEach((K,J)=>{let U=J<C;K.classList.toggle("selected",U),K.setAttribute("aria-checked",J===C-1?"true":"false")})}),y.push(W),M.appendChild(W)}g.appendChild(M);let S=null;if(d){let C=document.createElement("div");C.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),C.appendChild(S),g.appendChild(C)}let I=document.createElement("div");I.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(),f.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(m===null){M.classList.add("tvw-feedback-shake"),setTimeout(()=>M.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let C=(S==null?void 0:S.value.trim())||void 0;await n(m,C),f.remove()}catch(C){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(v),I.appendChild(O),g.appendChild(I),f.appendChild(g),f}function ss(e){let{onSubmit:n,onDismiss:o,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:f="Very likely"}=e,m=document.createElement("div");m.className="tvw-feedback-container tvw-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,w=document.createElement("div");w.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let R=document.createElement("h3");R.className="tvw-feedback-title",R.textContent=t,h.appendChild(R);let M=document.createElement("p");M.className="tvw-feedback-subtitle",M.textContent=r,h.appendChild(M),w.appendChild(h);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 I=document.createElement("span");I.className="tvw-feedback-label-low",I.textContent=p;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,S.appendChild(I),S.appendChild(v);let O=document.createElement("div");O.className="tvw-feedback-numbers";let C=[];for(let j=0;j<=10;j++){let D=document.createElement("button");D.type="button",D.className="tvw-feedback-rating-btn tvw-feedback-number-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`Rating ${j} out of 10`),D.textContent=String(j),D.dataset.rating=String(j),j<=6?D.classList.add("tvw-feedback-detractor"):j<=8?D.classList.add("tvw-feedback-passive"):D.classList.add("tvw-feedback-promoter"),D.addEventListener("click",()=>{g=j,C.forEach((Y,H)=>{Y.classList.toggle("selected",H===j),Y.setAttribute("aria-checked",H===j?"true":"false")})}),C.push(D),O.appendChild(D)}y.appendChild(S),y.appendChild(O),w.appendChild(y);let W=null;if(d){let j=document.createElement("div");j.className="tvw-feedback-comment-container",W=document.createElement("textarea"),W.className="tvw-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),w.appendChild(j)}let K=document.createElement("div");K.className="tvw-feedback-actions";let J=document.createElement("button");J.type="button",J.className="tvw-feedback-btn tvw-feedback-btn-skip",J.textContent=a,J.addEventListener("click",()=>{o==null||o(),m.remove()});let U=document.createElement("button");return U.type="button",U.className="tvw-feedback-btn tvw-feedback-btn-submit",U.textContent=i,U.addEventListener("click",async()=>{if(g===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}U.disabled=!0,U.textContent="Submitting...";try{let j=(W==null?void 0:W.value.trim())||void 0;await n(g,j),m.remove()}catch(j){U.disabled=!1,U.textContent=i,console.error("[NPS Feedback] Failed to submit:",j)}}),K.appendChild(J),K.appendChild(U),w.appendChild(K),m.appendChild(w),m}var un="vanilla-agent-chat-history",Qi=30*1e3,Ms=e=>!e||typeof e!="object"?{}:{...e},di=e=>e.map(n=>({...n,streaming:!1})),ci=(e,n)=>{let o=e!=null&&e.markdown?Sn(e.markdown):null;return t=>{var i,a,d;let r=(i=t.text)!=null?i:"",s=(a=t.message.rawContent)!=null?a:null;if(n){let p=n.process({text:r,raw:s!=null?s:r,message:t.message,streaming:t.streaming});p!==null&&(r=p.text,p.persist||(t.message.__skipPersist=!0))}return e!=null&&e.postprocessMessage?e.postprocessMessage({...t,text:r,raw:(d=s!=null?s:t.text)!=null?d:""}):o?o(r):Fn(r)}},os=(e,n,o)=>{var Bs,Is,Rs,Fs,$s,Ns,Os,Ds,_s,js,qs,zs,Us,Js,Ys,Ks,Xs;(!e.id||e.id!=="vanilla-agent-root")&&(e.id="vanilla-agent-root");let t=Vn(n),r=En.getForInstance(t.plugins);t.components&&dn.registerAll(t.components);let s=ri(),i=(Bs=t.storageAdapter)!=null?Bs:Gn(),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 c=l;c.metadata&&(a=Ms(c.metadata)),(Is=c.messages)!=null&&Is.length&&(t={...t,initialMessages:c.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let p=()=>a,f=l=>{var A;a=(A=l({...a}))!=null?A:{},mn()},m=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Mn],g=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick],w=Wn({parsers:m,handlers:g,getSessionMetadata:p,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Fs=(Rs=t.launcher)==null?void 0:Rs.enabled)!=null?Fs:!0,R=(Ns=($s=t.launcher)==null?void 0:$s.autoExpand)!=null?Ns:!1,M=R,y=h,S=(Ds=(Os=t.layout)==null?void 0:Os.header)==null?void 0:Ds.layout,I=h?R:!0,v=ci(t,w),O=(js=(_s=t.features)==null?void 0:_s.showReasoning)!=null?js:!0,C=(zs=(qs=t.features)==null?void 0:qs.showToolCalls)!=null?zs:!0,W={onCopy:l=>{var c,A;s.emit("message:copy",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",P)}),(A=(c=t.messageActions)==null?void 0:c.onCopy)==null||A.call(c,l)},onFeedback:l=>{var c,A;s.emit("message:feedback",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",P)}),(A=(c=t.messageActions)==null?void 0:c.onFeedback)==null||A.call(c,l)}},K=(Us=t.statusIndicator)!=null?Us:{},J=l=>{var c,A,P,b;return l==="idle"?(c=K.idleText)!=null?c:gt.idle:l==="connecting"?(A=K.connectingText)!=null?A:gt.connecting:l==="connected"?(P=K.connectedText)!=null?P:gt.connected:l==="error"?(b=K.errorText)!=null?b:gt.error:gt[l]},{wrapper:U,panel:j}=Gr(t),D=Qr(t,h),{container:Y,body:H,messagesWrapper:X,suggestions:Pe,textarea:V,sendButton:_,sendButtonWrapper:tt,composerForm:at,statusText:lt,introTitle:kt,introSubtitle:Ft,closeButton:q,iconHolder:we,headerTitle:dt,headerSubtitle:ct,header:Ue,footer:ut,actionsRow:$t,leftActions:Pt,rightActions:Ht}=D,F=D.micButton,Oe=D.micButtonWrapper,me=D.attachmentButton,nt=D.attachmentButtonWrapper,he=D.attachmentInput,st=D.attachmentPreviewsContainer,Te=null;(Js=t.attachments)!=null&&Js.enabled&&he&&st&&(Te=Qt.fromConfig(t.attachments),Te.setPreviewsContainer(st),he.addEventListener("change",l=>{let c=l.target;Te==null||Te.handleFileSelect(c.files),c.value=""}));let xt=r.find(l=>l.renderHeader);if(xt!=null&&xt.renderHeader){let l=xt.renderHeader({config:t,defaultRenderer:()=>{let c=qt({config:t,showClose:h});return Zt(Y,c,t),c.header},onClose:()=>L(!1,"user")});if(l){let c=Y.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),Ue=l)}}let St=r.find(l=>l.renderComposer);if(St!=null&&St.renderComposer){let l=St.renderComposer({config:t,defaultRenderer:()=>on({config:t}).footer,onSubmit:c=>{$&&!$.isStreaming()&&$.sendMessage(c)},disabled:!1});l&&(ut.replaceWith(l),ut=l)}(()=>{var P,b;let l=(b=(P=t.layout)==null?void 0:P.slots)!=null?b:{},c=Q=>{switch(Q){case"body-top":return Y.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return X;case"footer-top":return Pe;case"composer":return at;case"footer-bottom":return lt;default:return null}},A=(Q,ue)=>{var T;switch(Q){case"header-left":case"header-center":case"header-right":if(Q==="header-left")Ue.insertBefore(ue,Ue.firstChild);else if(Q==="header-right")Ue.appendChild(ue);else{let G=Ue.querySelector(".tvw-flex-col");G?(T=G.parentNode)==null||T.insertBefore(ue,G.nextSibling):Ue.appendChild(ue)}break;case"body-top":let ee=H.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ee?ee.replaceWith(ue):H.insertBefore(ue,H.firstChild);break;case"body-bottom":H.appendChild(ue);break;case"footer-top":Pe.replaceWith(ue);break;case"footer-bottom":lt.replaceWith(ue);break;default:break}};for(let[Q,ue]of Object.entries(l))if(ue)try{let T=ue({config:t,defaultContent:()=>c(Q)});T&&A(Q,T)}catch(T){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${Q}":`,T)}})();let Je=l=>{let A=l.target.closest('button[data-expand-header="true"]');if(!A)return;let P=A.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!P)return;let b=P.getAttribute("data-message-id");if(!b)return;let Q=A.getAttribute("data-bubble-type");Q==="reasoning"?(an.has(b)?an.delete(b):an.add(b),ti(b,P)):Q==="tool"&&(ln.has(b)?ln.delete(b):ln.add(b),ni(b,P,t))};X.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),X.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),j.appendChild(Y),e.appendChild(U);let Qe=()=>{var pe,je,qe,rt,Tt,Z,Me,Kt,Xt,Pn,Hn,cs,ze,Bn,hn,fn;let l=(je=(pe=t.launcher)==null?void 0:pe.sidebarMode)!=null?je:!1,c=l||((rt=(qe=t.launcher)==null?void 0:qe.fullHeight)!=null?rt:!1),A=(Tt=t.theme)!=null?Tt:{},P=(Me=(Z=t.launcher)==null?void 0:Z.position)!=null?Me:"bottom-left",b=P==="bottom-left"||P==="top-left",Q=l?"none":"1px solid var(--tvw-cw-border)",ue=l?b?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",T=l?"0":"16px",ee=(Kt=A.panelBorder)!=null?Kt:Q,G=(Xt=A.panelShadow)!=null?Xt:ue,ve=(Pn=A.panelBorderRadius)!=null?Pn:T;e.style.cssText="",U.style.cssText="",j.style.cssText="",Y.style.cssText="",H.style.cssText="",ut.style.cssText="";let N=(cs=(Hn=t==null?void 0:t.launcher)==null?void 0:Hn.width)!=null?cs:t==null?void 0:t.launcherWidth,Fe=N!=null?N:"min(400px, calc(100vw - 24px))";l||(j.style.width=Fe,j.style.maxWidth=Fe),j.style.boxShadow=G,j.style.borderRadius=ve,Y.style.border=ee,Y.style.borderRadius=ve;let Ae=((ze=t.launcher)==null?void 0:ze.enabled)===!1;if(c&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",U.style.display="flex",U.style.flexDirection="column",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.maxHeight="100%",U.style.height="100%",Ae&&(U.style.overflow="hidden"),j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.height="100%",j.style.overflow="hidden",Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.overflow="hidden",H.style.flex="1 1 0%",H.style.minHeight="0",H.style.overflowY="auto",ut.style.flexShrink="0"),U.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&&!Ae&&((Bn=Lt[P])!=null?Bn:Lt["bottom-right"]).split(" ").forEach(wn=>U.classList.add(wn)),l){let Ut=(fn=(hn=t.launcher)==null?void 0:hn.sidebarWidth)!=null?fn:"420px";U.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
24
- width: ${Nt} !important;
24
+ width: ${Ut} !important;
25
25
  height: 100vh !important;
26
26
  max-height: 100vh !important;
27
27
  margin: 0 !important;
28
28
  padding: 0 !important;
29
29
  display: flex !important;
30
30
  flex-direction: column !important;
31
- ${C?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
- `,O.style.cssText=`
31
+ ${b?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
+ `,j.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
35
35
  flex-direction: column !important;
@@ -40,9 +40,9 @@
40
40
  min-height: 0 !important;
41
41
  margin: 0 !important;
42
42
  padding: 0 !important;
43
- box-shadow: ${X} !important;
44
- border-radius: ${me} !important;
45
- `,O.style.setProperty("width","100%","important"),O.style.setProperty("max-width","100%","important"),U.style.cssText=`
43
+ box-shadow: ${G} !important;
44
+ border-radius: ${ve} !important;
45
+ `,j.style.setProperty("width","100%","important"),j.style.setProperty("max-width","100%","important"),Y.style.cssText=`
46
46
  display: flex !important;
47
47
  flex-direction: column !important;
48
48
  flex: 1 1 0% !important;
@@ -51,18 +51,90 @@
51
51
  min-height: 0 !important;
52
52
  max-height: 100% !important;
53
53
  overflow: hidden !important;
54
- border-radius: ${me} !important;
54
+ border-radius: ${ve} !important;
55
55
  border: ${ee} !important;
56
- `,Ze.style.cssText=`
56
+ `,ut.style.cssText=`
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(!Ae){let Ut="max-height: -moz-available !important; max-height: stretch !important;",wn=l?"":"padding-top: 1.25em !important;";U.style.cssText+=Ut+wn}};Qe(),Kn(e,t);let He=[],Ye=null,Wt=()=>{Ye&&(Ye(),Ye=null),t.colorScheme==="auto"&&(Ye=Kr(()=>{Kn(e,t)}))};Wt(),He.push(()=>{Ye&&(Ye(),Ye=null)});let ft=si(Pe),ot=null,$,wt=!1,yt=!0,At=0,te=0,ye=null,Re=!1,vt=0,Ze=!1,Bt=125,It=2e3,Nt=5,tn=50,Ot=new Map,Le={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},pn=(Ks=(Ys=t.voiceRecognition)==null?void 0:Ys.autoResume)!=null?Ks:!1,gn=l=>{s.emit("voice:state",{active:Le.active,source:l,timestamp:Date.now()})},Dt=()=>{f(l=>({...l,voiceState:{active:Le.active,timestamp:Date.now(),manuallyDeactivated:Le.manuallyDeactivated}}))},Ln=()=>{var P,b;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let l=Ms(a.voiceState),c=!!l.active,A=Number((b=l.timestamp)!=null?b:0);Le.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-A<Qi&&setTimeout(()=>{Le.active||(Le.manuallyDeactivated=!1,_e("restore"))},1e3)},kn=()=>$?di($.getMessages()).filter(l=>!l.__skipPersist):[];function mn(l){if(!(i!=null&&i.save))return;let A={messages:l?di(l):$?kn():[],metadata:a};try{let P=i.save(A);P instanceof Promise&&P.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)})}catch(P){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)}}let Yt=(l=!1)=>{if(!yt)return;let c=Date.now();Re&&c<vt&&!l||(Re&&c>=vt&&(Re=!1),!(!l&&!wt)&&(c-te<Bt||(te=c,ye&&cancelAnimationFrame(ye),ye=requestAnimationFrame(()=>{Re||!yt||(Ze=!0,H.scrollTop=H.scrollHeight,At=H.scrollTop,requestAnimationFrame(()=>{Ze=!1}),ye=null)}))))},k=null,le=()=>U.querySelector("#vanilla-agent-scroll-container")||H,Se=(l,c=500)=>{let A=l.scrollTop,P=l.clientHeight,b=l.scrollHeight,Q=b-A;if(A+P>=b-2||Math.abs(Q)<5)return;k!==null&&(cancelAnimationFrame(k),k=null);let T=performance.now(),ee=ve=>1-Math.pow(1-ve,3),G=ve=>{let N=l.scrollHeight;N!==b&&(b=N,Q=b-A);let Fe=ve-T,Ae=Math.min(Fe/c,1),pe=ee(Ae),je=A+Q*pe;l.scrollTop=je,Ae<1?k=requestAnimationFrame(G):(l.scrollTop=l.scrollHeight,k=null)};k=requestAnimationFrame(G)},De=l=>{let c=new Map;l.forEach(A=>{let P=Ot.get(A.id);c.set(A.id,{streaming:A.streaming,role:A.role}),!P&&A.role==="assistant"&&s.emit("assistant:message",A),A.role==="assistant"&&(P!=null&&P.streaming)&&A.streaming===!1&&s.emit("assistant:complete",A)}),Ot.clear(),c.forEach((A,P)=>{Ot.set(P,A)})},Ke=(l,c,A)=>{let P=document.createElement("div");c.forEach(T=>{var Fe,Ae;let ee=null,G=r.find(pe=>!!(T.variant==="reasoning"&&pe.renderReasoning||T.variant==="tool"&&pe.renderToolCall||!T.variant&&pe.renderMessage)),ve=(Fe=t.layout)==null?void 0:Fe.messages;if(G)if(T.variant==="reasoning"&&T.reasoning&&G.renderReasoning){if(!O)return;ee=G.renderReasoning({message:T,defaultRenderer:()=>vs(T),config:t})}else if(T.variant==="tool"&&T.toolCall&&G.renderToolCall){if(!C)return;ee=G.renderToolCall({message:T,defaultRenderer:()=>bs(T,t),config:t})}else G.renderMessage&&(ee=G.renderMessage({message:T,defaultRenderer:()=>{let pe=rn(T,A,ve,t.messageActions,W);return T.role!=="user"&&Cs(pe,T,t,$),pe},config:t}));if(!ee&&T.role==="assistant"&&!T.variant&&t.enableComponentStreaming!==!1&&es(T)){let je=ts(T);if(je){let qe=Zn(je,{config:t,message:T,transform:A});if(qe){let rt=document.createElement("div");if(rt.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(" "),rt.id=`bubble-${T.id}`,rt.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=A({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),rt.appendChild(Tt)}rt.appendChild(qe),ee=rt}}}if(!ee)if(T.variant==="reasoning"&&T.reasoning){if(!O)return;ee=vs(T)}else if(T.variant==="tool"&&T.toolCall){if(!C)return;ee=bs(T,t)}else{let pe=(Ae=t.layout)==null?void 0:Ae.messages;pe!=null&&pe.renderUserMessage&&T.role==="user"?ee=pe.renderUserMessage({message:T,config:t,streaming:!!T.streaming}):pe!=null&&pe.renderAssistantMessage&&T.role==="assistant"?ee=pe.renderAssistantMessage({message:T,config:t,streaming:!!T.streaming}):ee=rn(T,A,pe,t.messageActions,W),T.role!=="user"&&ee&&Cs(ee,T,t,$)}let N=document.createElement("div");N.className="tvw-flex",N.id=`wrapper-${T.id}`,N.setAttribute("data-wrapper-id",T.id),T.role==="user"&&N.classList.add("tvw-justify-end"),N.appendChild(ee),P.appendChild(N)});let b=c.some(T=>T.role==="assistant"&&T.streaming),Q=c[c.length-1],ue=(Q==null?void 0:Q.role)==="assistant"&&!Q.streaming;if(wt&&c.some(T=>T.role==="user")&&!b&&!ue){let T=Tn(),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(T);let G=document.createElement("div");G.className="tvw-flex",G.id="wrapper-typing-indicator",G.setAttribute("data-wrapper-id","typing-indicator"),G.appendChild(ee),P.appendChild(G)}Vr(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let T=le();Se(T)})})},ke=()=>{h&&(I?(U.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),j.classList.remove("tvw-scale-95","tvw-opacity-0"),j.classList.add("tvw-scale-100","tvw-opacity-100"),se?se.element.style.display="none":de&&(de.style.display="none")):(U.classList.add("tvw-pointer-events-none","tvw-opacity-0"),j.classList.remove("tvw-scale-100","tvw-opacity-100"),j.classList.add("tvw-scale-95","tvw-opacity-0"),se?se.element.style.display="":de&&(de.style.display="")))},L=(l,c="user")=>{if(!h||I===l)return;let A=I;I=l,ke(),I&&(mt(),Yt(!0));let P={open:I,source:c,timestamp:Date.now()};I&&!A?s.emit("widget:opened",P):!I&&A&&s.emit("widget:closed",P),s.emit("widget:state",{open:I,launcherEnabled:h,voiceActive:Le.active,streaming:$.isStreaming()})},bt=l=>{_.disabled=l,F&&(F.disabled=l),ft.buttons.forEach(c=>{c.disabled=l})},oe=()=>{var b,Q,ue,T,ee,G,ve,N,Fe,Ae,pe,je,qe,rt;kt.textContent=(Q=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?Q:"Hello \u{1F44B}",Ft.textContent=(T=(ue=t.copy)==null?void 0:ue.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",V.placeholder=(G=(ee=t.copy)==null?void 0:ee.inputPlaceholder)!=null?G:"How can I help...",((N=(ve=t.sendButton)==null?void 0:ve.useIcon)!=null?N:!1)||(_.textContent=(Ae=(Fe=t.copy)==null?void 0:Fe.sendButtonLabel)!=null?Ae:"Send");let c=(je=(pe=t.theme)==null?void 0:pe.inputFontFamily)!=null?je:"sans-serif",A=(rt=(qe=t.theme)==null?void 0:qe.inputFontWeight)!=null?rt:"400",P=Tt=>{switch(Tt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};V.style.fontFamily=P(c),V.style.fontWeight=A};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(c=>({...c,session_id:l}))}}),$=new nn(t,{onMessagesChanged(l){Ke(X,l,v),$&&(l.some(P=>P.role==="user")?ft.render([],$,V,l):ft.render(t.suggestionChips,$,V,l,t.suggestionChipsConfig)),Yt(!wt),De(l);let c=[...l].reverse().find(A=>A.role==="user");Le.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),mn(l)},onStatusChanged(l){var P;let c=(P=t.statusIndicator)!=null?P:{},A=b=>{var Q,ue,T,ee;return b==="idle"?(Q=c.idleText)!=null?Q:gt.idle:b==="connecting"?(ue=c.connectingText)!=null?ue:gt.connecting:b==="connected"?(T=c.connectedText)!=null?T:gt.connected:b==="error"?(ee=c.errorText)!=null?ee:gt.error:gt[b]};lt.textContent=A(l)},onStreamingChanged(l){wt=l,bt(l),$&&Ke(X,$.getMessages(),v),l||Yt(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=Ms(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&$.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let B=l=>{var b;l.preventDefault();let c=V.value.trim(),A=(b=Te==null?void 0:Te.hasAttachments())!=null?b:!1;if(!c&&!A)return;let P;A&&(P=[],P.push(...Te.getContentParts()),c&&P.push(Un(c))),V.value="",V.style.height="auto",$.sendMessage(c,{contentParts:P}),A&&Te.clearAttachments()},E=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),_.click())},z=null,fe=!1,Ee=null,Xe=null,Ie=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,_e=(l="user")=>{var Q,ue,T,ee;if(fe||$.isStreaming())return;let c=Ie();if(!c)return;z=new c;let P=(ue=((Q=t.voiceRecognition)!=null?Q:{}).pauseDuration)!=null?ue:2e3;z.continuous=!0,z.interimResults=!0,z.lang="en-US";let b=V.value;z.onresult=G=>{let ve="",N="";for(let Ae=0;Ae<G.results.length;Ae++){let pe=G.results[Ae],je=pe[0].transcript;pe.isFinal?ve+=je+" ":N=je}let Fe=b+ve+N;V.value=Fe,Ee&&clearTimeout(Ee),(ve||N)&&(Ee=window.setTimeout(()=>{let Ae=V.value.trim();Ae&&z&&fe&&(We(),V.value="",V.style.height="auto",$.sendMessage(Ae,{viaVoice:!0}))},P))},z.onerror=G=>{G.error!=="no-speech"&&We()},z.onend=()=>{if(fe){let G=V.value.trim();G&&G!==b.trim()&&(V.value="",V.style.height="auto",$.sendMessage(G,{viaVoice:!0})),We()}};try{if(z.start(),fe=!0,Le.active=!0,l!=="system"&&(Le.manuallyDeactivated=!1),gn(l),Dt(),F){Xe={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let G=(T=t.voiceRecognition)!=null?T:{},ve=(ee=G.recordingBackgroundColor)!=null?ee:"#ef4444",N=G.recordingIconColor,Fe=G.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=ve,N){F.style.color=N;let Ae=F.querySelector("svg");Ae&&Ae.setAttribute("stroke",N)}Fe&&(F.style.borderColor=Fe),F.setAttribute("aria-label","Stop voice recognition")}}catch{We("system")}},We=(l="user")=>{if(fe){if(fe=!1,Ee&&(clearTimeout(Ee),Ee=null),z){try{z.stop()}catch{}z=null}if(Le.active=!1,gn(l),Dt(),F){if(F.classList.remove("tvw-voice-recording"),Xe){F.style.backgroundColor=Xe.backgroundColor,F.style.color=Xe.color,F.style.borderColor=Xe.borderColor;let c=F.querySelector("svg");c&&c.setAttribute("stroke",Xe.color||"currentColor"),Xe=null}F.setAttribute("aria-label","Start voice recognition")}}},Ce=(l,c)=>{var je,qe,rt,Tt,Z,Me,Kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=u("div","tvw-send-button-wrapper"),b=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");b.type="button",b.setAttribute("aria-label","Start voice recognition");let Q=(je=l==null?void 0:l.iconName)!=null?je:"mic",ue=(qe=c==null?void 0:c.size)!=null?qe:"40px",T=(rt=l==null?void 0:l.iconSize)!=null?rt:ue,ee=parseFloat(T)||24,G=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,ve=(Z=l==null?void 0:l.iconColor)!=null?Z:c==null?void 0:c.textColor;b.style.width=T,b.style.height=T,b.style.minWidth=T,b.style.minHeight=T,b.style.fontSize="18px",b.style.lineHeight="1";let N=ve||"currentColor",Fe=re(Q,ee,N,1.5);Fe?(b.appendChild(Fe),b.style.color=N):(b.textContent="\u{1F3A4}",b.style.color=N),G?b.style.backgroundColor=G:b.classList.add("tvw-bg-cw-primary"),ve?b.style.color=ve:!ve&&!(c!=null&&c.textColor)&&b.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(b.style.borderWidth=l.borderWidth,b.style.borderStyle="solid"),l!=null&&l.borderColor&&(b.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(b.style.paddingLeft=l.paddingX,b.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(b.style.paddingTop=l.paddingY,b.style.paddingBottom=l.paddingY),P.appendChild(b);let Ae=(Me=l==null?void 0:l.tooltipText)!=null?Me:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&Ae){let Xt=u("div","tvw-send-button-tooltip");Xt.textContent=Ae,P.appendChild(Xt)}return{micButton:b,micButtonWrapper:P}},xe=()=>{if(fe){let l=V.value.trim();Le.manuallyDeactivated=!0,Dt(),We("user"),l&&(V.value="",V.style.height="auto",$.sendMessage(l))}else Le.manuallyDeactivated=!1,Dt(),_e("user")};F&&(F.addEventListener("click",xe),He.push(()=>{We("system"),F&&F.removeEventListener("click",xe)}));let Ve=s.on("assistant:complete",()=>{pn&&(Le.active||Le.manuallyDeactivated||pn==="assistant"&&!Le.lastUserMessageWasVoice||setTimeout(()=>{!Le.active&&!Le.manuallyDeactivated&&_e("auto")},600))});He.push(Ve);let ce=()=>{L(!I,"user")},se=null,de=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>An(t,ce).element,onToggle:ce});c&&(de=c)}de||(se=An(t,ce))}se?e.appendChild(se.element):de&&e.appendChild(de),ke(),ft.render(t.suggestionChips,$,V,void 0,t.suggestionChipsConfig),oe(),bt($.isStreaming()),Yt(!0),Ln();let mt=()=>{var A,P,b,Q,ue,T,ee,G;let l=(P=(A=t.launcher)==null?void 0:A.sidebarMode)!=null?P:!1,c=l||((Q=(b=t.launcher)==null?void 0:b.fullHeight)!=null?Q:!1);if(!h){j.style.height="",j.style.width="";return}if(!l){let ve=(T=(ue=t==null?void 0:t.launcher)==null?void 0:ue.width)!=null?T:t==null?void 0:t.launcherWidth,N=ve!=null?ve:"min(400px, calc(100vw - 24px))";j.style.width=N,j.style.maxWidth=N}if(!c){let ve=window.innerHeight,N=64,Fe=(G=(ee=t.launcher)==null?void 0:ee.heightOffset)!=null?G:0,Ae=Math.max(200,ve-N),pe=Math.min(640,Ae),je=Math.max(200,pe-Fe);j.style.height=`${je}px`}};mt(),window.addEventListener("resize",mt),He.push(()=>window.removeEventListener("resize",mt)),At=H.scrollTop;let Ps=()=>{let l=H.scrollTop,c=H.scrollHeight,A=H.clientHeight,P=c-l-A,b=Math.abs(l-At);if(At=l,!Ze&&!(b<=Nt)){if(!yt&&P<tn){Re=!1,yt=!0;return}yt&&P>tn&&(Re=!0,vt=Date.now()+It,yt=!1)}};H.addEventListener("scroll",Ps,{passive:!0}),He.push(()=>H.removeEventListener("scroll",Ps)),He.push(()=>{ye&&cancelAnimationFrame(ye)});let Hs=()=>{q&&(ot&&(q.removeEventListener("click",ot),ot=null),h?(q.style.display="",ot=()=>{I=!1,ke()},q.addEventListener("click",ot)):q.style.display="none")};Hs(),(()=>{let{clearChatButton:l}=D;l&&l.addEventListener("click",()=>{$.clearMessages();try{localStorage.removeItem(un),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${un}`)}catch(A){console.error("[AgentWidget] Failed to clear default localStorage:",A)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==un)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(A){console.error("[AgentWidget] Failed to clear custom localStorage:",A)}let c=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let A=i.clear();A instanceof Promise&&A.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",P)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)}a={},w.syncFromMetadata()})})(),at.addEventListener("submit",B),V.addEventListener("keydown",E),He.push(()=>{at.removeEventListener("submit",B),V.removeEventListener("keydown",E)}),He.push(()=>{$.cancel()}),se?He.push(()=>{se==null||se.destroy()}):de&&He.push(()=>{de==null||de.remove()});let _t={update(l){var 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,Lo,ko,Po,Ho,Bo,Io,Ro,Fo,$o,No,Oo,Do,_o,jo,qo,zo,Uo,Jo,Yo,Ko,Xo,Vo,Go,Qo,Zo,er,tr,nr,sr,or,rr,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar;let c=t.toolCall,A=t.colorScheme;t={...t,...l},Qe(),Kn(e,t),t.colorScheme!==A&&Wt();let P=En.getForInstance(t.plugins);if(r.length=0,r.push(...P),h=(Gs=(Vs=t.launcher)==null?void 0:Vs.enabled)!=null?Gs:!0,R=(Zs=(Qs=t.launcher)==null?void 0:Qs.autoExpand)!=null?Zs:!1,O=(to=(eo=t.features)==null?void 0:eo.showReasoning)!=null?to:!0,C=(so=(no=t.features)==null?void 0:no.showToolCalls)!=null?so:!0,((oo=t.launcher)==null?void 0:oo.enabled)===!1&&se&&(se.destroy(),se=null),((ro=t.launcher)==null?void 0:ro.enabled)===!1&&de&&(de.remove(),de=null),((io=t.launcher)==null?void 0:io.enabled)!==!1&&!se&&!de){let x=r.find(ge=>ge.renderLauncher);if(x!=null&&x.renderLauncher){let ge=x.renderLauncher({config:t,defaultRenderer:()=>An(t,ce).element,onToggle:ce});ge&&(de=ge,e.appendChild(de))}de||(se=An(t,ce),e.appendChild(se.element))}se&&se.update(t),dt&&((ao=t.launcher)==null?void 0:ao.title)!==void 0&&(dt.textContent=t.launcher.title),ct&&((lo=t.launcher)==null?void 0:lo.subtitle)!==void 0&&(ct.textContent=t.launcher.subtitle);let b=(co=t.layout)==null?void 0:co.header;if((b==null?void 0:b.layout)!==S&&Ue){let x=b?sn(t,b,{showClose:h,onClose:()=>L(!1,"user")}):qt({config:t,showClose:h,onClose:()=>L(!1,"user")});Ue.replaceWith(x.header),Ue=x.header,we=x.iconHolder,dt=x.headerTitle,ct=x.headerSubtitle,q=x.closeButton,S=b==null?void 0:b.layout}else if(b&&(we&&(we.style.display=b.showIcon===!1?"none":""),dt&&(dt.style.display=b.showTitle===!1?"none":""),ct&&(ct.style.display=b.showSubtitle===!1?"none":""),q&&(q.style.display=b.showCloseButton===!1?"none":""),D.clearChatButtonWrapper)){let x=b.showClearChat;if(x!==void 0){D.clearChatButtonWrapper.style.display=x?"":"none";let{closeButtonWrapper:ge}=D;ge&&!ge.classList.contains("tvw-absolute")&&(x?ge.classList.remove("tvw-ml-auto"):ge.classList.add("tvw-ml-auto"))}}let ue=((uo=t.layout)==null?void 0:uo.showHeader)!==!1;Ue&&(Ue.style.display=ue?"":"none");let T=((po=t.layout)==null?void 0:po.showFooter)!==!1;ut&&(ut.style.display=T?"":"none"),h!==y?h?L(R,"auto"):(I=!0,ke()):R!==M&&L(R,"auto"),M=R,y=h,mt(),Hs(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&$&&Ke(X,$.getMessages(),v);let N=(go=t.launcher)!=null?go:{},Fe=(mo=N.headerIconHidden)!=null?mo:!1,Ae=(fo=(ho=t.layout)==null?void 0:ho.header)==null?void 0:fo.showIcon,pe=Fe||Ae===!1,je=N.headerIconName,qe=(wo=N.headerIconSize)!=null?wo:"48px";if(we){let x=Y.querySelector(".tvw-border-b-cw-divider"),ge=x==null?void 0:x.querySelector(".tvw-flex-col");if(pe)we.style.display="none",x&&ge&&!x.contains(ge)&&x.insertBefore(ge,x.firstChild);else{if(we.style.display="",we.style.height=qe,we.style.width=qe,x&&ge&&(x.contains(we)?we.nextSibling!==ge&&(we.remove(),x.insertBefore(we,ge)):x.insertBefore(we,ge)),je){let ne=parseFloat(qe)||24,be=re(je,ne*.6,"#ffffff",2);be?we.replaceChildren(be):we.textContent=(yo=N.agentIconText)!=null?yo:"\u{1F4AC}"}else if(N.iconUrl){let ne=we.querySelector("img");if(ne)ne.src=N.iconUrl,ne.style.height=qe,ne.style.width=qe;else{let be=document.createElement("img");be.src=N.iconUrl,be.alt="",be.className="tvw-rounded-xl tvw-object-cover",be.style.height=qe,be.style.width=qe,we.replaceChildren(be)}}else{let ne=we.querySelector("svg"),be=we.querySelector("img");(ne||be)&&we.replaceChildren(),we.textContent=(vo=N.agentIconText)!=null?vo:"\u{1F4AC}"}let $e=we.querySelector("img");$e&&($e.style.height=qe,$e.style.width=qe)}}let rt=(Co=(bo=t.layout)==null?void 0:bo.header)==null?void 0:Co.showTitle,Tt=(So=(xo=t.layout)==null?void 0:xo.header)==null?void 0:So.showSubtitle;if(dt&&(dt.style.display=rt===!1?"none":""),ct&&(ct.style.display=Tt===!1?"none":""),q){((To=(Ao=t.layout)==null?void 0:Ao.header)==null?void 0:To.showCloseButton)===!1?q.style.display="none":q.style.display="";let ge=(Eo=N.closeButtonSize)!=null?Eo:"32px",$e=(Mo=N.closeButtonPlacement)!=null?Mo:"inline";q.style.height=ge,q.style.width=ge;let{closeButtonWrapper:ne}=D,be=$e==="top-right",pt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&be!==pt)if(ne.remove(),be)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(ne);else{let ie=(Lo=(Wo=N.clearChat)==null?void 0:Wo.placement)!=null?Lo:"inline",Ge=(Po=(ko=N.clearChat)==null?void 0:ko.enabled)!=null?Po:!0;ne.className=Ge&&ie==="inline"?"":"tvw-ml-auto";let Ct=Y.querySelector(".tvw-border-b-cw-divider");Ct&&Ct.appendChild(ne)}if(N.closeButtonColor?(q.style.color=N.closeButtonColor,q.classList.remove("tvw-text-cw-muted")):(q.style.color="",q.classList.add("tvw-text-cw-muted")),N.closeButtonBackgroundColor?(q.style.backgroundColor=N.closeButtonBackgroundColor,q.classList.remove("hover:tvw-bg-gray-100")):(q.style.backgroundColor="",q.classList.add("hover:tvw-bg-gray-100")),N.closeButtonBorderWidth||N.closeButtonBorderColor){let ie=N.closeButtonBorderWidth||"0px",Ge=N.closeButtonBorderColor||"transparent";q.style.border=`${ie} solid ${Ge}`,q.classList.remove("tvw-border-none")}else q.style.border="",q.classList.add("tvw-border-none");N.closeButtonBorderRadius?(q.style.borderRadius=N.closeButtonBorderRadius,q.classList.remove("tvw-rounded-full")):(q.style.borderRadius="",q.classList.add("tvw-rounded-full")),N.closeButtonPaddingX?(q.style.paddingLeft=N.closeButtonPaddingX,q.style.paddingRight=N.closeButtonPaddingX):(q.style.paddingLeft="",q.style.paddingRight=""),N.closeButtonPaddingY?(q.style.paddingTop=N.closeButtonPaddingY,q.style.paddingBottom=N.closeButtonPaddingY):(q.style.paddingTop="",q.style.paddingBottom="");let it=(Ho=N.closeButtonIconName)!=null?Ho:"x",Et=(Bo=N.closeButtonIconText)!=null?Bo:"\xD7";q.innerHTML="";let ht=re(it,"20px",N.closeButtonColor||"",2);ht?q.appendChild(ht):q.textContent=Et;let Ne=(Io=N.closeButtonTooltipText)!=null?Io:"Close chat",Mt=(Ro=N.closeButtonShowTooltip)!=null?Ro:!0;if(q.setAttribute("aria-label",Ne),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),Mt&&Ne)){let ie=null,Ge=()=>{if(ie||!q)return;ie=u("div","tvw-clear-chat-tooltip"),ie.textContent=Ne;let Cn=u("div");Cn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(Cn);let Vt=q.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Vt.left+Vt.width/2}px`,ie.style.top=`${Vt.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};ne.addEventListener("mouseenter",Ge),ne.addEventListener("mouseleave",Ct),q.addEventListener("focus",Ge),q.addEventListener("blur",Ct),ne._cleanupTooltip=()=>{Ct(),ne&&(ne.removeEventListener("mouseenter",Ge),ne.removeEventListener("mouseleave",Ct)),q&&(q.removeEventListener("focus",Ge),q.removeEventListener("blur",Ct))}}}let{clearChatButton:Z,clearChatButtonWrapper:Me}=D;if(Z){let x=(Fo=N.clearChat)!=null?Fo:{},ge=($o=x.enabled)!=null?$o:!0,$e=(Oo=(No=t.layout)==null?void 0:No.header)==null?void 0:Oo.showClearChat,ne=$e!==void 0?$e:ge,be=(Do=x.placement)!=null?Do:"inline";if(Me){Me.style.display=ne?"":"none";let{closeButtonWrapper:pt}=D;pt&&!pt.classList.contains("tvw-absolute")&&(ne?pt.classList.remove("tvw-ml-auto"):pt.classList.add("tvw-ml-auto"));let it=be==="top-right",Et=Me.classList.contains("tvw-absolute");if(it!==Et&&ne){if(Me.remove(),it)Me.className="tvw-absolute tvw-top-4 tvw-z-50",Me.style.right="48px",Y.style.position="relative",Y.appendChild(Me);else{Me.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Me.style.right="";let Ne=Y.querySelector(".tvw-border-b-cw-divider"),Mt=D.closeButtonWrapper;Ne&&Mt&&Mt.parentElement===Ne?Ne.insertBefore(Me,Mt):Ne&&Ne.appendChild(Me)}let ht=D.closeButtonWrapper;ht&&!ht.classList.contains("tvw-absolute")&&(it?ht.classList.add("tvw-ml-auto"):ht.classList.remove("tvw-ml-auto"))}}if(ne){let pt=(_o=x.size)!=null?_o:"32px";Z.style.height=pt,Z.style.width=pt;let it=(jo=x.iconName)!=null?jo:"refresh-cw",Et=(qo=x.iconColor)!=null?qo:"";Z.innerHTML="";let ht=re(it,"20px",Et||"",2);if(ht&&Z.appendChild(ht),Et?(Z.style.color=Et,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),x.backgroundColor?(Z.style.backgroundColor=x.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),x.borderWidth||x.borderColor){let ie=x.borderWidth||"0px",Ge=x.borderColor||"transparent";Z.style.border=`${ie} solid ${Ge}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");x.borderRadius?(Z.style.borderRadius=x.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),x.paddingX?(Z.style.paddingLeft=x.paddingX,Z.style.paddingRight=x.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),x.paddingY?(Z.style.paddingTop=x.paddingY,Z.style.paddingBottom=x.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let Ne=(zo=x.tooltipText)!=null?zo:"Clear chat",Mt=(Uo=x.showTooltip)!=null?Uo:!0;if(Z.setAttribute("aria-label",Ne),Me&&(Me._cleanupTooltip&&(Me._cleanupTooltip(),delete Me._cleanupTooltip),Mt&&Ne)){let ie=null,Ge=()=>{if(ie||!Z)return;ie=u("div","tvw-clear-chat-tooltip"),ie.textContent=Ne;let Cn=u("div");Cn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(Cn);let Vt=Z.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Vt.left+Vt.width/2}px`,ie.style.top=`${Vt.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};Me.addEventListener("mouseenter",Ge),Me.addEventListener("mouseleave",Ct),Z.addEventListener("focus",Ge),Z.addEventListener("blur",Ct),Me._cleanupTooltip=()=>{Ct(),Me&&(Me.removeEventListener("mouseenter",Ge),Me.removeEventListener("mouseleave",Ct)),Z&&(Z.removeEventListener("focus",Ge),Z.removeEventListener("blur",Ct))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Mn],Xt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick];w=Wn({parsers:Kt,handlers:Xt,getSessionMetadata:p,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),v=ci(t,w),$.updateConfig(t),Ke(X,$.getMessages(),v),ft.render(t.suggestionChips,$,V,void 0,t.suggestionChipsConfig),oe(),bt($.isStreaming());let Pn=((Jo=t.voiceRecognition)==null?void 0:Jo.enabled)===!0,Hn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Pn&&Hn)if(!F||!Oe){let x=Ce(t.voiceRecognition,t.sendButton);x&&(F=x.micButton,Oe=x.micButtonWrapper,Ht.insertBefore(Oe,tt),F.addEventListener("click",xe),F.disabled=$.isStreaming())}else{let x=(Yo=t.voiceRecognition)!=null?Yo:{},ge=(Ko=t.sendButton)!=null?Ko:{},$e=(Xo=x.iconName)!=null?Xo:"mic",ne=(Vo=ge.size)!=null?Vo:"40px",be=(Go=x.iconSize)!=null?Go:ne,pt=parseFloat(be)||24;F.style.width=be,F.style.height=be,F.style.minWidth=be,F.style.minHeight=be;let it=(Zo=(Qo=x.iconColor)!=null?Qo:ge.textColor)!=null?Zo:"currentColor";F.innerHTML="";let Et=re($e,pt,it,2);Et?F.appendChild(Et):F.textContent="\u{1F3A4}";let ht=(er=x.backgroundColor)!=null?er:ge.backgroundColor;ht?(F.style.backgroundColor=ht,F.classList.remove("tvw-bg-cw-primary")):(F.style.backgroundColor="",F.classList.add("tvw-bg-cw-primary")),it?(F.style.color=it,F.classList.remove("tvw-text-white")):!it&&!ge.textColor&&(F.style.color="",F.classList.add("tvw-text-white")),x.borderWidth?(F.style.borderWidth=x.borderWidth,F.style.borderStyle="solid"):(F.style.borderWidth="",F.style.borderStyle=""),x.borderColor?F.style.borderColor=x.borderColor:F.style.borderColor="",x.paddingX?(F.style.paddingLeft=x.paddingX,F.style.paddingRight=x.paddingX):(F.style.paddingLeft="",F.style.paddingRight=""),x.paddingY?(F.style.paddingTop=x.paddingY,F.style.paddingBottom=x.paddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Ne=Oe==null?void 0:Oe.querySelector(".tvw-send-button-tooltip"),Mt=(tr=x.tooltipText)!=null?tr:"Start voice recognition";if(((nr=x.showTooltip)!=null?nr:!1)&&Mt)if(Ne)Ne.textContent=Mt,Ne.style.display="";else{let Ge=document.createElement("div");Ge.className="tvw-send-button-tooltip",Ge.textContent=Mt,Oe==null||Oe.insertBefore(Ge,F)}else Ne&&(Ne.style.display="none");Oe.style.display="",F.disabled=$.isStreaming()}else F&&Oe&&(Oe.style.display="none",fe&&We());if(((sr=t.attachments)==null?void 0:sr.enabled)===!0)if(!nt||!me){let x=(or=t.attachments)!=null?or:{},$e=(ir=((rr=t.sendButton)!=null?rr:{}).size)!=null?ir:"40px";st||(st=u("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),st.style.display="none",at.insertBefore(st,V)),he||(he=document.createElement("input"),he.type="file",he.accept=((ar=x.allowedTypes)!=null?ar:Jt).join(","),he.multiple=((lr=x.maxFiles)!=null?lr:4)>1,he.style.display="none",he.setAttribute("aria-label","Attach files"),at.insertBefore(he,V)),nt=u("div","tvw-send-button-wrapper"),me=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),me.type="button",me.setAttribute("aria-label",(dr=x.buttonTooltipText)!=null?dr:"Attach file");let ne=(cr=x.buttonIconName)!=null?cr:"paperclip",be=$e,pt=parseFloat(be)||40,it=Math.round(pt*.6);me.style.width=be,me.style.height=be,me.style.minWidth=be,me.style.minHeight=be,me.style.fontSize="18px",me.style.lineHeight="1",me.style.backgroundColor="transparent",me.style.color="var(--cw-primary, #111827)",me.style.border="none",me.style.borderRadius="6px",me.style.transition="background-color 0.15s ease",me.addEventListener("mouseenter",()=>{me.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),me.addEventListener("mouseleave",()=>{me.style.backgroundColor="transparent"});let Et=re(ne,it,"currentColor",1.5);Et?me.appendChild(Et):me.textContent="\u{1F4CE}",me.addEventListener("click",Mt=>{Mt.preventDefault(),he==null||he.click()}),nt.appendChild(me);let ht=(ur=x.buttonTooltipText)!=null?ur:"Attach file",Ne=u("div","tvw-send-button-tooltip");Ne.textContent=ht,nt.appendChild(Ne),Pt.append(nt),!Te&&he&&st&&(Te=Qt.fromConfig(x),Te.setPreviewsContainer(st),he.addEventListener("change",async()=>{Te&&(he!=null&&he.files)&&(await Te.handleFileSelect(he.files),he.value="")}))}else{nt.style.display="";let x=(pr=t.attachments)!=null?pr:{};he&&(he.accept=((gr=x.allowedTypes)!=null?gr:Jt).join(","),he.multiple=((mr=x.maxFiles)!=null?mr:4)>1),Te&&Te.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else nt&&(nt.style.display="none"),Te&&Te.clearAttachments();let ze=(hr=t.sendButton)!=null?hr:{},Bn=(fr=ze.useIcon)!=null?fr:!1,hn=(wr=ze.iconText)!=null?wr:"\u2191",fn=ze.iconName,Ut=(yr=ze.tooltipText)!=null?yr:"Send message",wn=(vr=ze.showTooltip)!=null?vr:!1,yn=(br=ze.size)!=null?br:"40px",In=ze.backgroundColor,Rt=ze.textColor;if(Bn){if(_.style.width=yn,_.style.height=yn,_.style.minWidth=yn,_.style.minHeight=yn,_.style.fontSize="18px",_.style.lineHeight="1",_.innerHTML="",fn){let x=parseFloat(yn)||24,ge=Rt&&typeof Rt=="string"&&Rt.trim()?Rt.trim():"currentColor",$e=re(fn,x,ge,2);$e?(_.appendChild($e),_.style.color=ge):(_.textContent=hn,Rt?_.style.color=Rt:_.classList.add("tvw-text-white"))}else _.textContent=hn,Rt?_.style.color=Rt:_.classList.add("tvw-text-white");_.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",In?(_.style.backgroundColor=In,_.classList.remove("tvw-bg-cw-primary")):_.classList.add("tvw-bg-cw-primary")}else _.textContent=(xr=(Cr=t.copy)==null?void 0:Cr.sendButtonLabel)!=null?xr:"Send",_.style.width="",_.style.height="",_.style.minWidth="",_.style.minHeight="",_.style.fontSize="",_.style.lineHeight="",_.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",In?(_.style.backgroundColor=In,_.classList.remove("tvw-bg-cw-accent")):_.classList.add("tvw-bg-cw-accent"),Rt?_.style.color=Rt:_.classList.add("tvw-text-white");ze.borderWidth?(_.style.borderWidth=ze.borderWidth,_.style.borderStyle="solid"):(_.style.borderWidth="",_.style.borderStyle=""),ze.borderColor?_.style.borderColor=ze.borderColor:_.style.borderColor="",ze.paddingX?(_.style.paddingLeft=ze.paddingX,_.style.paddingRight=ze.paddingX):(_.style.paddingLeft="",_.style.paddingRight=""),ze.paddingY?(_.style.paddingTop=ze.paddingY,_.style.paddingBottom=ze.paddingY):(_.style.paddingTop="",_.style.paddingBottom="");let vn=tt==null?void 0:tt.querySelector(".tvw-send-button-tooltip");if(wn&&Ut)if(vn)vn.textContent=Ut,vn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=Ut,tt==null||tt.insertBefore(x,_)}else vn&&(vn.style.display="none");let bn=(Sr=t.statusIndicator)!=null?Sr:{},yi=(Ar=bn.visible)!=null?Ar:!0;if(lt.style.display=yi?"":"none",$){let x=$.getStatus(),ge=$e=>{var ne,be,pt,it;return $e==="idle"?(ne=bn.idleText)!=null?ne:gt.idle:$e==="connecting"?(be=bn.connectingText)!=null?be:gt.connecting:$e==="connected"?(pt=bn.connectedText)!=null?pt:gt.connected:$e==="error"?(it=bn.errorText)!=null?it:gt.error:gt[$e]};lt.textContent=ge(x)}},open(){h&&L(!0,"api")},close(){h&&L(!1,"api")},toggle(){h&&L(!I,"api")},clearChat(){$.clearMessages();try{localStorage.removeItem(un),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${un}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==un)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let l=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let c=i.clear();c instanceof Promise&&c.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}a={},w.syncFromMetadata()},setMessage(l){return!V||$.isStreaming()?!1:(!I&&h&&L(!0,"system"),V.value=l,V.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let c=(l==null?void 0:l.trim())||V.value.trim();return c?(!I&&h&&L(!0,"system"),V.value="",V.style.height="auto",$.sendMessage(c),!0):!1},startVoiceRecognition(){return fe||$.isStreaming()||!Ie()?!1:(!I&&h&&L(!0,"system"),Le.manuallyDeactivated=!1,Dt(),_e("user"),!0)},stopVoiceRecognition(){return fe?(Le.manuallyDeactivated=!0,Dt(),We("user"),!0):!1},injectTestMessage(l){!I&&h&&L(!0,"system"),$.injectTestEvent(l)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){f(l)},on(l,c){return s.on(l,c)},off(l,c){s.off(l,c)},isOpen(){return h&&I},isVoiceActive(){return Le.active},getState(){return{open:h&&I,launcherEnabled:h,voiceActive:Le.active,streaming:$.isStreaming()}},showCSATFeedback(l){!I&&h&&L(!0,"system");let c=X.querySelector(".tvw-feedback-container");c&&c.remove();let A=ns({onSubmit:async(P,b)=>{var Q;$.isClientTokenMode()&&await $.submitCSATFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});X.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&h&&L(!0,"system");let c=X.querySelector(".tvw-feedback-container");c&&c.remove();let A=ss({onSubmit:async(P,b)=>{var Q;$.isClientTokenMode()&&await $.submitNPSFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});X.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return $.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return $.submitNPSFeedback(l,c)},destroy(){He.forEach(l=>l()),U.remove(),se==null||se.destroy(),de==null||de.remove(),ot&&q.removeEventListener("click",ot)}};if((((Xs=o==null?void 0:o.debugTools)!=null?Xs:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,c={controller:_t,getMessages:_t.getMessages,getStatus:_t.getStatus,getMetadata:_t.getPersistentMetadata,updateMetadata:_t.updatePersistentMetadata,clearHistory:()=>_t.clearChat(),setVoiceActive:A=>A?_t.startVoiceRecognition():_t.stopVoiceRecognition()};window.AgentWidgetBrowser=c,He.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return _t};var Ws={},Zi=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},ea=()=>{try{if(typeof Ws!="undefined"&&Ws.url)return new URL("../widget.css",Ws.url).href}catch{}return null},ui=e=>{let n=ea(),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(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-vanilla-agent","true"),e.insertBefore(t,e.firstChild)}else o();else if(!document.head.querySelector("link[data-vanilla-agent]")&&n){let r=document.createElement("link");r.rel="stylesheet",r.href=n,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},Ls=e=>{var p,f,m,g;let n=Zi(e.target),o=document.createElement("div");o.className="vanilla-agent-host";let t=(m=(f=(p=e.config)==null?void 0:p.launcher)==null?void 0:f.enabled)!=null?m:!0;t||(o.style.height="100%"),n.appendChild(o);let r=e.useShadowDom===!0,s,i;if(r){let w=o.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),ui(w)}else i=o,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),o.appendChild(s),ui(o);let a=os(s,e.config,{debugTools:e.debugTools});(g=e.onReady)==null||g.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 zt(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function ta(e){if(e)return{getHeaders:zt(e.getHeaders),onFeedback:zt(e.onFeedback),onCopy:zt(e.onCopy),requestMiddleware:zt(e.requestMiddleware),actionHandlers:zt(e.actionHandlers),actionParsers:zt(e.actionParsers),postprocessMessage:zt(e.postprocessMessage),contextProviders:zt(e.contextProviders),streamParser:zt(e.streamParser)}}var pi=`({ 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
+ }`,gi=`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
+ }`,mi=`(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
+ }`,hi=`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
+ }`,na=`(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
+ }`,sa=`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 oa(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function rs(e){var n,o;return(o=(n=e.parserType)!=null?n:oa(e.streamParser))!=null?o:"plain"}function is(e,n){let o=[];return e.toolCall&&(o.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([t,r])=>{typeof r=="string"&&o.push(`${n} ${t}: "${r}",`)}),o.push(`${n}},`)),o}function as(e,n,o){let t=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(o==null?void 0:o.onFeedback)||(o==null?void 0:o.onCopy);return(r||s)&&(t.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?t.push(`${n} ${i}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${i}: ${a},`))}),o!=null&&o.onFeedback&&t.push(`${n} onFeedback: ${o.onFeedback},`),o!=null&&o.onCopy&&t.push(`${n} onCopy: ${o.onCopy},`),t.push(`${n}},`)),t}function ls(e,n){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(`${n}markdown: {`),t&&(o.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`)}),o.push(`${n} },`)),r&&o.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),o.push(`${n}},`))}return o}function ds(e,n){let o=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(t||r)&&(o.push(`${n}layout: {`),t&&(o.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`))}),o.push(`${n} },`)),r&&(o.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(o.push(`${n} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?o.push(`${n} ${a}: "${d}",`):typeof d=="boolean"&&o.push(`${n} ${a}: ${d},`)}),o.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(o.push(`${n} timestamp: {`),Object.entries(i).forEach(([d,p])=>{d!=="format"&&(typeof p=="string"?o.push(`${n} ${d}: "${p}",`):typeof p=="boolean"&&o.push(`${n} ${d}: ${p},`))}),o.push(`${n} },`)):typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`))}),o.push(`${n} },`)),o.push(`${n}},`))}return o}function ks(e,n){let o=[];return e&&(e.getHeaders&&o.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&o.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&o.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&o.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&o.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&o.push(`${n}streamParser: ${e.streamParser},`)),o}function fi(e,n="esm",o){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let r=o?{...o,hooks:ta(o.hooks)}:void 0;return n==="esm"?ra(t,r):n==="script-installer"?la(t):n==="script-advanced"?ca(t,r):n==="react-component"?ia(t,r):n==="react-advanced"?aa(t,r):da(t,r)}function ra(e,n){let o=n==null?void 0:n.hooks,t=rs(e),r=t!=="plain",s=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...ks(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
+ `)}function ia(e,n){let o=n==null?void 0:n.hooks,t=rs(e),r=t!=="plain",s=["// 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&&s.push(` apiUrl: "${e.apiUrl}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...ks(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
134
+ `)}function aa(e,n){let o=n==null?void 0:n.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,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),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(...is(e," ")),t.push(...as(e," ",o)),t.push(...ls(e," ")),t.push(...ds(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(${na}),`)),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(` ${pi}`),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(` ${pi}`),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(` ${mi}`),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(` ${mi}`),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 wi(e){var r;let n=rs(e),o=n!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.flowId&&(t.flowId=e.flowId),o&&(t.parserType=n),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 s={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(t.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(t.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(t.markdown=s)}if(e.layout){let s={};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&&(s.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 p={};Object.entries(d).forEach(([f,m])=>{f!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(p[f]=m)}),Object.keys(p).length>0&&(i.timestamp=p)}else(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(t.layout=s)}return t}function la(e){let n=wi(e);return`<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js" data-config='${JSON.stringify(n,null,0).replace(/'/g,"&#39;")}'></script>`}function da(e,n){let o=n==null?void 0:n.hooks,t=rs(e),r=t!=="plain",s=["<!-- 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&&s.push(` apiUrl: "${e.apiUrl}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...ks(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
136
+ `)}function ca(e,n){let o=n==null?void 0:n.hooks,t=wi(e),s=["<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&&(s.push(` widgetConfig.getHeaders = ${o.getHeaders};`),s.push("")),o!=null&&o.contextProviders&&(s.push(` widgetConfig.contextProviders = ${o.contextProviders};`),s.push("")),o!=null&&o.streamParser?s.push(` widgetConfig.streamParser = ${o.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${sa});`),s.push(" };")),s.push(""),o!=null&&o.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${o.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${gi}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${gi}`),s.push(" ];")),s.push(""),o!=null&&o.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${o.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${hi}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${hi}`),s.push(" ];")),s.push(""),o!=null&&o.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${o.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),o!=null&&o.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${o.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(o!=null&&o.onFeedback||o!=null&&o.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),o!=null&&o.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${o.onFeedback};`),o!=null&&o.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${o.onCopy};`),s.push("")),s.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>"),s.join(`
139
+ `)}var ua=Ls;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,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,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,validateImageFile});
68
140
  //# sourceMappingURL=index.cjs.map