vanilla-agent 1.24.0 → 1.25.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 Ko=Object.create;var Tn=Object.defineProperty;var Xo=Object.getOwnPropertyDescriptor;var Vo=Object.getOwnPropertyNames;var Go=Object.getPrototypeOf,Zo=Object.prototype.hasOwnProperty;var Qo=(n,e)=>{for(var s in e)Tn(n,s,{get:e[s],enumerable:!0})},xo=(n,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vo(e))!Zo.call(n,r)&&r!==s&&Tn(n,r,{get:()=>e[r],enumerable:!(t=Xo(e,r))||t.enumerable});return n};var er=(n,e,s)=>(s=n!=null?Ko(Go(n)):{},xo(e||!n||!n.__esModule?Tn(s,"default",{value:n,enumerable:!0}):s,n)),tr=n=>xo(Tn({},"__esModule",{value:!0}),n);var Hr={};Qo(Hr,{AgentWidgetClient:()=>Jt,AgentWidgetSession:()=>Zt,DEFAULT_WIDGET_CONFIG:()=>ke,attachHeaderToContainer:()=>Qt,buildComposer:()=>en,buildDefaultHeader:()=>Zn,buildExpandedHeader:()=>es,buildHeader:()=>Ot,buildHeaderWithLayout:()=>In,buildMinimalHeader:()=>Qn,componentRegistry:()=>nn,createActionManager:()=>bn,createAgentExperience:()=>zn,createBubbleWithLayout:()=>Fo,createCSATFeedback:()=>qn,createComponentMiddleware:()=>qo,createComponentStreamParser:()=>On,createDirectivePostprocessor:()=>Mo,createFlexibleJsonStreamParser:()=>Bo,createJsonStreamParser:()=>Bn,createLocalStorageAdapter:()=>Nn,createMarkdownProcessor:()=>hn,createMarkdownProcessorFromConfig:()=>mn,createMessageActions:()=>ns,createNPSFeedback:()=>Un,createPlainTextParser:()=>kn,createRegexJsonParser:()=>Ln,createStandardBubble:()=>tn,createTypingIndicator:()=>wn,createXmlParser:()=>Hn,default:()=>Br,defaultActionHandlers:()=>Kt,defaultJsonActionParser:()=>vn,directivePostprocessor:()=>Wo,escapeHtml:()=>En,extractComponentDirectiveFromMessage:()=>_n,generateAssistantMessageId:()=>Pn,generateCodeSnippet:()=>Jo,generateMessageId:()=>$o,generateUserMessageId:()=>$n,getHeaderLayout:()=>ts,hasComponentDirective:()=>jn,headerLayouts:()=>Rn,initAgentWidget:()=>gs,isComponentDirectiveType:()=>_o,markdownPostprocessor:()=>Xn,mergeWithDefaults:()=>Fn,pluginRegistry:()=>yn,renderComponentDirective:()=>Dn});module.exports=tr(Hr);var Ao=require("marked"),nr=n=>{if(n)return n},hn=n=>{var r,o;let e=n==null?void 0:n.markedOptions,s=new Ao.Marked({gfm:(r=e==null?void 0:e.gfm)!=null?r:!0,breaks:(o=e==null?void 0:e.breaks)!=null?o:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),t=nr(n==null?void 0:n.renderer);return t&&s.use({renderer:t}),i=>s.parse(i)},mn=n=>n?hn({markedOptions:n.options,renderer:n.renderer}):hn(),sr=hn(),Xn=n=>sr(n),En=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),To=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),So=n=>`%%FORM_PLACEHOLDER_${n}%%`,Eo=(n,e)=>{let s=n;return s=s.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let o=JSON.parse(r.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let i=So(e.length);return e.push({token:i,type:String(o.type)}),i}}catch{return t}return t}),s=s.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let o=So(e.length);return e.push({token:o,type:r}),o}),s},Mo=n=>{let e=mn(n);return s=>{let t=[],r=Eo(s,t),o=e(r);return t.forEach(({token:i,type:l})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${To(l)}"></div>`;o=o.replace(c,f)}),o}},Wo=n=>{let e=[],s=Eo(n,e),t=Xn(s);return e.forEach(({token:r,type:o})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="tvw-form-directive" data-tv-form="${To(o)}"></div>`;t=t.replace(i,c)}),t};var Lt=require("partial-json"),Mn=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Vn=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)}},or=n=>{var i,l;let e=(i=n.completedAt)!=null?i:Date.now(),s=(l=n.startedAt)!=null?l:e,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-s))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},ko=n=>n.status==="complete"?or(n):n.status==="pending"?"Waiting":"",rr=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 Lo=n=>n.status==="complete"?rr(n):"Using tool...",ir=()=>{let n=null,e=0,s=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=t.match(r);if(o&&o[1])try{return o[1].replace(/\\n/g,`
1
+ "use strict";var nr=Object.create;var Cn=Object.defineProperty;var sr=Object.getOwnPropertyDescriptor;var or=Object.getOwnPropertyNames;var rr=Object.getPrototypeOf,ir=Object.prototype.hasOwnProperty;var ar=(n,e)=>{for(var s in e)Cn(n,s,{get:e[s],enumerable:!0})},ko=(n,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of or(e))!ir.call(n,r)&&r!==s&&Cn(n,r,{get:()=>e[r],enumerable:!(t=sr(e,r))||t.enumerable});return n};var lr=(n,e,s)=>(s=n!=null?nr(rr(n)):{},ko(e||!n||!n.__esModule?Cn(s,"default",{value:n,enumerable:!0}):s,n)),dr=n=>ko(Cn({},"__esModule",{value:!0}),n);var _r={};ar(_r,{AgentWidgetClient:()=>Yt,AgentWidgetSession:()=>Qt,DEFAULT_DARK_THEME:()=>us,DEFAULT_LIGHT_THEME:()=>cs,DEFAULT_WIDGET_CONFIG:()=>Te,attachHeaderToContainer:()=>Zt,buildComposer:()=>en,buildDefaultHeader:()=>Zn,buildExpandedHeader:()=>ts,buildHeader:()=>Ot,buildHeaderWithLayout:()=>Rn,buildMinimalHeader:()=>es,componentRegistry:()=>nn,createActionManager:()=>mn,createAgentExperience:()=>jn,createBubbleWithLayout:()=>Uo,createCSATFeedback:()=>Dn,createComponentMiddleware:()=>Vo,createComponentStreamParser:()=>$n,createDirectivePostprocessor:()=>Ro,createFlexibleJsonStreamParser:()=>Fo,createJsonStreamParser:()=>Mn,createLocalStorageAdapter:()=>In,createMarkdownProcessor:()=>ln,createMarkdownProcessorFromConfig:()=>dn,createMessageActions:()=>ss,createNPSFeedback:()=>_n,createPlainTextParser:()=>Tn,createRegexJsonParser:()=>En,createStandardBubble:()=>tn,createTypingIndicator:()=>un,createXmlParser:()=>kn,default:()=>Dr,defaultActionHandlers:()=>Kt,defaultJsonActionParser:()=>gn,directivePostprocessor:()=>Po,escapeHtml:()=>xn,extractComponentDirectiveFromMessage:()=>On,generateAssistantMessageId:()=>Ln,generateCodeSnippet:()=>er,generateMessageId:()=>Oo,generateUserMessageId:()=>Wn,getHeaderLayout:()=>ns,hasComponentDirective:()=>Nn,headerLayouts:()=>Hn,initAgentWidget:()=>fs,isComponentDirectiveType:()=>Xo,markdownPostprocessor:()=>Vn,mergeWithDefaults:()=>Pn,pluginRegistry:()=>pn,renderComponentDirective:()=>Fn});module.exports=dr(_r);var Lo=require("marked"),cr=n=>{if(n)return n},ln=n=>{var r,o;let e=n==null?void 0:n.markedOptions,s=new Lo.Marked({gfm:(r=e==null?void 0:e.gfm)!=null?r:!0,breaks:(o=e==null?void 0:e.breaks)!=null?o:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),t=cr(n==null?void 0:n.renderer);return t&&s.use({renderer:t}),i=>s.parse(i)},dn=n=>n?ln({markedOptions:n.options,renderer:n.renderer}):ln(),ur=ln(),Vn=n=>ur(n),xn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Bo=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Wo=n=>`%%FORM_PLACEHOLDER_${n}%%`,Ho=(n,e)=>{let s=n;return s=s.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let o=JSON.parse(r.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let i=Wo(e.length);return e.push({token:i,type:String(o.type)}),i}}catch{return t}return t}),s=s.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let o=Wo(e.length);return e.push({token:o,type:r}),o}),s},Ro=n=>{let e=dn(n);return s=>{let t=[],r=Ho(s,t),o=e(r);return t.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),w=`<div class="tvw-form-directive" data-tv-form="${Bo(l)}"></div>`;o=o.replace(d,w)}),o}},Po=n=>{let e=[],s=Ho(n,e),t=Vn(s);return e.forEach(({token:r,type:o})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Bo(o)}"></div>`;t=t.replace(i,d)}),t};var Wt=require("partial-json"),Sn=n=>n.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Gn=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)}},pr=n=>{var i,l;let e=(i=n.completedAt)!=null?i:Date.now(),s=(l=n.startedAt)!=null?l:e,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-s))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Io=n=>n.status==="complete"?pr(n):n.status==="pending"?"Waiting":"",gr=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 $o=n=>n.status==="complete"?gr(n):"Using tool...",mr=()=>{let n=null,e=0,s=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=t.match(r);if(o&&o[1])try{return o[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=t.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let o=s(t);return o!==null&&(n=o),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},Wn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},kn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Ln=()=>{var e;let n=ir();return{processChunk:async s=>{let t=s.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(s)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Bn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:s=>{let t=s.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(s.length<=e)return n!==null||n===""?{text:n||"",raw:s}:null;try{let r=(0,Lt.parse)(s,Lt.STR|Lt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?Mn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=Mn(r.text)))}catch{}return e=s.length,n!==null?{text:n,raw:s}:null},close:()=>{}}},Bo=n=>{let e=null,s=0,r=n||(o=>{if(!o||typeof o!="object")return null;let i=l=>typeof l=="string"?Mn(l):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Mn(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:()=>e,processChunk:o=>{let i=o.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(o.length<=s)return e!==null?{text:e,raw:o}:null;try{let l=(0,Lt.parse)(o,Lt.STR|Lt.OBJ),c=r(l);c!==null&&(e=c)}catch{}return s=o.length,{text:e||"",raw:o}},close:()=>{}}},Hn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var ar="https://api.travrse.ai/v1/dispatch",Ho="https://api.travrse.ai";function lr(n){switch(n){case"json":return Bn;case"regex-json":return Ln;case"xml":return Hn;case"plain":default:return kn}}var Jt=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;var s,t,r;this.apiUrl=(s=e.apiUrl)!=null?s:ar,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:lr(e.parserType),this.contextProviders=(r=e.contextProviders)!=null?r:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(e){var t;let s=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ho;return e==="init"?`${s}/v1/client/init`:`${s}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var e,s;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(s=(e=this.config).onSessionInit)==null||s.call(e,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.clientToken,flow_id:this.config.flowId})});if(!e.ok){let t=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${t.hint||t.error}`):e.status===403?new Error(`Origin not allowed: ${t.hint||t.error}`):new Error(t.error||"Failed to initialize session")}let s=await e.json();return{sessionId:s.session_id,expiresAt:new Date(s.expires_at),flow:s.flow,config:{welcomeMessage:s.config.welcome_message,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var s;return`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ho}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.message_id)throw new Error(`message_id is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(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(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:e,type:s})}async submitCSATFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:e,comment:s})}async submitNPSFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:e,comment:s})}async dispatch(e,s){return this.isClientTokenMode()?this.dispatchClientToken(e,s):this.dispatchProxy(e,s)}async dispatchClientToken(e,s){var r,o,i,l;let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),s({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(r=this.config).onSessionExpired)==null||o.call(r);let u=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:u}),u}let d=await this.buildPayload(e.messages),f={session_id:c.sessionId,messages:e.messages.map(u=>({id:u.id,role:u.role,content:u.rawContent||u.content})),...e.assistantMessageId&&{assistant_message_id:e.assistantMessageId},...d.metadata&&{metadata:d.metadata},...d.context&&{context:d.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",f);let w=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f),signal:t.signal});if(!w.ok){let u=await w.json().catch(()=>({error:"Chat request failed"}));if(w.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let g=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:g}),g}if(w.status===429){let g=new Error(u.hint||"Message limit reached for this session.");throw s({type:"error",error:g}),g}let C=new Error(u.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!w.body){let u=new Error("No response body received");throw s({type:"error",error:u}),u}s({type:"status",status:"connected"});try{await this.streamResponse(w.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&s({type:"error",error:d}),d}}async dispatchProxy(e,s){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),s({type:"status",status:"connecting"});let r=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();o={...o,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal},r)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw s({type:"error",error:c}),c}else i=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.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(e){let t={messages:e.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:e,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(e,s,t,r,o){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let c={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return t.current=c,r(c),c};if(i.text!==void 0){let c=l();c.content+=i.text,r(c)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.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(e,s,t){var re,q,qe,Ve,nt,bt,Ct,Y,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,Ie,ot,Ue,R,dt,Se,Oe,te,Ae,Te,ze,Ye,xt,Bt,yt,Et,St,ye,Ht,Le,Je,At,Dt,Mt,jt,Wt,Cn,xn,Sn,Jn,_t,qt,Ke,Xt,cn,un,pn;let r=e.getReader(),o=new TextDecoder,i="",l=Date.now(),c=0,d=()=>l+c++,f=A=>{let V=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,ie=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,ve=A.tools?A.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...A,reasoning:V,toolCall:ie,tools:ve}},w=A=>{s({type:"message",message:f(A)})},u=null,C={current:null},g=new Map,U=new Map,I={lastId:null,byStep:new Map},h={lastId:null,byCall:new Map},b=A=>{if(A==null)return null;try{return String(A)}catch{return null}},W=A=>{var V,ie,ve,Fe,Ne;return b((Ne=(Fe=(ve=(ie=(V=A.stepId)!=null?V:A.step_id)!=null?ie:A.step)!=null?ve:A.parentId)!=null?Fe:A.flowStepId)!=null?Ne:A.flow_step_id)},v=A=>{var V,ie,ve,Fe,Ne,ue,$;return b(($=(ue=(Ne=(Fe=(ve=(ie=(V=A.callId)!=null?V:A.call_id)!=null?ie:A.requestId)!=null?ve:A.request_id)!=null?Fe:A.toolCallId)!=null?Ne:A.tool_call_id)!=null?ue:A.stepId)!=null?$:A.step_id)},D=()=>u||(u={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},w(u),u),x=(A,V)=>{I.lastId=V,A&&I.byStep.set(A,V)},S=(A,V)=>{var Ne;let ie=(Ne=A.reasoningId)!=null?Ne:A.id,ve=W(A);if(ie){let ue=String(ie);return x(ve,ue),ue}if(ve){let ue=I.byStep.get(ve);if(ue)return I.lastId=ue,ue}if(I.lastId&&!V)return I.lastId;if(!V)return null;let Fe=`reason-${d()}`;return x(ve,Fe),Fe},X=A=>{let V=g.get(A);if(V)return V;let ie={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:A,status:"streaming",chunks:[]}};return g.set(A,ie),w(ie),ie},B=(A,V)=>{h.lastId=V,A&&h.byCall.set(A,V)},j=(A,V)=>{var Ne;let ie=(Ne=A.toolId)!=null?Ne:A.id,ve=v(A);if(ie){let ue=String(ie);return B(ve,ue),ue}if(ve){let ue=h.byCall.get(ve);if(ue)return h.lastId=ue,ue}if(h.lastId&&!V)return h.lastId;if(!V)return null;let Fe=`tool-${d()}`;return B(ve,Fe),Fe},Z=A=>{let V=U.get(A);if(V)return V;let ie={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:A,status:"pending"}};return U.set(A,ie),w(ie),ie},_=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let V=Number(A);if(!Number.isNaN(V)&&Number.isFinite(V))return V;let ie=Date.parse(A);if(!Number.isNaN(ie))return ie}return Date.now()},K=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},Q=new Map,ne=new Map;for(;;){let{done:A,value:V}=await r.read();if(A)break;i+=o.decode(V,{stream:!0});let ie=i.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let o=s(t);return o!==null&&(n=o),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},An=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Tn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},En=()=>{var e;let n=mr();return{processChunk:async s=>{let t=s.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(s)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Mn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:s=>{let t=s.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(s.length<=e)return n!==null||n===""?{text:n||"",raw:s}:null;try{let r=(0,Wt.parse)(s,Wt.STR|Wt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?Sn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=Sn(r.text)))}catch{}return e=s.length,n!==null?{text:n,raw:s}:null},close:()=>{}}},Fo=n=>{let e=null,s=0,r=n||(o=>{if(!o||typeof o!="object")return null;let i=l=>typeof l=="string"?Sn(l):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Sn(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return 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:()=>e,processChunk:o=>{let i=o.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(o.length<=s)return e!==null?{text:e,raw:o}:null;try{let l=(0,Wt.parse)(o,Wt.STR|Wt.OBJ),d=r(l);d!==null&&(e=d)}catch{}return s=o.length,{text:e||"",raw:o}},close:()=>{}}},kn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var hr="https://api.travrse.ai/v1/dispatch",No="https://api.travrse.ai";function fr(n){switch(n){case"json":return Mn;case"regex-json":return En;case"xml":return kn;case"plain":default:return Tn}}var Yt=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;var s,t,r;this.apiUrl=(s=e.apiUrl)!=null?s:hr,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:fr(e.parserType),this.contextProviders=(r=e.contextProviders)!=null?r:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(e){var t;let s=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||No;return e==="init"?`${s}/v1/client/init`:`${s}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var e,s;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(s=(e=this.config).onSessionInit)==null||s.call(e,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.clientToken,flow_id:this.config.flowId})});if(!e.ok){let t=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${t.hint||t.error}`):e.status===403?new Error(`Origin not allowed: ${t.hint||t.error}`):new Error(t.error||"Failed to initialize session")}let s=await e.json();return{sessionId:s.session_id,expiresAt:new Date(s.expires_at),flow:s.flow,config:{welcomeMessage:s.config.welcome_message,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var s;return`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||No}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.message_id)throw new Error(`message_id is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(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(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:e,type:s})}async submitCSATFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:e,comment:s})}async submitNPSFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:e,comment:s})}async dispatch(e,s){return this.isClientTokenMode()?this.dispatchClientToken(e,s):this.dispatchProxy(e,s)}async dispatchClientToken(e,s){var r,o,i,l;let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.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 u=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:u}),u}let c=await this.buildPayload(e.messages),w={session_id:d.sessionId,messages:e.messages.map(u=>({id:u.id,role:u.role,content:u.rawContent||u.content})),...e.assistantMessageId&&{assistant_message_id:e.assistantMessageId},...c.metadata&&{metadata:c.metadata},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w);let y=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:t.signal});if(!y.ok){let u=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let g=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:g}),g}if(y.status===429){let g=new Error(u.hint||"Message limit reached for this session.");throw s({type:"error",error:g}),g}let C=new Error(u.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!y.body){let u=new Error("No response body received");throw s({type:"error",error:u}),u}s({type:"status",status:"connected"});try{await this.streamResponse(y.body,s,e.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(e,s){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),s({type:"status",status:"connecting"});let r=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();o={...o,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.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:t.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(e){let t={messages:e.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:e,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(e,s,t,r,o){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let 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 t.current=d,r(d),d};if(i.text!==void 0){let d=l();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.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(e,s,t){var de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye,E,$e,V,Le,Ie,Fe,Ne,ut,At,vt,Lt,Bt,Dt,Et,Z,pt,bt,gt,Ht,hn,rn,_t,Mt,fn,wn,yn,Kn,jt,qt,Ke,Xt,an;let r=e.getReader(),o=new TextDecoder,i="",l=Date.now(),d=0,c=()=>l+d++,w=M=>{let ce=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,se=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,me=M.tools?M.tools.map(Se=>({...Se,chunks:Se.chunks?[...Se.chunks]:void 0})):void 0;return{...M,reasoning:ce,toolCall:se,tools:me}},y=M=>{s({type:"message",message:w(M)})},u=null,C={current:null},g=new Map,j=new Map,$={lastId:null,byStep:new Map},m={lastId:null,byCall:new Map},b=M=>{if(M==null)return null;try{return String(M)}catch{return null}},W=M=>{var ce,se,me,Se,Ee;return b((Ee=(Se=(me=(se=(ce=M.stepId)!=null?ce:M.step_id)!=null?se:M.step)!=null?me:M.parentId)!=null?Se:M.flowStepId)!=null?Ee:M.flow_step_id)},v=M=>{var ce,se,me,Se,Ee,Me,L;return b((L=(Me=(Ee=(Se=(me=(se=(ce=M.callId)!=null?ce:M.call_id)!=null?se:M.requestId)!=null?me:M.request_id)!=null?Se:M.toolCallId)!=null?Ee:M.tool_call_id)!=null?Me:M.stepId)!=null?L:M.step_id)},N=()=>u||(u={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},y(u),u),x=(M,ce)=>{$.lastId=ce,M&&$.byStep.set(M,ce)},S=(M,ce)=>{var Ee;let se=(Ee=M.reasoningId)!=null?Ee:M.id,me=W(M);if(se){let Me=String(se);return x(me,Me),Me}if(me){let Me=$.byStep.get(me);if(Me)return $.lastId=Me,Me}if($.lastId&&!ce)return $.lastId;if(!ce)return null;let Se=`reason-${c()}`;return x(me,Se),Se},Y=M=>{let ce=g.get(M);if(ce)return ce;let se={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return g.set(M,se),y(se),se},R=(M,ce)=>{m.lastId=ce,M&&m.byCall.set(M,ce)},O=(M,ce)=>{var Ee;let se=(Ee=M.toolId)!=null?Ee:M.id,me=v(M);if(se){let Me=String(se);return R(me,Me),Me}if(me){let Me=m.byCall.get(me);if(Me)return m.lastId=Me,Me}if(m.lastId&&!ce)return m.lastId;if(!ce)return null;let Se=`tool-${c()}`;return R(me,Se),Se},G=M=>{let ce=j.get(M);if(ce)return ce;let se={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return j.set(M,se),y(se),se},D=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ce=Number(M);if(!Number.isNaN(ce)&&Number.isFinite(ce))return ce;let se=Date.parse(M);if(!Number.isNaN(se))return se}return Date.now()},U=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},Q=new Map,ie=new Map;for(;;){let{done:M,value:ce}=await r.read();if(M)break;i+=o.decode(ce,{stream:!0});let se=i.split(`
5
5
 
6
- `);i=(re=ie.pop())!=null?re:"";for(let ve of ie){let Fe=ve.split(`
7
- `),Ne="message",ue="";for(let se of Fe)se.startsWith("event:")?Ne=se.replace("event:","").trim():se.startsWith("data:")&&(ue+=se.replace("data:","").trim());if(!ue)continue;let $;try{$=JSON.parse(ue)}catch(se){s({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let rt=Ne!=="message"?Ne:(q=$.type)!=null?q:"message";if(this.parseSSEEvent){C.current=u;let se=await this.handleCustomSSEEvent($,s,C,w,d);if(C.current&&!u&&(u=C.current),se)continue}if(rt==="reason_start"){let se=(qe=S($,!0))!=null?qe:`reason-${d()}`,M=X(se);M.reasoning=(Ve=M.reasoning)!=null?Ve:{id:se,status:"streaming",chunks:[]},M.reasoning.startedAt=(bt=M.reasoning.startedAt)!=null?bt:_((nt=$.startedAt)!=null?nt:$.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",w(M)}else if(rt==="reason_chunk"){let se=(Y=(Ct=S($,!1))!=null?Ct:S($,!0))!=null?Y:`reason-${d()}`,M=X(se);M.reasoning=(fe=M.reasoning)!=null?fe:{id:se,status:"streaming",chunks:[]},M.reasoning.startedAt=(ft=M.reasoning.startedAt)!=null?ft:_((mt=$.startedAt)!=null?mt:$.timestamp);let y=(H=(st=(Ge=$.reasoningText)!=null?Ge:$.text)!=null?st:$.delta)!=null?H:"";if(y&&$.hidden!==!0&&M.reasoning.chunks.push(String(y)),M.reasoning.status=$.done?"complete":"streaming",$.done){M.reasoning.completedAt=_((He=$.completedAt)!=null?He:$.timestamp);let F=(at=M.reasoning.startedAt)!=null?at:Date.now();M.reasoning.durationMs=Math.max(0,((lt=M.reasoning.completedAt)!=null?lt:Date.now())-F)}M.streaming=M.reasoning.status!=="complete",w(M)}else if(rt==="reason_complete"){let se=(wt=(Tt=S($,!1))!=null?Tt:S($,!0))!=null?wt:`reason-${d()}`,M=g.get(se);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=_((Ie=$.completedAt)!=null?Ie:$.timestamp);let F=(ot=M.reasoning.startedAt)!=null?ot:Date.now();M.reasoning.durationMs=Math.max(0,((Ue=M.reasoning.completedAt)!=null?Ue:Date.now())-F),M.streaming=!1,w(M)}let y=W($);y&&I.byStep.delete(y)}else if(rt==="tool_start"){let se=(R=j($,!0))!=null?R:`tool-${d()}`,M=Z(se),y=(dt=M.toolCall)!=null?dt:{id:se,status:"pending"};y.name=(Se=$.toolName)!=null?Se:y.name,y.status="running",$.args!==void 0&&(y.args=$.args),y.startedAt=(te=y.startedAt)!=null?te:_((Oe=$.startedAt)!=null?Oe:$.timestamp),y.completedAt=void 0,y.durationMs=void 0,M.toolCall=y,M.streaming=!0,w(M)}else if(rt==="tool_chunk"){let se=(Te=(Ae=j($,!1))!=null?Ae:j($,!0))!=null?Te:`tool-${d()}`,M=Z(se),y=(ze=M.toolCall)!=null?ze:{id:se,status:"running"};y.startedAt=(xt=y.startedAt)!=null?xt:_((Ye=$.startedAt)!=null?Ye:$.timestamp);let F=(Et=(yt=(Bt=$.text)!=null?Bt:$.delta)!=null?yt:$.message)!=null?Et:"";F&&(y.chunks=(St=y.chunks)!=null?St:[],y.chunks.push(String(F))),y.status="running",M.toolCall=y,M.streaming=!0,w(M)}else if(rt==="tool_complete"){let se=(Ht=(ye=j($,!1))!=null?ye:j($,!0))!=null?Ht:`tool-${d()}`,M=Z(se),y=(Le=M.toolCall)!=null?Le:{id:se,status:"running"};if(y.status="complete",$.result!==void 0&&(y.result=$.result),typeof $.duration=="number"&&(y.duration=$.duration),y.completedAt=_((Je=$.completedAt)!=null?Je:$.timestamp),typeof $.duration=="number")y.durationMs=$.duration;else{let be=(At=y.startedAt)!=null?At:Date.now();y.durationMs=Math.max(0,((Dt=y.completedAt)!=null?Dt:Date.now())-be)}M.toolCall=y,M.streaming=!1,w(M);let F=v($);F&&h.byCall.delete(F)}else if(rt==="step_chunk"){let se=$.stepType,M=$.executionType;if(se==="tool"||M==="context")continue;let y=D(),F=(Cn=(Wt=(jt=(Mt=$.text)!=null?Mt:$.delta)!=null?jt:$.content)!=null?Wt:$.chunk)!=null?Cn:"";if(F){let Ee=((xn=ne.get(y.id))!=null?xn:"")+F;y.rawContent=Ee,Q.has(y.id)||Q.set(y.id,this.createStreamParser());let Ze=Q.get(y.id),$e=Ee.trim().startsWith("{")||Ee.trim().startsWith("[");if($e&&ne.set(y.id,Ee),Ze.__isPlainTextParser===!0){y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y);continue}let je=Ze.processChunk(Ee);if(je instanceof Promise)je.then(de=>{var Pe;let pe=typeof de=="string"?de:(Pe=de==null?void 0:de.text)!=null?Pe:null;if(pe!==null&&pe.trim()!==""){let ge=u;ge&&ge.id===y.id&&(ge.content=pe,w(ge))}else if(!$e&&!Ee.trim().startsWith("<")){let ge=u;ge&&ge.id===y.id&&(ge.content+=F,ne.delete(ge.id),Q.delete(ge.id),ge.rawContent=void 0,w(ge))}}).catch(()=>{y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y)});else{let de=typeof je=="string"?je:(Sn=je==null?void 0:je.text)!=null?Sn:null;de!==null&&de.trim()!==""?(y.content=de,w(y)):!$e&&!Ee.trim().startsWith("<")&&(y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y))}}if($.isComplete){let be=(_t=(Jn=$.result)==null?void 0:Jn.response)!=null?_t:y.content;if(be){let Ee=ne.get(y.id),Ze=Ee!=null?Ee:K(be);y.rawContent=Ze;let $e=Q.get(y.id),Ce=null,je=!1;if($e&&(Ce=$e.getExtractedText(),Ce===null&&(Ce=Wn(Ze)),Ce===null)){let de=$e.processChunk(Ze);de instanceof Promise?(je=!0,de.then(pe=>{var ge;let Pe=typeof pe=="string"?pe:(ge=pe==null?void 0:pe.text)!=null?ge:null;if(Pe!==null){let De=u;De&&De.id===y.id&&(De.content=Pe,De.streaming=!1,Q.delete(De.id),ne.delete(De.id),w(De))}})):Ce=typeof de=="string"?de:(qt=de==null?void 0:de.text)!=null?qt:null}if(!je){Ce!==null&&Ce.trim()!==""?y.content=Ce:ne.has(y.id)||(y.content=K(be));let de=Q.get(y.id);if(de){let pe=(Ke=de.close)==null?void 0:Ke.call(de);pe instanceof Promise&&pe.catch(()=>{}),Q.delete(y.id)}ne.delete(y.id),y.streaming=!1,w(y)}}}}else if(rt==="step_complete"){let se=$.stepType,M=$.executionType;if(se==="tool"||M==="context")continue;let y=(Xt=$.result)==null?void 0:Xt.response,F=D();if(y!=null){let be=Q.get(F.id),Ee=!1,Ze=!1;if(be){let $e=be.getExtractedText(),Ce=ne.get(F.id),je=Ce!=null?Ce:K(y);if(F.rawContent=je,$e!==null&&$e.trim()!=="")F.content=$e,Ee=!0;else{let de=Wn(je);if(de!==null)F.content=de,Ee=!0;else{let pe=be.processChunk(je);if(pe instanceof Promise)Ze=!0,pe.then(Pe=>{var De;let ge=typeof Pe=="string"?Pe:(De=Pe==null?void 0:Pe.text)!=null?De:null;if(ge!==null&&ge.trim()!==""){let it=u;it&&it.id===F.id&&(it.content=ge,it.streaming=!1,Q.delete(it.id),ne.delete(it.id),w(it))}else{let it=be.getExtractedText(),ht=u;ht&&ht.id===F.id&&(it!==null&&it.trim()!==""?ht.content=it:ne.has(ht.id)||(ht.content=K(y)),ht.streaming=!1,Q.delete(ht.id),ne.delete(ht.id),w(ht))}});else{let Pe=typeof pe=="string"?pe:(cn=pe==null?void 0:pe.text)!=null?cn:null;if(Pe!==null&&Pe.trim()!=="")F.content=Pe,Ee=!0;else{let ge=be.getExtractedText();ge!==null&&ge.trim()!==""&&(F.content=ge,Ee=!0)}}}}}if(!Ze){if(!F.rawContent){let $e=ne.get(F.id);F.rawContent=$e!=null?$e:K(y)}if(!Ee&&!ne.has(F.id)&&(F.content=K(y)),be){let $e=(un=be.close)==null?void 0:un.call(be);$e instanceof Promise&&$e.catch(()=>{})}Q.delete(F.id),ne.delete(F.id),F.streaming=!1,w(F)}}else Q.delete(F.id),ne.delete(F.id),F.streaming=!1,w(F)}else if(rt==="flow_complete"){let se=(pn=$.result)==null?void 0:pn.response;if(se!=null){let M=D(),y=ne.get(M.id),F=y!=null?y:K(se);M.rawContent=F;let be=K(se),Ee=Q.get(M.id);if(Ee){let Ce=Wn(F);if(Ce!==null)be=Ce;else{let je=Ee.processChunk(F);je instanceof Promise&&je.then(pe=>{var ge;let Pe=typeof pe=="string"?pe:(ge=pe==null?void 0:pe.text)!=null?ge:null;if(Pe!==null){let De=u;De&&De.id===M.id&&(De.content=Pe,De.streaming=!1,w(De))}});let de=Ee.getExtractedText();de!==null&&(be=de)}}Q.delete(M.id),ne.delete(M.id);let Ze=be!==M.content,$e=M.streaming!==!1;Ze&&(M.content=be),M.streaming=!1,(Ze||$e)&&w(M)}else if(u!==null){let M=u;Q.delete(M.id),ne.delete(M.id),M.streaming!==!1&&(M.streaming=!1,w(M))}s({type:"status",status:"idle"})}else rt==="error"&&$.error&&s({type:"error",error:$.error instanceof Error?$.error:new Error(String($.error))})}}}};function $o(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${n}_${e}`}function $n(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Pn(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Zt=class{constructor(e={},s){this.config=e;this.callbacks=s;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=e=>{var s,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(s=this.callbacks).onError)==null||t.call(s,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(r=>{var o;return{...r,sequence:(o=r.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Jt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var e,s;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(s=(e=this.callbacks).onError)==null||s.call(e,t instanceof Error?t:new Error(String(t))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(s)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,s){return this.client.submitMessageFeedback(e,s)}async submitCSATFeedback(e,s){return this.client.submitCSATFeedback(e,s)}async submitNPSFeedback(e,s){return this.client.submitNPSFeedback(e,s)}updateConfig(e){this.config={...this.config,...e},this.client=new Jt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,s){var d,f,w,u,C;let t=e.trim();if(!t)return;(d=this.abortController)==null||d.abort();let r=$n(),o=Pn(),i={id:r,role:"user",content:t,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 c=[...this.messages];try{await this.client.dispatch({messages:c,signal:l.signal,assistantMessageId:o},this.handleEvent)}catch(g){let U={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(U),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(w=(f=this.callbacks).onError)==null||w.call(f,g):(C=(u=this.callbacks).onError)==null||C.call(u,new Error(String(g)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let s=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,s]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let s=this.ensureSequence(e),t=this.messages.findIndex(r=>r.id===s.id);if(t===-1){this.appendMessage(s);return}this.messages=this.messages.map((r,o)=>o===t?{...r,...s}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((s,t)=>{var c,d;let r=new Date(s.createdAt).getTime(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let i=(c=s.sequence)!=null?c:0,l=(d=t.sequence)!=null?d:0;return i!==l?i-l:s.id.localeCompare(t.id)})}};var Gn=(n,e)=>{var t;let s=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(s).forEach(([r,o])=>{if(o==null||o==="")return;let i=r.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(o))})};var dr=er(require("lucide"),1),ce=(n,e=24,s="currentColor",t=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),o=dr[r];return o?cr(o,e,s,t):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function cr(n,e,s,t){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",s),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let i=o[0],l=o[1];if(l){let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([d,f])=>{d!=="stroke"&&c.setAttribute(d,String(f))}),r.appendChild(c)}}}),r}var m=(n,e)=>{let s=document.createElement(n);return e&&(s.className=e),s};var Xe={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var vt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var fn=(n,e)=>{let s=m("button");s.type="button",s.innerHTML=`
6
+ `);i=(de=se.pop())!=null?de:"";for(let me of se){let Se=me.split(`
7
+ `),Ee="message",Me="";for(let ae of Se)ae.startsWith("event:")?Ee=ae.replace("event:","").trim():ae.startsWith("data:")&&(Me+=ae.replace("data:","").trim());if(!Me)continue;let L;try{L=JSON.parse(Me)}catch(ae){s({type:"error",error:ae instanceof Error?ae:new Error("Failed to parse chat stream payload")});continue}let Oe=Ee!=="message"?Ee:(_=L.type)!=null?_:"message";if(this.parseSSEEvent){C.current=u;let ae=await this.handleCustomSSEEvent(L,s,C,y,c);if(C.current&&!u&&(u=C.current),ae)continue}if(Oe==="reason_start"){let ae=(ze=S(L,!0))!=null?ze:`reason-${c()}`,k=Y(ae);k.reasoning=(Ge=k.reasoning)!=null?Ge:{id:ae,status:"streaming",chunks:[]},k.reasoning.startedAt=(xt=k.reasoning.startedAt)!=null?xt:D((nt=L.startedAt)!=null?nt:L.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",y(k)}else if(Oe==="reason_chunk"){let ae=(q=(St=S(L,!1))!=null?St:S(L,!0))!=null?q:`reason-${c()}`,k=Y(ae);k.reasoning=(ve=k.reasoning)!=null?ve:{id:ae,status:"streaming",chunks:[]},k.reasoning.startedAt=(ft=k.reasoning.startedAt)!=null?ft:D((ht=L.startedAt)!=null?ht:L.timestamp);let A=(I=(st=(Qe=L.reasoningText)!=null?Qe:L.text)!=null?st:L.delta)!=null?I:"";if(A&&L.hidden!==!0&&k.reasoning.chunks.push(String(A)),k.reasoning.status=L.done?"complete":"streaming",L.done){k.reasoning.completedAt=D((Be=L.completedAt)!=null?Be:L.timestamp);let z=(at=k.reasoning.startedAt)!=null?at:Date.now();k.reasoning.durationMs=Math.max(0,((lt=k.reasoning.completedAt)!=null?lt:Date.now())-z)}k.streaming=k.reasoning.status!=="complete",y(k)}else if(Oe==="reason_complete"){let ae=(wt=(Tt=S(L,!1))!=null?Tt:S(L,!0))!=null?wt:`reason-${c()}`,k=g.get(ae);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=D((He=L.completedAt)!=null?He:L.timestamp);let z=(Je=k.reasoning.startedAt)!=null?Je:Date.now();k.reasoning.durationMs=Math.max(0,((yt=k.reasoning.completedAt)!=null?yt:Date.now())-z),k.streaming=!1,y(k)}let A=W(L);A&&$.byStep.delete(A)}else if(Oe==="tool_start"){let ae=(ot=O(L,!0))!=null?ot:`tool-${c()}`,k=G(ae),A=(Ye=k.toolCall)!=null?Ye:{id:ae,status:"pending"};A.name=(E=L.toolName)!=null?E:A.name,A.status="running",L.args!==void 0&&(A.args=L.args),A.startedAt=(V=A.startedAt)!=null?V:D(($e=L.startedAt)!=null?$e:L.timestamp),A.completedAt=void 0,A.durationMs=void 0,k.toolCall=A,k.streaming=!0,y(k)}else if(Oe==="tool_chunk"){let ae=(Ie=(Le=O(L,!1))!=null?Le:O(L,!0))!=null?Ie:`tool-${c()}`,k=G(ae),A=(Fe=k.toolCall)!=null?Fe:{id:ae,status:"running"};A.startedAt=(ut=A.startedAt)!=null?ut:D((Ne=L.startedAt)!=null?Ne:L.timestamp);let z=(Lt=(vt=(At=L.text)!=null?At:L.delta)!=null?vt:L.message)!=null?Lt:"";z&&(A.chunks=(Bt=A.chunks)!=null?Bt:[],A.chunks.push(String(z))),A.status="running",k.toolCall=A,k.streaming=!0,y(k)}else if(Oe==="tool_complete"){let ae=(Et=(Dt=O(L,!1))!=null?Dt:O(L,!0))!=null?Et:`tool-${c()}`,k=G(ae),A=(Z=k.toolCall)!=null?Z:{id:ae,status:"running"};if(A.status="complete",L.result!==void 0&&(A.result=L.result),typeof L.duration=="number"&&(A.duration=L.duration),A.completedAt=D((pt=L.completedAt)!=null?pt:L.timestamp),typeof L.duration=="number")A.durationMs=L.duration;else{let K=(bt=A.startedAt)!=null?bt:Date.now();A.durationMs=Math.max(0,((gt=A.completedAt)!=null?gt:Date.now())-K)}k.toolCall=A,k.streaming=!1,y(k);let z=v(L);z&&m.byCall.delete(z)}else if(Oe==="step_chunk"){let ae=L.stepType,k=L.executionType;if(ae==="tool"||k==="context")continue;let A=N(),z=(_t=(rn=(hn=(Ht=L.text)!=null?Ht:L.delta)!=null?hn:L.content)!=null?rn:L.chunk)!=null?_t:"";if(z){let X=((Mt=ie.get(A.id))!=null?Mt:"")+z;A.rawContent=X,Q.has(A.id)||Q.set(A.id,this.createStreamParser());let je=Q.get(A.id),ke=X.trim().startsWith("{")||X.trim().startsWith("[");if(ke&&ie.set(A.id,X),je.__isPlainTextParser===!0){A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A);continue}let qe=je.processChunk(X);if(qe instanceof Promise)qe.then(re=>{var Re;let Ce=typeof re=="string"?re:(Re=re==null?void 0:re.text)!=null?Re:null;if(Ce!==null&&Ce.trim()!==""){let fe=u;fe&&fe.id===A.id&&(fe.content=Ce,y(fe))}else if(!ke&&!X.trim().startsWith("<")){let fe=u;fe&&fe.id===A.id&&(fe.content+=z,ie.delete(fe.id),Q.delete(fe.id),fe.rawContent=void 0,y(fe))}}).catch(()=>{A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A)});else{let re=typeof qe=="string"?qe:(fn=qe==null?void 0:qe.text)!=null?fn:null;re!==null&&re.trim()!==""?(A.content=re,y(A)):!ke&&!X.trim().startsWith("<")&&(A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A))}}if(L.isComplete){let K=(yn=(wn=L.result)==null?void 0:wn.response)!=null?yn:A.content;if(K){let X=ie.get(A.id),je=X!=null?X:U(K);A.rawContent=je;let ke=Q.get(A.id),De=null,qe=!1;if(ke&&(De=ke.getExtractedText(),De===null&&(De=An(je)),De===null)){let re=ke.processChunk(je);re instanceof Promise?(qe=!0,re.then(Ce=>{var fe;let Re=typeof Ce=="string"?Ce:(fe=Ce==null?void 0:Ce.text)!=null?fe:null;if(Re!==null){let _e=u;_e&&_e.id===A.id&&(_e.content=Re,_e.streaming=!1,Q.delete(_e.id),ie.delete(_e.id),y(_e))}})):De=typeof re=="string"?re:(Kn=re==null?void 0:re.text)!=null?Kn:null}if(!qe){De!==null&&De.trim()!==""?A.content=De:ie.has(A.id)||(A.content=U(K));let re=Q.get(A.id);if(re){let Ce=(jt=re.close)==null?void 0:jt.call(re);Ce instanceof Promise&&Ce.catch(()=>{}),Q.delete(A.id)}ie.delete(A.id),A.streaming=!1,y(A)}}}}else if(Oe==="step_complete"){let ae=L.stepType,k=L.executionType;if(ae==="tool"||k==="context")continue;let A=(qt=L.result)==null?void 0:qt.response,z=N();if(A!=null){let K=Q.get(z.id),X=!1,je=!1;if(K){let ke=K.getExtractedText(),De=ie.get(z.id),qe=De!=null?De:U(A);if(z.rawContent=qe,ke!==null&&ke.trim()!=="")z.content=ke,X=!0;else{let re=An(qe);if(re!==null)z.content=re,X=!0;else{let Ce=K.processChunk(qe);if(Ce instanceof Promise)je=!0,Ce.then(Re=>{var _e;let fe=typeof Re=="string"?Re:(_e=Re==null?void 0:Re.text)!=null?_e:null;if(fe!==null&&fe.trim()!==""){let rt=u;rt&&rt.id===z.id&&(rt.content=fe,rt.streaming=!1,Q.delete(rt.id),ie.delete(rt.id),y(rt))}else{let rt=K.getExtractedText(),mt=u;mt&&mt.id===z.id&&(rt!==null&&rt.trim()!==""?mt.content=rt:ie.has(mt.id)||(mt.content=U(A)),mt.streaming=!1,Q.delete(mt.id),ie.delete(mt.id),y(mt))}});else{let Re=typeof Ce=="string"?Ce:(Ke=Ce==null?void 0:Ce.text)!=null?Ke:null;if(Re!==null&&Re.trim()!=="")z.content=Re,X=!0;else{let fe=K.getExtractedText();fe!==null&&fe.trim()!==""&&(z.content=fe,X=!0)}}}}}if(!je){if(!z.rawContent){let ke=ie.get(z.id);z.rawContent=ke!=null?ke:U(A)}if(!X&&!ie.has(z.id)&&(z.content=U(A)),K){let ke=(Xt=K.close)==null?void 0:Xt.call(K);ke instanceof Promise&&ke.catch(()=>{})}Q.delete(z.id),ie.delete(z.id),z.streaming=!1,y(z)}}else Q.delete(z.id),ie.delete(z.id),z.streaming=!1,y(z)}else if(Oe==="flow_complete"){let ae=(an=L.result)==null?void 0:an.response;if(ae!=null){let k=N(),A=ie.get(k.id),z=A!=null?A:U(ae);k.rawContent=z;let K=U(ae),X=Q.get(k.id);if(X){let De=An(z);if(De!==null)K=De;else{let qe=X.processChunk(z);qe instanceof Promise&&qe.then(Ce=>{var fe;let Re=typeof Ce=="string"?Ce:(fe=Ce==null?void 0:Ce.text)!=null?fe:null;if(Re!==null){let _e=u;_e&&_e.id===k.id&&(_e.content=Re,_e.streaming=!1,y(_e))}});let re=X.getExtractedText();re!==null&&(K=re)}}Q.delete(k.id),ie.delete(k.id);let je=K!==k.content,ke=k.streaming!==!1;je&&(k.content=K),k.streaming=!1,(je||ke)&&y(k)}else if(u!==null){let k=u;Q.delete(k.id),ie.delete(k.id),k.streaming!==!1&&(k.streaming=!1,y(k))}s({type:"status",status:"idle"})}else Oe==="error"&&L.error&&s({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};function Oo(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${n}_${e}`}function Wn(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Ln(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Qt=class{constructor(e={},s){this.config=e;this.callbacks=s;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=e=>{var s,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(s=this.callbacks).onError)==null||t.call(s,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(r=>{var o;return{...r,sequence:(o=r.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var e,s;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(s=(e=this.callbacks).onError)==null||s.call(e,t instanceof Error?t:new Error(String(t))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(s)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,s){return this.client.submitMessageFeedback(e,s)}async submitCSATFeedback(e,s){return this.client.submitCSATFeedback(e,s)}async submitNPSFeedback(e,s){return this.client.submitNPSFeedback(e,s)}updateConfig(e){this.config={...this.config,...e},this.client=new Yt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,s){var c,w,y,u,C;let t=e.trim();if(!t)return;(c=this.abortController)==null||c.abort();let r=Wn(),o=Ln(),i={id:r,role:"user",content:t,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(g){let j={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(j),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(y=(w=this.callbacks).onError)==null||y.call(w,g):(C=(u=this.callbacks).onError)==null||C.call(u,new Error(String(g)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let s=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,s]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let s=this.ensureSequence(e),t=this.messages.findIndex(r=>r.id===s.id);if(t===-1){this.appendMessage(s);return}this.messages=this.messages.map((r,o)=>o===t?{...r,...s}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((s,t)=>{var d,c;let r=new Date(s.createdAt).getTime(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let i=(d=s.sequence)!=null?d:0,l=(c=t.sequence)!=null?c:0;return i!==l?i-l:s.id.localeCompare(t.id)})}};var Qn=()=>{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"},wr=n=>{var o,i,l;let e=(o=n==null?void 0:n.colorScheme)!=null?o:"light",s=(i=n==null?void 0:n.theme)!=null?i:{},t=(l=n==null?void 0:n.darkTheme)!=null?l:s;return e==="light"?s:e==="dark"||Qn()==="dark"?t:s},Do=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let s=new MutationObserver(()=>{n(Qn())});s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>s.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let s=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>n(Qn());s.addEventListener?(s.addEventListener("change",t),e.push(()=>s.removeEventListener("change",t))):s.addListener&&(s.addListener(t),e.push(()=>s.removeListener(t)))}return()=>{e.forEach(s=>s())}},Bn=(n,e)=>{let s=wr(e);Object.entries(s).forEach(([t,r])=>{if(r==null||r==="")return;let o=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${o}`,String(r))})};var yr=lr(require("lucide"),1),ge=(n,e=24,s="currentColor",t=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),o=yr[r];return o?vr(o,e,s,t):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function vr(n,e,s,t){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",s),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let 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 f=(n,e)=>{let s=document.createElement(n);return e&&(s.className=e),s};var Ve={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ct={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var cn=(n,e)=>{let s=f("button");s.type="button",s.innerHTML=`
8
8
  <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
10
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -12,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",e);let t=o=>{var h,b,W,v,D,x,S,X,B,j,Z,_;let i=(h=o.launcher)!=null?h:{},l=s.querySelector("[data-role='launcher-title']");l&&(l.textContent=(b=i.title)!=null?b:"Chat Assistant");let c=s.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(W=i.subtitle)!=null?W:"Get answers fast");let d=s.querySelector(".tvw-flex-col");d&&(i.textHidden?d.style.display="none":d.style.display="");let f=s.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let K=(v=i.agentIconSize)!=null?v:"40px";if(f.style.height=K,f.style.width=K,f.innerHTML="",i.agentIconName){let Q=parseFloat(K)||24,ne=ce(i.agentIconName,Q*.6,"#ffffff",2);ne?(f.appendChild(ne),f.style.display=""):(f.textContent=(D=i.agentIconText)!=null?D:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(x=i.agentIconText)!=null?x:"\u{1F4AC}",f.style.display="")}let w=s.querySelector("[data-role='launcher-image']");if(w){let K=(S=i.agentIconSize)!=null?S:"40px";w.style.height=K,w.style.width=K,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(w.src=i.iconUrl,w.style.display="block"):w.style.display="none"}let u=s.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let K=(X=i.callToActionIconSize)!=null?X:"32px";u.style.height=K,u.style.width=K,i.callToActionIconBackgroundColor?(u.style.backgroundColor=i.callToActionIconBackgroundColor,u.classList.remove("tvw-bg-cw-primary")):(u.style.backgroundColor="",u.classList.add("tvw-bg-cw-primary"));let Q=0;if(i.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=i.callToActionIconPadding,Q=(parseFloat(i.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),i.callToActionIconHidden)u.style.display="none";else if(u.style.display="",u.innerHTML="",i.callToActionIconName){let ne=parseFloat(K)||24,re=Math.max(ne-Q,8),q=ce(i.callToActionIconName,re,"currentColor",2);q?u.appendChild(q):u.textContent=(B=i.callToActionIconText)!=null?B:"\u2197"}else u.textContent=(j=i.callToActionIconText)!=null?j:"\u2197"}let C=i.position&&vt[i.position]?vt[i.position]:vt["bottom-right"],g="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";s.className=`${g} ${C}`;let U="1px solid #e5e7eb",I="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";s.style.border=(Z=i.border)!=null?Z:U,s.style.boxShadow=(_=i.shadow)!=null?_:I},r=()=>{s.removeEventListener("click",e),s.remove()};return n&&t(n),{element:s,update:t,destroy:r}};var Ot=n=>{var j,Z,_,K,Q,ne,re,q,qe,Ve,nt,bt,Ct,Y,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,Ie,ot,Ue,R,dt,Se,Oe;let{config:e,showClose:s=!0}=n,t=m("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(j=e==null?void 0:e.launcher)!=null?j:{},o=(Z=r.headerIconSize)!=null?Z:"48px",i=(_=r.closeButtonSize)!=null?_:"32px",l=(K=r.closeButtonPlacement)!=null?K:"inline",c=(Q=r.headerIconHidden)!=null?Q:!1,d=r.headerIconName,f=m("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=o,f.style.width=o,!c)if(d){let te=parseFloat(o)||24,Ae=ce(d,te*.6,"#ffffff",2);Ae?f.replaceChildren(Ae):f.textContent=(re=(ne=e==null?void 0:e.launcher)==null?void 0:ne.agentIconText)!=null?re:"\u{1F4AC}"}else if((q=e==null?void 0:e.launcher)!=null&&q.iconUrl){let te=m("img");te.src=e.launcher.iconUrl,te.alt="",te.className="tvw-rounded-xl tvw-object-cover",te.style.height=o,te.style.width=o,f.replaceChildren(te)}else f.textContent=(Ve=(qe=e==null?void 0:e.launcher)==null?void 0:qe.agentIconText)!=null?Ve:"\u{1F4AC}";let w=m("div","tvw-flex tvw-flex-col"),u=m("span","tvw-text-base tvw-font-semibold");u.textContent=(bt=(nt=e==null?void 0:e.launcher)==null?void 0:nt.title)!=null?bt:"Chat Assistant";let C=m("span","tvw-text-xs tvw-text-cw-muted");C.textContent=(Y=(Ct=e==null?void 0:e.launcher)==null?void 0:Ct.subtitle)!=null?Y:"Here to help you get answers fast",w.append(u,C),c?t.append(w):t.append(f,w);let g=(fe=r.clearChat)!=null?fe:{},U=(mt=g.enabled)!=null?mt:!0,I=(ft=g.placement)!=null?ft:"inline",h=null,b=null;if(U){let te=(Ge=g.size)!=null?Ge:"32px",Ae=(st=g.iconName)!=null?st:"refresh-cw",Te=(H=g.iconColor)!=null?H:"",ze=(He=g.backgroundColor)!=null?He:"",Ye=(at=g.borderWidth)!=null?at:"",xt=(lt=g.borderColor)!=null?lt:"",Bt=(Tt=g.borderRadius)!=null?Tt:"",yt=(wt=g.paddingX)!=null?wt:"",Et=(Ie=g.paddingY)!=null?Ie:"",St=(ot=g.tooltipText)!=null?ot:"Clear chat",ye=(Ue=g.showTooltip)!=null?Ue:!0;b=m("div",I==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),I==="top-right"&&(b.style.right="48px"),h=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),h.style.height=te,h.style.width=te,h.type="button",h.setAttribute("aria-label",St);let Ht=ce(Ae,"20px",Te||"",2);if(Ht&&h.appendChild(Ht),Te&&(h.style.color=Te,h.classList.remove("tvw-text-cw-muted")),ze&&(h.style.backgroundColor=ze,h.classList.remove("hover:tvw-bg-gray-100")),Ye||xt){let Le=Ye||"0px",Je=xt||"transparent";h.style.border=`${Le} solid ${Je}`,h.classList.remove("tvw-border-none")}if(Bt&&(h.style.borderRadius=Bt,h.classList.remove("tvw-rounded-full")),yt?(h.style.paddingLeft=yt,h.style.paddingRight=yt):(h.style.paddingLeft="",h.style.paddingRight=""),Et?(h.style.paddingTop=Et,h.style.paddingBottom=Et):(h.style.paddingTop="",h.style.paddingBottom=""),b.appendChild(h),ye&&St&&h&&b){let Le=null,Je=()=>{if(Le||!h)return;Le=m("div","tvw-clear-chat-tooltip"),Le.textContent=St;let Dt=m("div");Dt.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(Dt);let Mt=h.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Mt.left+Mt.width/2}px`,Le.style.top=`${Mt.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},At=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};b.addEventListener("mouseenter",Je),b.addEventListener("mouseleave",At),h.addEventListener("focus",Je),h.addEventListener("blur",At),b._cleanupTooltip=()=>{At(),b&&(b.removeEventListener("mouseenter",Je),b.removeEventListener("mouseleave",At)),h&&(h.removeEventListener("focus",Je),h.removeEventListener("blur",At))}}I==="inline"&&t.appendChild(b)}let W=m("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":U&&I==="inline"?"":"tvw-ml-auto"),v=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let D=(R=r.closeButtonTooltipText)!=null?R:"Close chat",x=(dt=r.closeButtonShowTooltip)!=null?dt:!0;v.setAttribute("aria-label",D),v.style.display=s?"":"none";let S=(Se=r.closeButtonIconName)!=null?Se:"x",X=(Oe=r.closeButtonIconText)!=null?Oe:"\xD7",B=ce(S,"20px",r.closeButtonColor||"",2);if(B?v.appendChild(B):v.textContent=X,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let te=r.closeButtonBorderWidth||"0px",Ae=r.closeButtonBorderColor||"transparent";v.style.border=`${te} solid ${Ae}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),W.appendChild(v),x&&D){let te=null,Ae=()=>{if(te)return;te=m("div","tvw-clear-chat-tooltip"),te.textContent=D;let ze=m("div");ze.className="tvw-clear-chat-tooltip-arrow",te.appendChild(ze);let Ye=v.getBoundingClientRect();te.style.position="fixed",te.style.left=`${Ye.left+Ye.width/2}px`,te.style.top=`${Ye.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Te=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};W.addEventListener("mouseenter",Ae),W.addEventListener("mouseleave",Te),v.addEventListener("focus",Ae),v.addEventListener("blur",Te),W._cleanupTooltip=()=>{Te(),W.removeEventListener("mouseenter",Ae),W.removeEventListener("mouseleave",Te),v.removeEventListener("focus",Ae),v.removeEventListener("blur",Te)}}return l!=="top-right"&&t.appendChild(W),{header:t,iconHolder:f,headerTitle:u,headerSubtitle:C,closeButton:v,closeButtonWrapper:W,clearChatButton:h,clearChatButtonWrapper:b}},Qt=(n,e,s)=>{var i,l,c,d;let t=(i=s==null?void 0:s.launcher)!=null?i:{},r=(l=t.closeButtonPlacement)!=null?l:"inline",o=(d=(c=t.clearChat)==null?void 0:c.placement)!=null?d:"inline";n.appendChild(e.header),r==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&o==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var Zn=n=>Ot({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Qn=n=>{var g,U,I,h;let{config:e,showClose:s=!0,onClose:t}=n,r=(g=e==null?void 0:e.launcher)!=null?g:{},o=m("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=m("span","tvw-text-base tvw-font-semibold");i.textContent=(U=r.title)!=null?U:"Chat Assistant",o.appendChild(i);let l=(I=r.closeButtonSize)!=null?I:"32px",c=m("div",""),d=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");d.style.height=l,d.style.width=l,d.type="button",d.setAttribute("aria-label","Close chat"),d.style.display=s?"":"none";let f=(h=r.closeButtonIconName)!=null?h:"x",w=ce(f,"20px",r.closeButtonColor||"",2);w?d.appendChild(w):d.textContent="\xD7",t&&d.addEventListener("click",t),c.appendChild(d),o.appendChild(c);let u=m("div");u.style.display="none";let C=m("span");return C.style.display="none",{header:o,iconHolder:u,headerTitle:i,headerSubtitle:C,closeButton:d,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}},es=n=>{var v,D,x,S,X,B,j,Z;let{config:e,showClose:s=!0,onClose:t,onClearChat:r}=n,o=(v=e==null?void 0:e.launcher)!=null?v:{},i=m("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=m("div","tvw-flex tvw-items-center tvw-gap-3"),c=(D=o.headerIconSize)!=null?D:"56px",d=m("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");d.style.height=c,d.style.width=c;let f=o.headerIconName;if(f){let _=parseFloat(c)||24,K=ce(f,_*.5,"#ffffff",2);K?d.replaceChildren(K):d.textContent=(x=o.agentIconText)!=null?x:"\u{1F4AC}"}else if(o.iconUrl){let _=m("img");_.src=o.iconUrl,_.alt="",_.className="tvw-rounded-xl tvw-object-cover",_.style.height=c,_.style.width=c,d.replaceChildren(_)}else d.textContent=(S=o.agentIconText)!=null?S:"\u{1F4AC}";let w=m("div","tvw-flex tvw-flex-col tvw-flex-1"),u=m("span","tvw-text-lg tvw-font-semibold");u.textContent=(X=o.title)!=null?X:"Chat Assistant";let C=m("span","tvw-text-sm tvw-text-cw-muted");C.textContent=(B=o.subtitle)!=null?B:"Here to help you get answers fast",w.append(u,C),l.append(d,w);let g=(j=o.closeButtonSize)!=null?j:"32px",U=m("div",""),I=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");I.style.height=g,I.style.width=g,I.type="button",I.setAttribute("aria-label","Close chat"),I.style.display=s?"":"none";let h=(Z=o.closeButtonIconName)!=null?Z:"x",b=ce(h,"20px",o.closeButtonColor||"",2);b?I.appendChild(b):I.textContent="\xD7",t&&I.addEventListener("click",t),U.appendChild(I),l.appendChild(U),i.appendChild(l);let W=m("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return W.textContent="Online and ready to help",i.appendChild(W),{header:i,iconHolder:d,headerTitle:u,headerSubtitle:C,closeButton:I,closeButtonWrapper:U,clearChatButton:null,clearChatButtonWrapper:null}},Rn={default:Zn,minimal:Qn,expanded:es},ts=n=>{var e;return(e=Rn[n])!=null?e:Rn.default},In=(n,e,s)=>{var i,l,c;if(e!=null&&e.render){let d=e.render({config:n,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat}),f=m("div");f.style.display="none";let w=m("span"),u=m("span"),C=m("button");C.style.display="none";let g=m("div");return g.style.display="none",{header:d,iconHolder:f,headerTitle:w,headerSubtitle:u,closeButton:C,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",o=ts(t)({config:n,showClose:(c=(l=e==null?void 0:e.showCloseButton)!=null?l:s==null?void 0:s.showClose)!=null?c:!0,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat});return e&&(e.showIcon===!1&&(o.iconHolder.style.display="none"),e.showTitle===!1&&(o.headerTitle.style.display="none"),e.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(o.closeButton.style.display="none"),e.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var ur=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},en=n=>{var ne,re,q,qe,Ve,nt,bt,Ct,Y,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,Ie,ot,Ue,R,dt;let{config:e}=n,s=m("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=m("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((ne=e==null?void 0:e.voiceRecognition)==null?void 0:ne.enabled)===!0,o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),c=m("form",`tvw-widget-composer tvw-flex tvw-items-end ${r&&o?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);c.style.outline="none";let d=m("textarea");d.placeholder=(q=(re=e==null?void 0:e.copy)==null?void 0:re.inputPlaceholder)!=null?q:"Type your message\u2026",d.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",d.rows=1;let f=(Ve=(qe=e==null?void 0:e.theme)==null?void 0:qe.inputFontFamily)!=null?Ve:"sans-serif",w=(bt=(nt=e==null?void 0:e.theme)==null?void 0:nt.inputFontWeight)!=null?bt:"400";d.style.fontFamily=ur(f),d.style.fontWeight=w,d.style.border="none",d.style.outline="none",d.style.borderWidth="0",d.style.borderStyle="none",d.style.borderColor="transparent",d.addEventListener("focus",()=>{d.style.border="none",d.style.outline="none",d.style.borderWidth="0",d.style.borderStyle="none",d.style.borderColor="transparent",d.style.boxShadow="none"}),d.addEventListener("blur",()=>{d.style.border="none",d.style.outline="none"});let u=(Ct=e==null?void 0:e.sendButton)!=null?Ct:{},C=(Y=u.useIcon)!=null?Y:!1,g=(fe=u.iconText)!=null?fe:"\u2191",U=u.iconName,I=(mt=u.tooltipText)!=null?mt:"Send message",h=(ft=u.showTooltip)!=null?ft:!1,b=(Ge=u.size)!=null?Ge:"40px",W=u.backgroundColor,v=u.textColor,D=m("div","tvw-send-button-wrapper"),x=m("button",C?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(x.type="submit",C){if(x.style.width=b,x.style.height=b,x.style.minWidth=b,x.style.minHeight=b,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",U){let Se=parseFloat(b)||24,Oe=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",te=ce(U,Se,Oe,2);te?(x.appendChild(te),x.style.color=Oe):(x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white"))}else x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white");W?x.style.backgroundColor=W:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(H=(st=e==null?void 0:e.copy)==null?void 0:st.sendButtonLabel)!=null?H:"Send",v?x.style.color=v:x.classList.add("tvw-text-white");if(u.borderWidth&&(x.style.borderWidth=u.borderWidth,x.style.borderStyle="solid"),u.borderColor&&(x.style.borderColor=u.borderColor),u.paddingX?(x.style.paddingLeft=u.paddingX,x.style.paddingRight=u.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),u.paddingY?(x.style.paddingTop=u.paddingY,x.style.paddingBottom=u.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),h&&I){let Se=m("div","tvw-send-button-tooltip");Se.textContent=I,D.appendChild(Se)}D.appendChild(x);let S=(He=e==null?void 0:e.voiceRecognition)!=null?He:{},X=S.enabled===!0,B=null,j=null,Z=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(X&&Z){j=m("div","tvw-send-button-wrapper"),B=m("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),B.type="button",B.setAttribute("aria-label","Start voice recognition");let Se=(at=S.iconName)!=null?at:"mic",Oe=(lt=S.iconSize)!=null?lt:b,te=parseFloat(Oe)||24,Ae=(Tt=S.backgroundColor)!=null?Tt:W,Te=(wt=S.iconColor)!=null?wt:v;B.style.width=Oe,B.style.height=Oe,B.style.minWidth=Oe,B.style.minHeight=Oe,B.style.fontSize="18px",B.style.lineHeight="1";let ze=Te||"currentColor",Ye=ce(Se,te,ze,1.5);Ye?(B.appendChild(Ye),B.style.color=ze):(B.textContent="\u{1F3A4}",B.style.color=ze),Ae?B.style.backgroundColor=Ae:B.classList.add("tvw-bg-cw-primary"),Te?B.style.color=Te:!Te&&!v&&B.classList.add("tvw-text-white"),S.borderWidth&&(B.style.borderWidth=S.borderWidth,B.style.borderStyle="solid"),S.borderColor&&(B.style.borderColor=S.borderColor),S.paddingX&&(B.style.paddingLeft=S.paddingX,B.style.paddingRight=S.paddingX),S.paddingY&&(B.style.paddingTop=S.paddingY,B.style.paddingBottom=S.paddingY),j.appendChild(B);let xt=(Ie=S.tooltipText)!=null?Ie:"Start voice recognition";if(((ot=S.showTooltip)!=null?ot:!1)&&xt){let yt=m("div","tvw-send-button-tooltip");yt.textContent=xt,j.appendChild(yt)}}c.addEventListener("click",Se=>{Se.target!==x&&Se.target!==D&&Se.target!==B&&Se.target!==j&&d.focus()}),c.append(d),j&&c.append(j),c.append(D);let _=m("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),K=(Ue=e==null?void 0:e.statusIndicator)!=null?Ue:{},Q=(R=K.visible)!=null?R:!0;return _.style.display=Q?"":"none",_.textContent=(dt=K.idleText)!=null?dt:"Online",s.append(t,c,_),{footer:s,suggestions:t,composerForm:c,textarea:d,sendButton:x,sendButtonWrapper:D,micButton:B,micButtonWrapper:j,statusText:_}};var Po=n=>{var c,d,f,w,u,C,g;if(!((d=(c=n==null?void 0:n.launcher)==null?void 0:c.enabled)!=null?d:!0)){let U=m("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),I=m("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),h=(w=(f=n==null?void 0:n.launcher)==null?void 0:f.width)!=null?w:"100%";return U.style.width=h,I.style.width="100%",U.appendChild(I),{wrapper:U,panel:I}}let s=(u=n==null?void 0:n.launcher)!=null?u:{},t=s.position&&vt[s.position]?vt[s.position]:vt["bottom-right"],r=m("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),o=m("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(g=(C=n==null?void 0:n.launcher)==null?void 0:C.width)!=null?g: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}},Ro=(n,e=!0)=>{var w,u,C,g,U;let s=m("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=n==null?void 0:n.layout)==null?void 0:w.header,r=t?In(n,t,{showClose:e}):Ot({config:n,showClose:e}),o=m("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");o.id="vanilla-agent-scroll-container";let i=m("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=m("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(C=(u=n==null?void 0:n.copy)==null?void 0:u.welcomeTitle)!=null?C:"Hello \u{1F44B}";let c=m("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(U=(g=n==null?void 0:n.copy)==null?void 0:g.welcomeSubtitle)!=null?U:"Ask anything about your account or products.",i.append(l,c);let d=m("div","tvw-flex tvw-flex-col tvw-gap-3");o.append(i,d);let f=en({config:n});return Qt(s,r,n),s.append(o,f.footer),{container:s,body:o,messagesWrapper:d,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:c,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:f.footer}};var wn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let s=document.createElement("div");s.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",s.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(e),n.appendChild(s),n.appendChild(t),n.appendChild(r),n},pr=(n,e)=>{let s=m("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=m("img");r.src=t,r.alt=e==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",s.appendChild(r)}else s.textContent=t,s.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else s.textContent=e==="user"?"U":"A",s.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return s},Io=(n,e)=>{let s=m("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?s.textContent=e.format(t):s.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s},gr=(n,e="bubble")=>{let s=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):s.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":s.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:s.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return s},ns=(n,e,s)=>{var g,U,I,h,b,W;let t=(g=e.showCopy)!=null?g:!0,r=(U=e.showUpvote)!=null?U:!0,o=(I=e.showDownvote)!=null?I:!0,i=(h=e.visibility)!=null?h:"hover",l=(b=e.align)!=null?b:"right",c=(W=e.layout)!=null?W:"pill-inside",d={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[c],w=m("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${d} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`),u=null,C=(v,D,x,S)=>{let X=document.createElement("button");X.className="tvw-message-action-btn",X.setAttribute("aria-label",D),X.setAttribute("title",D),S&&X.setAttribute("data-action",S);let B=ce(v,14,"currentColor",2);return B&&X.appendChild(B),X.addEventListener("click",j=>{j.preventDefault(),j.stopPropagation(),x()}),X};if(t){let v=C("copy","Copy message",()=>{let D=n.content||"";navigator.clipboard.writeText(D).then(()=>{v.classList.add("tvw-message-action-success");let x=ce("check",14,"currentColor",2);x&&(v.innerHTML="",v.appendChild(x)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let S=ce("copy",14,"currentColor",2);S&&(v.innerHTML="",v.appendChild(S))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),s!=null&&s.onCopy&&s.onCopy(n),e.onCopy&&e.onCopy(n)},"copy");w.appendChild(v)}if(r){let v=C("thumbs-up","Upvote",()=>{if(u==="upvote")u=null,v.classList.remove("tvw-message-action-active");else{let x=w.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),u="upvote",v.classList.add("tvw-message-action-active");let S={type:"upvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),e.onFeedback&&e.onFeedback(S)}},"upvote");w.appendChild(v)}if(o){let v=C("thumbs-down","Downvote",()=>{if(u==="downvote")u=null,v.classList.remove("tvw-message-action-active");else{let x=w.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),u="downvote",v.classList.add("tvw-message-action-active");let S={type:"downvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),e.onFeedback&&e.onFeedback(S)}},"downvote");w.appendChild(v)}return w},tn=(n,e,s,t,r)=>{var W,v,D,x,S;let o=s!=null?s:{},i=(W=o.layout)!=null?W:"bubble",l=o.avatar,c=o.timestamp,d=(v=l==null?void 0:l.show)!=null?v:!1,f=(D=c==null?void 0:c.show)!=null?D:!1,w=(x=l==null?void 0:l.position)!=null?x:"left",u=(S=c==null?void 0:c.position)!=null?S:"below",C=gr(n.role,i),g=m("div",C.join(" ")),U=document.createElement("div");if(U.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),f&&u==="inline"&&n.createdAt){let X=Io(n,c);X.classList.add("tvw-ml-2","tvw-inline"),U.appendChild(X)}if(g.appendChild(U),f&&u==="below"&&n.createdAt){let X=Io(n,c);X.classList.add("tvw-mt-1"),g.appendChild(X)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let X=wn();g.appendChild(X)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let X=ns(n,t,r);g.appendChild(X)}if(!d||n.role==="system")return g;let h=m("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),b=pr(l,n.role);return w==="right"||w==="left"&&n.role==="user"?h.append(g,b):h.append(b,g),g.classList.remove("tvw-max-w-[85%]"),g.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),h},Fo=(n,e,s,t,r)=>{let o=s!=null?s:{};return n.role==="user"&&o.renderUserMessage?o.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&o.renderAssistantMessage?o.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):tn(n,e,s,t,r)};var ss=new Set,os=n=>{let e=n.reasoning,s=m("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return s;let t=ss.has(n.id),r=m("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false");let o=m("div","tvw-flex tvw-flex-col tvw-text-left"),i=m("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",o.appendChild(i);let l=m("span","tvw-text-xs tvw-text-cw-primary");l.textContent=ko(e),o.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let c=m("div","tvw-flex tvw-items-center"),f=ce(t?"chevron-up":"chevron-down",16,"currentColor",2);f?c.appendChild(f):c.textContent=t?"Hide":"Show";let w=m("div","tvw-flex tvw-items-center tvw-ml-auto");w.append(c),r.append(o,w);let u=m("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");u.style.display=t?"":"none";let C=e.chunks.join(""),g=m("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");g.textContent=C||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),u.appendChild(g);let U=()=>{r.setAttribute("aria-expanded",t?"true":"false"),c.innerHTML="";let b=ce(t?"chevron-up":"chevron-down",16,"currentColor",2);b?c.appendChild(b):c.textContent=t?"Hide":"Show",u.style.display=t?"":"none"},I=()=>{t=!t,t?ss.add(n.id):ss.delete(n.id),U()};return r.addEventListener("pointerdown",h=>{h.preventDefault(),I()}),r.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),I())}),U(),s.append(r,u),s};var rs=new Set,is=(n,e)=>{var I;let s=n.toolCall,t=(I=e==null?void 0:e.toolCall)!=null?I:{},r=m("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!s)return r;let o=rs.has(n.id),i=m("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",o?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=m("div","tvw-flex tvw-flex-col tvw-text-left"),c=m("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(c.style.color=t.headerTextColor),c.textContent=Lo(s),l.appendChild(c);let d=m("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",w=ce(o?"chevron-up":"chevron-down",16,f,2);w?d.appendChild(w):d.textContent=o?"Hide":"Show";let u=m("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");u.append(d),i.append(l,u);let C=m("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(C.style.display=o?"":"none",t.contentBackgroundColor&&(C.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(C.style.color=t.contentTextColor),t.contentPaddingX&&(C.style.paddingLeft=t.contentPaddingX,C.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(C.style.paddingTop=t.contentPaddingY,C.style.paddingBottom=t.contentPaddingY),s.name){let h=m("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?h.style.color=t.contentTextColor:t.headerTextColor&&(h.style.color=t.headerTextColor),h.textContent=s.name,C.appendChild(h)}if(s.args!==void 0){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Arguments";let W=m("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Vn(s.args),h.append(b,W),C.appendChild(h)}if(s.chunks&&s.chunks.length){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Activity";let W=m("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=s.chunks.join(`
16
- `),h.append(b,W),C.appendChild(h)}if(s.status==="complete"&&s.result!==void 0){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Result";let W=m("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Vn(s.result),h.append(b,W),C.appendChild(h)}if(s.status==="complete"&&typeof s.duration=="number"){let h=m("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(h.style.color=t.contentTextColor),h.textContent=`Duration: ${s.duration}ms`,C.appendChild(h)}let g=()=>{i.setAttribute("aria-expanded",o?"true":"false"),d.innerHTML="";let h=t.toggleTextColor||t.headerTextColor||"currentColor",b=ce(o?"chevron-up":"chevron-down",16,h,2);b?d.appendChild(b):d.textContent=o?"Hide":"Show",C.style.display=o?"":"none"},U=()=>{o=!o,o?rs.add(n.id):rs.delete(n.id),g()};return i.addEventListener("pointerdown",h=>{h.preventDefault(),U()}),i.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),U())}),g(),r.append(i,C),r};var No=n=>{let e=[];return{buttons:e,render:(t,r,o,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(C=>C.role==="user"))return;let f=document.createDocumentFragment(),w=r?r.isStreaming():!1,u=C=>{switch(C){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(C=>{let g=m("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");g.type="button",g.textContent=C,g.disabled=w,l!=null&&l.fontFamily&&(g.style.fontFamily=u(l.fontFamily)),l!=null&&l.fontWeight&&(g.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(g.style.paddingLeft=l.paddingX,g.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(g.style.paddingTop=l.paddingY,g.style.paddingBottom=l.paddingY),g.addEventListener("click",()=>{!r||r.isStreaming()||(o.value="",r.sendMessage(C))}),f.appendChild(g),e.push(g)}),n.appendChild(f)}}};var Oo={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"}},as=(n,e,s,t)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(o=>{var g,U,I;if(o.dataset.enhanced==="true")return;let i=(g=o.dataset.tvForm)!=null?g:"init";o.dataset.enhanced="true";let l=(U=Oo[i])!=null?U:Oo.init;o.classList.add("tvw-form-card","tvw-space-y-4");let c=m("div","tvw-space-y-1"),d=m("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(d.textContent=l.title,c.appendChild(d),l.description){let h=m("p","tvw-text-sm tvw-text-cw-muted");h.textContent=l.description,c.appendChild(h)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(h=>{var x,S;let b=m("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");b.htmlFor=`${e.id}-${i}-${h.name}`;let W=m("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");W.textContent=h.label,b.appendChild(W);let v=(x=h.type)!=null?x:"text",D;v==="textarea"?(D=document.createElement("textarea"),D.rows=3):(D=document.createElement("input"),D.type=v),D.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",D.id=`${e.id}-${i}-${h.name}`,D.name=h.name,D.placeholder=(S=h.placeholder)!=null?S:"",h.required&&(D.required=!0),b.appendChild(D),f.appendChild(b)});let w=m("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),u=m("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),C=m("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");C.type="submit",C.textContent=(I=l.submitLabel)!=null?I:"Submit",w.appendChild(u),w.appendChild(C),f.appendChild(w),o.replaceChildren(c,f),f.addEventListener("submit",async h=>{var D,x;h.preventDefault();let b=(D=s.formEndpoint)!=null?D:"/form",W=new FormData(f),v={};W.forEach((S,X)=>{v[X]=S}),v.type=i,C.disabled=!0,u.textContent="Submitting\u2026";try{let S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let X=await S.json();u.textContent=(x=X.message)!=null?x:"Thanks! We'll be in touch soon.",X.success&&X.nextPrompt&&await t.sendMessage(String(X.nextPrompt))}catch(S){u.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{C.disabled=!1}})})};var ls=class{constructor(){this.plugins=new Map}register(e){var s;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(s=e.onRegister)==null||s.call(e)}unregister(e){var t;let s=this.plugins.get(e);s&&((t=s.onUnregister)==null||t.call(s),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,s)=>{var t,r;return((t=s.priority)!=null?t:0)-((r=e.priority)!=null?r:0)})}getForInstance(e){let s=this.getAll();if(!e||e.length===0)return s;let t=new Set(e.map(o=>o.id));return[...s.filter(o=>!t.has(o.id)),...e].sort((o,i)=>{var l,c;return((l=i.priority)!=null?l:0)-((c=o.priority)!=null?c:0)})}clear(){this.plugins.forEach(e=>{var s;return(s=e.onUnregister)==null?void 0:s.call(e)}),this.plugins.clear()}},yn=new ls;var ke={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Fn(n){var e,s,t,r,o,i,l,c,d,f,w,u,C,g,U,I,h,b,W;return n?{...ke,...n,theme:{...ke.theme,...n.theme},launcher:{...ke.launcher,...n.launcher,clearChat:{...(e=ke.launcher)==null?void 0:e.clearChat,...(s=n.launcher)==null?void 0:s.clearChat}},copy:{...ke.copy,...n.copy},sendButton:{...ke.sendButton,...n.sendButton},statusIndicator:{...ke.statusIndicator,...n.statusIndicator},voiceRecognition:{...ke.voiceRecognition,...n.voiceRecognition},features:{...ke.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:ke.suggestionChips,suggestionChipsConfig:{...ke.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...ke.layout,...n.layout,header:{...(r=ke.layout)==null?void 0:r.header,...(o=n.layout)==null?void 0:o.header},messages:{...(i=ke.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(d=(c=ke.layout)==null?void 0:c.messages)==null?void 0:d.avatar,...(w=(f=n.layout)==null?void 0:f.messages)==null?void 0:w.avatar},timestamp:{...(C=(u=ke.layout)==null?void 0:u.messages)==null?void 0:C.timestamp,...(U=(g=n.layout)==null?void 0:g.messages)==null?void 0:U.timestamp}},slots:{...(I=ke.layout)==null?void 0:I.slots,...(h=n.layout)==null?void 0:h.slots}},markdown:{...ke.markdown,...n.markdown,options:{...(b=ke.markdown)==null?void 0:b.options,...(W=n.markdown)==null?void 0:W.options}},messageActions:{...ke.messageActions,...n.messageActions}}:ke}var Do=()=>{let n=new Map,e=(r,o)=>(n.has(r)||n.set(r,new Set),n.get(r).add(o),()=>s(r,o)),s=(r,o)=>{var i;(i=n.get(r))==null||i.delete(o)};return{on:e,off:s,emit:(r,o)=>{var i;(i=n.get(r))==null||i.forEach(l=>{try{l(o)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var hr=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},mr=n=>{let e=n.trim(),s=e.indexOf("{");if(s===-1)return null;let t=0;for(let r=s;r<e.length;r+=1){let o=e[r];if(o==="{"&&(t+=1),o==="}"&&(t-=1,t===0))return e.slice(s,r+1)}return null},vn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=hr(n),s=mr(e);if(!s)return null;let t=JSON.parse(s);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...o}=t;return{type:String(r),payload:o,raw:t}}catch{return null}},ds=n=>typeof n=="string"?n:n==null?"":String(n),Kt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:ds(n.payload.text)},messageAndClick:(n,e)=>{var r;if(n.type!=="message_and_click")return;let s=n.payload,t=ds(s.element);if(t&&((r=e.document)!=null&&r.querySelector)){let o=e.document.querySelector(t);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:ds(s.text)}}},jo=n=>Array.isArray(n)?n.map(e=>String(e)):[],bn=n=>{let e=new Set(jo(n.getMetadata().processedActionMessageIds)),s=()=>{e=new Set(jo(n.getMetadata().processedActionMessageIds))},t=()=>{let o=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||e.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((d,f)=>d||(f==null?void 0:f({text:i,message:o.message}))||null,null):null;if(!l)return null;e.add(o.message.id),t();let c={action:l,message:o.message};n.emit("action:detected",c);for(let d of n.handlers)if(d)try{let f=d(l,{message:o.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!f)continue;if(f.handled){let w=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:w}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:s}};var fr=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},wr=n=>n.map(e=>({...e,streaming:!1})),Nn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let s=e();return s?fr(s.getItem(n)):null},save:s=>{let t=e();if(t)try{let r={...s,messages:s.messages?wr(s.messages):void 0};t.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let s=e();if(s)try{s.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var cs=class{constructor(){this.components=new Map}register(e,s){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,s)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([s,t])=>{this.register(s,t)})}},nn=new cs;var sn=require("partial-json");function yr(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function vr(n,e){if(!yr(n))return null;let s=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:s,raw:e}}function On(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:s=>{let t=s.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(s.length<=e)return n;try{let r=(0,sn.parse)(s,sn.STR|sn.OBJ),o=vr(r,s);o&&(n=o)}catch{}return e=s.length,n},reset:()=>{n=null,e=0}}}function _o(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Dn(n,e){let{config:s,message:t,onPropsUpdate:r}=e,o=nn.get(n.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,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 qo(){let n=On();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function jn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function _n(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var br=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function qn(n){let{onSubmit:e,onDismiss:s,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:d=br}=n,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let w=null,u=document.createElement("div");u.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let g=document.createElement("h3");g.className="tvw-feedback-title",g.textContent=t,C.appendChild(g);let U=document.createElement("p");U.className="tvw-feedback-subtitle",U.textContent=r,C.appendChild(U),u.appendChild(C);let I=document.createElement("div");I.className="tvw-feedback-rating tvw-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let h=[];for(let x=1;x<=5;x++){let S=document.createElement("button");S.type="button",S.className="tvw-feedback-rating-btn tvw-feedback-star-btn",S.setAttribute("role","radio"),S.setAttribute("aria-checked","false"),S.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${d[x-1]}`),S.title=d[x-1],S.dataset.rating=String(x),S.innerHTML=`
15
+ `,s.addEventListener("click",e);let t=o=>{var m,b,W,v,N,x,S,Y,R,O,G,D;let i=(m=o.launcher)!=null?m:{},l=s.querySelector("[data-role='launcher-title']");l&&(l.textContent=(b=i.title)!=null?b:"Chat Assistant");let d=s.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(W=i.subtitle)!=null?W:"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 Q=parseFloat(U)||24,ie=ge(i.agentIconName,Q*.6,"#ffffff",2);ie?(w.appendChild(ie),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 y=s.querySelector("[data-role='launcher-image']");if(y){let U=(S=i.agentIconSize)!=null?S:"40px";y.style.height=U,y.style.width=U,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let u=s.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let U=(Y=i.callToActionIconSize)!=null?Y:"32px";u.style.height=U,u.style.width=U,i.callToActionIconBackgroundColor?(u.style.backgroundColor=i.callToActionIconBackgroundColor,u.classList.remove("tvw-bg-cw-primary")):(u.style.backgroundColor="",u.classList.add("tvw-bg-cw-primary"));let Q=0;if(i.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=i.callToActionIconPadding,Q=(parseFloat(i.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),i.callToActionIconHidden)u.style.display="none";else if(u.style.display="",u.innerHTML="",i.callToActionIconName){let ie=parseFloat(U)||24,de=Math.max(ie-Q,8),_=ge(i.callToActionIconName,de,"currentColor",2);_?u.appendChild(_):u.textContent=(R=i.callToActionIconText)!=null?R:"\u2197"}else u.textContent=(O=i.callToActionIconText)!=null?O:"\u2197"}let C=i.position&&Ct[i.position]?Ct[i.position]:Ct["bottom-right"],g="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";s.className=`${g} ${C}`;let j="1px solid #e5e7eb",$="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";s.style.border=(G=i.border)!=null?G:j,s.style.boxShadow=(D=i.shadow)!=null?D:$},r=()=>{s.removeEventListener("click",e),s.remove()};return n&&t(n),{element:s,update:t,destroy:r}};var Ot=n=>{var O,G,D,U,Q,ie,de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye,E,$e;let{config:e,showClose:s=!0}=n,t=f("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=(O=e==null?void 0:e.launcher)!=null?O:{},o=(G=r.headerIconSize)!=null?G:"48px",i=(D=r.closeButtonSize)!=null?D:"32px",l=(U=r.closeButtonPlacement)!=null?U:"inline",d=(Q=r.headerIconHidden)!=null?Q:!1,c=r.headerIconName,w=f("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 V=parseFloat(o)||24,Le=ge(c,V*.6,"#ffffff",2);Le?w.replaceChildren(Le):w.textContent=(de=(ie=e==null?void 0:e.launcher)==null?void 0:ie.agentIconText)!=null?de:"\u{1F4AC}"}else if((_=e==null?void 0:e.launcher)!=null&&_.iconUrl){let V=f("img");V.src=e.launcher.iconUrl,V.alt="",V.className="tvw-rounded-xl tvw-object-cover",V.style.height=o,V.style.width=o,w.replaceChildren(V)}else w.textContent=(Ge=(ze=e==null?void 0:e.launcher)==null?void 0:ze.agentIconText)!=null?Ge:"\u{1F4AC}";let y=f("div","tvw-flex tvw-flex-col"),u=f("span","tvw-text-base tvw-font-semibold");u.textContent=(xt=(nt=e==null?void 0:e.launcher)==null?void 0:nt.title)!=null?xt:"Chat Assistant";let C=f("span","tvw-text-xs tvw-text-cw-muted");C.textContent=(q=(St=e==null?void 0:e.launcher)==null?void 0:St.subtitle)!=null?q:"Here to help you get answers fast",y.append(u,C),d?t.append(y):t.append(w,y);let g=(ve=r.clearChat)!=null?ve:{},j=(ht=g.enabled)!=null?ht:!0,$=(ft=g.placement)!=null?ft:"inline",m=null,b=null;if(j){let V=(Qe=g.size)!=null?Qe:"32px",Le=(st=g.iconName)!=null?st:"refresh-cw",Ie=(I=g.iconColor)!=null?I:"",Fe=(Be=g.backgroundColor)!=null?Be:"",Ne=(at=g.borderWidth)!=null?at:"",ut=(lt=g.borderColor)!=null?lt:"",At=(Tt=g.borderRadius)!=null?Tt:"",vt=(wt=g.paddingX)!=null?wt:"",Lt=(He=g.paddingY)!=null?He:"",Bt=(Je=g.tooltipText)!=null?Je:"Clear chat",Dt=(yt=g.showTooltip)!=null?yt:!0;b=f("div",$==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),$==="top-right"&&(b.style.right="48px"),m=f("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=V,m.style.width=V,m.type="button",m.setAttribute("aria-label",Bt);let Et=ge(Le,"20px",Ie||"",2);if(Et&&m.appendChild(Et),Ie&&(m.style.color=Ie,m.classList.remove("tvw-text-cw-muted")),Fe&&(m.style.backgroundColor=Fe,m.classList.remove("hover:tvw-bg-gray-100")),Ne||ut){let Z=Ne||"0px",pt=ut||"transparent";m.style.border=`${Z} solid ${pt}`,m.classList.remove("tvw-border-none")}if(At&&(m.style.borderRadius=At,m.classList.remove("tvw-rounded-full")),vt?(m.style.paddingLeft=vt,m.style.paddingRight=vt):(m.style.paddingLeft="",m.style.paddingRight=""),Lt?(m.style.paddingTop=Lt,m.style.paddingBottom=Lt):(m.style.paddingTop="",m.style.paddingBottom=""),b.appendChild(m),Dt&&Bt&&m&&b){let Z=null,pt=()=>{if(Z||!m)return;Z=f("div","tvw-clear-chat-tooltip"),Z.textContent=Bt;let gt=f("div");gt.className="tvw-clear-chat-tooltip-arrow",Z.appendChild(gt);let Ht=m.getBoundingClientRect();Z.style.position="fixed",Z.style.left=`${Ht.left+Ht.width/2}px`,Z.style.top=`${Ht.top-8}px`,Z.style.transform="translate(-50%, -100%)",document.body.appendChild(Z)},bt=()=>{Z&&Z.parentNode&&(Z.parentNode.removeChild(Z),Z=null)};b.addEventListener("mouseenter",pt),b.addEventListener("mouseleave",bt),m.addEventListener("focus",pt),m.addEventListener("blur",bt),b._cleanupTooltip=()=>{bt(),b&&(b.removeEventListener("mouseenter",pt),b.removeEventListener("mouseleave",bt)),m&&(m.removeEventListener("focus",pt),m.removeEventListener("blur",bt))}}$==="inline"&&t.appendChild(b)}let W=f("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":j&&$==="inline"?"":"tvw-ml-auto"),v=f("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=(ot=r.closeButtonTooltipText)!=null?ot:"Close chat",x=(Ye=r.closeButtonShowTooltip)!=null?Ye:!0;v.setAttribute("aria-label",N),v.style.display=s?"":"none";let S=(E=r.closeButtonIconName)!=null?E:"x",Y=($e=r.closeButtonIconText)!=null?$e:"\xD7",R=ge(S,"20px",r.closeButtonColor||"",2);if(R?v.appendChild(R):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 V=r.closeButtonBorderWidth||"0px",Le=r.closeButtonBorderColor||"transparent";v.style.border=`${V} solid ${Le}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),W.appendChild(v),x&&N){let V=null,Le=()=>{if(V)return;V=f("div","tvw-clear-chat-tooltip"),V.textContent=N;let Fe=f("div");Fe.className="tvw-clear-chat-tooltip-arrow",V.appendChild(Fe);let Ne=v.getBoundingClientRect();V.style.position="fixed",V.style.left=`${Ne.left+Ne.width/2}px`,V.style.top=`${Ne.top-8}px`,V.style.transform="translate(-50%, -100%)",document.body.appendChild(V)},Ie=()=>{V&&V.parentNode&&(V.parentNode.removeChild(V),V=null)};W.addEventListener("mouseenter",Le),W.addEventListener("mouseleave",Ie),v.addEventListener("focus",Le),v.addEventListener("blur",Ie),W._cleanupTooltip=()=>{Ie(),W.removeEventListener("mouseenter",Le),W.removeEventListener("mouseleave",Ie),v.removeEventListener("focus",Le),v.removeEventListener("blur",Ie)}}return l!=="top-right"&&t.appendChild(W),{header:t,iconHolder:w,headerTitle:u,headerSubtitle:C,closeButton:v,closeButtonWrapper:W,clearChatButton:m,clearChatButtonWrapper:b}},Zt=(n,e,s)=>{var i,l,d,c;let t=(i=s==null?void 0:s.launcher)!=null?i:{},r=(l=t.closeButtonPlacement)!=null?l:"inline",o=(c=(d=t.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),r==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&o==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var Zn=n=>Ot({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),es=n=>{var g,j,$,m;let{config:e,showClose:s=!0,onClose:t}=n,r=(g=e==null?void 0:e.launcher)!=null?g:{},o=f("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=f("span","tvw-text-base tvw-font-semibold");i.textContent=(j=r.title)!=null?j:"Chat Assistant",o.appendChild(i);let l=($=r.closeButtonSize)!=null?$:"32px",d=f("div",""),c=f("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=(m=r.closeButtonIconName)!=null?m:"x",y=ge(w,"20px",r.closeButtonColor||"",2);y?c.appendChild(y):c.textContent="\xD7",t&&c.addEventListener("click",t),d.appendChild(c),o.appendChild(d);let u=f("div");u.style.display="none";let C=f("span");return C.style.display="none",{header:o,iconHolder:u,headerTitle:i,headerSubtitle:C,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},ts=n=>{var v,N,x,S,Y,R,O,G;let{config:e,showClose:s=!0,onClose:t,onClearChat:r}=n,o=(v=e==null?void 0:e.launcher)!=null?v:{},i=f("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=f("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=o.headerIconSize)!=null?N:"56px",c=f("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 D=parseFloat(d)||24,U=ge(w,D*.5,"#ffffff",2);U?c.replaceChildren(U):c.textContent=(x=o.agentIconText)!=null?x:"\u{1F4AC}"}else if(o.iconUrl){let D=f("img");D.src=o.iconUrl,D.alt="",D.className="tvw-rounded-xl tvw-object-cover",D.style.height=d,D.style.width=d,c.replaceChildren(D)}else c.textContent=(S=o.agentIconText)!=null?S:"\u{1F4AC}";let y=f("div","tvw-flex tvw-flex-col tvw-flex-1"),u=f("span","tvw-text-lg tvw-font-semibold");u.textContent=(Y=o.title)!=null?Y:"Chat Assistant";let C=f("span","tvw-text-sm tvw-text-cw-muted");C.textContent=(R=o.subtitle)!=null?R:"Here to help you get answers fast",y.append(u,C),l.append(c,y);let g=(O=o.closeButtonSize)!=null?O:"32px",j=f("div",""),$=f("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");$.style.height=g,$.style.width=g,$.type="button",$.setAttribute("aria-label","Close chat"),$.style.display=s?"":"none";let m=(G=o.closeButtonIconName)!=null?G:"x",b=ge(m,"20px",o.closeButtonColor||"",2);b?$.appendChild(b):$.textContent="\xD7",t&&$.addEventListener("click",t),j.appendChild($),l.appendChild(j),i.appendChild(l);let W=f("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return W.textContent="Online and ready to help",i.appendChild(W),{header:i,iconHolder:c,headerTitle:u,headerSubtitle:C,closeButton:$,closeButtonWrapper:j,clearChatButton:null,clearChatButtonWrapper:null}},Hn={default:Zn,minimal:es,expanded:ts},ns=n=>{var e;return(e=Hn[n])!=null?e:Hn.default},Rn=(n,e,s)=>{var i,l,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat}),w=f("div");w.style.display="none";let y=f("span"),u=f("span"),C=f("button");C.style.display="none";let g=f("div");return g.style.display="none",{header:c,iconHolder:w,headerTitle:y,headerSubtitle:u,closeButton:C,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",o=ns(t)({config:n,showClose:(d=(l=e==null?void 0:e.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 e&&(e.showIcon===!1&&(o.iconHolder.style.display="none"),e.showTitle===!1&&(o.headerTitle.style.display="none"),e.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(o.closeButton.style.display="none"),e.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var br=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},en=n=>{var ie,de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye;let{config:e}=n,s=f("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=f("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((ie=e==null?void 0:e.voiceRecognition)==null?void 0:ie.enabled)===!0,o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=f("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=f("textarea");c.placeholder=(_=(de=e==null?void 0:e.copy)==null?void 0:de.inputPlaceholder)!=null?_:"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=(Ge=(ze=e==null?void 0:e.theme)==null?void 0:ze.inputFontFamily)!=null?Ge:"sans-serif",y=(xt=(nt=e==null?void 0:e.theme)==null?void 0:nt.inputFontWeight)!=null?xt:"400";c.style.fontFamily=br(w),c.style.fontWeight=y,c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.addEventListener("focus",()=>{c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.style.boxShadow="none"}),c.addEventListener("blur",()=>{c.style.border="none",c.style.outline="none"});let u=(St=e==null?void 0:e.sendButton)!=null?St:{},C=(q=u.useIcon)!=null?q:!1,g=(ve=u.iconText)!=null?ve:"\u2191",j=u.iconName,$=(ht=u.tooltipText)!=null?ht:"Send message",m=(ft=u.showTooltip)!=null?ft:!1,b=(Qe=u.size)!=null?Qe:"40px",W=u.backgroundColor,v=u.textColor,N=f("div","tvw-send-button-wrapper"),x=f("button",C?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(x.type="submit",C){if(x.style.width=b,x.style.height=b,x.style.minWidth=b,x.style.minHeight=b,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",j){let E=parseFloat(b)||24,$e=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",V=ge(j,E,$e,2);V?(x.appendChild(V),x.style.color=$e):(x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white"))}else x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white");W?x.style.backgroundColor=W:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(I=(st=e==null?void 0:e.copy)==null?void 0:st.sendButtonLabel)!=null?I:"Send",v?x.style.color=v:x.classList.add("tvw-text-white");if(u.borderWidth&&(x.style.borderWidth=u.borderWidth,x.style.borderStyle="solid"),u.borderColor&&(x.style.borderColor=u.borderColor),u.paddingX?(x.style.paddingLeft=u.paddingX,x.style.paddingRight=u.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),u.paddingY?(x.style.paddingTop=u.paddingY,x.style.paddingBottom=u.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),m&&$){let E=f("div","tvw-send-button-tooltip");E.textContent=$,N.appendChild(E)}N.appendChild(x);let S=(Be=e==null?void 0:e.voiceRecognition)!=null?Be:{},Y=S.enabled===!0,R=null,O=null,G=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Y&&G){O=f("div","tvw-send-button-wrapper"),R=f("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),R.type="button",R.setAttribute("aria-label","Start voice recognition");let E=(at=S.iconName)!=null?at:"mic",$e=(lt=S.iconSize)!=null?lt:b,V=parseFloat($e)||24,Le=(Tt=S.backgroundColor)!=null?Tt:W,Ie=(wt=S.iconColor)!=null?wt:v;R.style.width=$e,R.style.height=$e,R.style.minWidth=$e,R.style.minHeight=$e,R.style.fontSize="18px",R.style.lineHeight="1";let Fe=Ie||"currentColor",Ne=ge(E,V,Fe,1.5);Ne?(R.appendChild(Ne),R.style.color=Fe):(R.textContent="\u{1F3A4}",R.style.color=Fe),Le?R.style.backgroundColor=Le:R.classList.add("tvw-bg-cw-primary"),Ie?R.style.color=Ie:!Ie&&!v&&R.classList.add("tvw-text-white"),S.borderWidth&&(R.style.borderWidth=S.borderWidth,R.style.borderStyle="solid"),S.borderColor&&(R.style.borderColor=S.borderColor),S.paddingX&&(R.style.paddingLeft=S.paddingX,R.style.paddingRight=S.paddingX),S.paddingY&&(R.style.paddingTop=S.paddingY,R.style.paddingBottom=S.paddingY),O.appendChild(R);let ut=(He=S.tooltipText)!=null?He:"Start voice recognition";if(((Je=S.showTooltip)!=null?Je:!1)&&ut){let vt=f("div","tvw-send-button-tooltip");vt.textContent=ut,O.appendChild(vt)}}d.addEventListener("click",E=>{E.target!==x&&E.target!==N&&E.target!==R&&E.target!==O&&c.focus()}),d.append(c),O&&d.append(O),d.append(N);let D=f("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),U=(yt=e==null?void 0:e.statusIndicator)!=null?yt:{},Q=(ot=U.visible)!=null?ot:!0;return D.style.display=Q?"":"none",D.textContent=(Ye=U.idleText)!=null?Ye:"Online",s.append(t,d,D),{footer:s,suggestions:t,composerForm:d,textarea:c,sendButton:x,sendButtonWrapper:N,micButton:R,micButtonWrapper:O,statusText:D}};var _o=n=>{var d,c,w,y,u,C,g;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let j=f("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),$=f("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),m=(y=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?y:"100%";return j.style.width=m,$.style.width="100%",j.appendChild($),{wrapper:j,panel:$}}let s=(u=n==null?void 0:n.launcher)!=null?u:{},t=s.position&&Ct[s.position]?Ct[s.position]:Ct["bottom-right"],r=f("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),o=f("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(g=(C=n==null?void 0:n.launcher)==null?void 0:C.width)!=null?g: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}},jo=(n,e=!0)=>{var y,u,C,g,j;let s=f("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=(y=n==null?void 0:n.layout)==null?void 0:y.header,r=t?Rn(n,t,{showClose:e}):Ot({config:n,showClose:e}),o=f("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");o.id="vanilla-agent-scroll-container";let i=f("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=f("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(C=(u=n==null?void 0:n.copy)==null?void 0:u.welcomeTitle)!=null?C:"Hello \u{1F44B}";let d=f("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");d.textContent=(j=(g=n==null?void 0:n.copy)==null?void 0:g.welcomeSubtitle)!=null?j:"Ask anything about your account or products.",i.append(l,d);let c=f("div","tvw-flex tvw-flex-col tvw-gap-3");o.append(i,c);let w=en({config:n});return Zt(s,r,n),s.append(o,w.footer),{container:s,body:o,messagesWrapper:c,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,introTitle:l,introSubtitle:d,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:w.footer}};var un=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let s=document.createElement("div");s.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",s.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(e),n.appendChild(s),n.appendChild(t),n.appendChild(r),n},Cr=(n,e)=>{let s=f("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=f("img");r.src=t,r.alt=e==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",s.appendChild(r)}else s.textContent=t,s.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else s.textContent=e==="user"?"U":"A",s.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return s},qo=(n,e)=>{let s=f("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?s.textContent=e.format(t):s.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s},xr=(n,e="bubble")=>{let s=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):s.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":s.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:s.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return s},ss=(n,e,s)=>{var g,j,$,m,b,W;let t=(g=e.showCopy)!=null?g:!0,r=(j=e.showUpvote)!=null?j:!0,o=($=e.showDownvote)!=null?$:!0,i=(m=e.visibility)!=null?m:"hover",l=(b=e.align)!=null?b:"right",d=(W=e.layout)!=null?W:"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],y=f("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`),u=null,C=(v,N,x,S)=>{let Y=document.createElement("button");Y.className="tvw-message-action-btn",Y.setAttribute("aria-label",N),Y.setAttribute("title",N),S&&Y.setAttribute("data-action",S);let R=ge(v,14,"currentColor",2);return R&&Y.appendChild(R),Y.addEventListener("click",O=>{O.preventDefault(),O.stopPropagation(),x()}),Y};if(t){let v=C("copy","Copy message",()=>{let N=n.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let x=ge("check",14,"currentColor",2);x&&(v.innerHTML="",v.appendChild(x)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let S=ge("copy",14,"currentColor",2);S&&(v.innerHTML="",v.appendChild(S))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),s!=null&&s.onCopy&&s.onCopy(n),e.onCopy&&e.onCopy(n)},"copy");y.appendChild(v)}if(r){let v=C("thumbs-up","Upvote",()=>{if(u==="upvote")u=null,v.classList.remove("tvw-message-action-active");else{let x=y.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),u="upvote",v.classList.add("tvw-message-action-active");let S={type:"upvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),e.onFeedback&&e.onFeedback(S)}},"upvote");y.appendChild(v)}if(o){let v=C("thumbs-down","Downvote",()=>{if(u==="downvote")u=null,v.classList.remove("tvw-message-action-active");else{let x=y.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),u="downvote",v.classList.add("tvw-message-action-active");let S={type:"downvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),e.onFeedback&&e.onFeedback(S)}},"downvote");y.appendChild(v)}return y},tn=(n,e,s,t,r)=>{var W,v,N,x,S;let o=s!=null?s:{},i=(W=o.layout)!=null?W:"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,y=(x=l==null?void 0:l.position)!=null?x:"left",u=(S=d==null?void 0:d.position)!=null?S:"below",C=xr(n.role,i),g=f("div",C.join(" ")),j=document.createElement("div");if(j.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),w&&u==="inline"&&n.createdAt){let Y=qo(n,d);Y.classList.add("tvw-ml-2","tvw-inline"),j.appendChild(Y)}if(g.appendChild(j),w&&u==="below"&&n.createdAt){let Y=qo(n,d);Y.classList.add("tvw-mt-1"),g.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=un();g.appendChild(Y)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let Y=ss(n,t,r);g.appendChild(Y)}if(!c||n.role==="system")return g;let m=f("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),b=Cr(l,n.role);return y==="right"||y==="left"&&n.role==="user"?m.append(g,b):m.append(b,g),g.classList.remove("tvw-max-w-[85%]"),g.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),m},Uo=(n,e,s,t,r)=>{let o=s!=null?s:{};return n.role==="user"&&o.renderUserMessage?o.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&o.renderAssistantMessage?o.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):tn(n,e,s,t,r)};var os=new Set,rs=n=>{let e=n.reasoning,s=f("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return s;let t=os.has(n.id),r=f("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false");let o=f("div","tvw-flex tvw-flex-col tvw-text-left"),i=f("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",o.appendChild(i);let l=f("span","tvw-text-xs tvw-text-cw-primary");l.textContent=Io(e),o.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let d=f("div","tvw-flex tvw-items-center"),w=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=t?"Hide":"Show";let y=f("div","tvw-flex tvw-items-center tvw-ml-auto");y.append(d),r.append(o,y);let u=f("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");u.style.display=t?"":"none";let C=e.chunks.join(""),g=f("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");g.textContent=C||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),u.appendChild(g);let j=()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let b=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);b?d.appendChild(b):d.textContent=t?"Hide":"Show",u.style.display=t?"":"none"},$=()=>{t=!t,t?os.add(n.id):os.delete(n.id),j()};return r.addEventListener("pointerdown",m=>{m.preventDefault(),$()}),r.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),$())}),j(),s.append(r,u),s};var is=new Set,as=(n,e)=>{var $;let s=n.toolCall,t=($=e==null?void 0:e.toolCall)!=null?$:{},r=f("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!s)return r;let o=is.has(n.id),i=f("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"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=f("div","tvw-flex tvw-flex-col tvw-text-left"),d=f("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=$o(s),l.appendChild(d);let c=f("div","tvw-flex tvw-items-center"),w=t.toggleTextColor||t.headerTextColor||"currentColor",y=ge(o?"chevron-up":"chevron-down",16,w,2);y?c.appendChild(y):c.textContent=o?"Hide":"Show";let u=f("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");u.append(c),i.append(l,u);let C=f("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(C.style.display=o?"":"none",t.contentBackgroundColor&&(C.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(C.style.color=t.contentTextColor),t.contentPaddingX&&(C.style.paddingLeft=t.contentPaddingX,C.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(C.style.paddingTop=t.contentPaddingY,C.style.paddingBottom=t.contentPaddingY),s.name){let m=f("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=s.name,C.appendChild(m)}if(s.args!==void 0){let m=f("div","tvw-space-y-1"),b=f("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Arguments";let W=f("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Gn(s.args),m.append(b,W),C.appendChild(m)}if(s.chunks&&s.chunks.length){let m=f("div","tvw-space-y-1"),b=f("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Activity";let W=f("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=s.chunks.join(`
16
+ `),m.append(b,W),C.appendChild(m)}if(s.status==="complete"&&s.result!==void 0){let m=f("div","tvw-space-y-1"),b=f("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Result";let W=f("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Gn(s.result),m.append(b,W),C.appendChild(m)}if(s.status==="complete"&&typeof s.duration=="number"){let m=f("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${s.duration}ms`,C.appendChild(m)}let g=()=>{i.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",b=ge(o?"chevron-up":"chevron-down",16,m,2);b?c.appendChild(b):c.textContent=o?"Hide":"Show",C.style.display=o?"":"none"},j=()=>{o=!o,o?is.add(n.id):is.delete(n.id),g()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),j()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),j())}),g(),r.append(i,C),r};var zo=n=>{let e=[];return{buttons:e,render:(t,r,o,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(C=>C.role==="user"))return;let w=document.createDocumentFragment(),y=r?r.isStreaming():!1,u=C=>{switch(C){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(C=>{let g=f("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");g.type="button",g.textContent=C,g.disabled=y,l!=null&&l.fontFamily&&(g.style.fontFamily=u(l.fontFamily)),l!=null&&l.fontWeight&&(g.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(g.style.paddingLeft=l.paddingX,g.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(g.style.paddingTop=l.paddingY,g.style.paddingBottom=l.paddingY),g.addEventListener("click",()=>{!r||r.isStreaming()||(o.value="",r.sendMessage(C))}),w.appendChild(g),e.push(g)}),n.appendChild(w)}}};var Jo={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"}},ls=(n,e,s,t)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(o=>{var g,j,$;if(o.dataset.enhanced==="true")return;let i=(g=o.dataset.tvForm)!=null?g:"init";o.dataset.enhanced="true";let l=(j=Jo[i])!=null?j:Jo.init;o.classList.add("tvw-form-card","tvw-space-y-4");let d=f("div","tvw-space-y-1"),c=f("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=l.title,d.appendChild(c),l.description){let m=f("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,d.appendChild(m)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var x,S;let b=f("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");b.htmlFor=`${e.id}-${i}-${m.name}`;let W=f("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");W.textContent=m.label,b.appendChild(W);let v=(x=m.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=`${e.id}-${i}-${m.name}`,N.name=m.name,N.placeholder=(S=m.placeholder)!=null?S:"",m.required&&(N.required=!0),b.appendChild(N),w.appendChild(b)});let y=f("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),u=f("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),C=f("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");C.type="submit",C.textContent=($=l.submitLabel)!=null?$:"Submit",y.appendChild(u),y.appendChild(C),w.appendChild(y),o.replaceChildren(d,w),w.addEventListener("submit",async m=>{var N,x;m.preventDefault();let b=(N=s.formEndpoint)!=null?N:"/form",W=new FormData(w),v={};W.forEach((S,Y)=>{v[Y]=S}),v.type=i,C.disabled=!0,u.textContent="Submitting\u2026";try{let S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let Y=await S.json();u.textContent=(x=Y.message)!=null?x:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await t.sendMessage(String(Y.nextPrompt))}catch(S){u.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{C.disabled=!1}})})};var ds=class{constructor(){this.plugins=new Map}register(e){var s;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(s=e.onRegister)==null||s.call(e)}unregister(e){var t;let s=this.plugins.get(e);s&&((t=s.onUnregister)==null||t.call(s),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,s)=>{var t,r;return((t=s.priority)!=null?t:0)-((r=e.priority)!=null?r:0)})}getForInstance(e){let s=this.getAll();if(!e||e.length===0)return s;let t=new Set(e.map(o=>o.id));return[...s.filter(o=>!t.has(o.id)),...e].sort((o,i)=>{var l,d;return((l=i.priority)!=null?l:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var s;return(s=e.onUnregister)==null?void 0:s.call(e)}),this.plugins.clear()}},pn=new ds;var cs={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"},us={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"},Te={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:cs,darkTheme:us,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 Pn(n){var e,s,t,r,o,i,l,d,c,w,y,u,C,g,j,$,m,b,W;return n?{...Te,...n,theme:{...Te.theme,...n.theme},darkTheme:{...Te.darkTheme,...n.darkTheme},launcher:{...Te.launcher,...n.launcher,clearChat:{...(e=Te.launcher)==null?void 0:e.clearChat,...(s=n.launcher)==null?void 0:s.clearChat}},copy:{...Te.copy,...n.copy},sendButton:{...Te.sendButton,...n.sendButton},statusIndicator:{...Te.statusIndicator,...n.statusIndicator},voiceRecognition:{...Te.voiceRecognition,...n.voiceRecognition},features:{...Te.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Te.suggestionChips,suggestionChipsConfig:{...Te.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Te.layout,...n.layout,header:{...(r=Te.layout)==null?void 0:r.header,...(o=n.layout)==null?void 0:o.header},messages:{...(i=Te.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(c=(d=Te.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(y=(w=n.layout)==null?void 0:w.messages)==null?void 0:y.avatar},timestamp:{...(C=(u=Te.layout)==null?void 0:u.messages)==null?void 0:C.timestamp,...(j=(g=n.layout)==null?void 0:g.messages)==null?void 0:j.timestamp}},slots:{...($=Te.layout)==null?void 0:$.slots,...(m=n.layout)==null?void 0:m.slots}},markdown:{...Te.markdown,...n.markdown,options:{...(b=Te.markdown)==null?void 0:b.options,...(W=n.markdown)==null?void 0:W.options}},messageActions:{...Te.messageActions,...n.messageActions}}:Te}var Yo=()=>{let n=new Map,e=(r,o)=>(n.has(r)||n.set(r,new Set),n.get(r).add(o),()=>s(r,o)),s=(r,o)=>{var i;(i=n.get(r))==null||i.delete(o)};return{on:e,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 Sr=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Ar=n=>{let e=n.trim(),s=e.indexOf("{");if(s===-1)return null;let t=0;for(let r=s;r<e.length;r+=1){let o=e[r];if(o==="{"&&(t+=1),o==="}"&&(t-=1,t===0))return e.slice(s,r+1)}return null},gn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Sr(n),s=Ar(e);if(!s)return null;let t=JSON.parse(s);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...o}=t;return{type:String(r),payload:o,raw:t}}catch{return null}},ps=n=>typeof n=="string"?n:n==null?"":String(n),Kt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:ps(n.payload.text)},messageAndClick:(n,e)=>{var r;if(n.type!=="message_and_click")return;let s=n.payload,t=ps(s.element);if(t&&((r=e.document)!=null&&r.querySelector)){let o=e.document.querySelector(t);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:ps(s.text)}}},Ko=n=>Array.isArray(n)?n.map(e=>String(e)):[],mn=n=>{let e=new Set(Ko(n.getMetadata().processedActionMessageIds)),s=()=>{e=new Set(Ko(n.getMetadata().processedActionMessageIds))},t=()=>{let o=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||e.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;e.add(o.message.id),t();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.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!w)continue;if(w.handled){let y=w.persistMessage!==!1;return{text:w.displayText!==void 0?w.displayText:"",persist:y}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:s}};var Tr=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},Er=n=>n.map(e=>({...e,streaming:!1})),In=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let s=e();return s?Tr(s.getItem(n)):null},save:s=>{let t=e();if(t)try{let r={...s,messages:s.messages?Er(s.messages):void 0};t.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let s=e();if(s)try{s.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var gs=class{constructor(){this.components=new Map}register(e,s){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,s)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([s,t])=>{this.register(s,t)})}},nn=new gs;var sn=require("partial-json");function Mr(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function kr(n,e){if(!Mr(n))return null;let s=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:s,raw:e}}function $n(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:s=>{let t=s.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(s.length<=e)return n;try{let r=(0,sn.parse)(s,sn.STR|sn.OBJ),o=kr(r,s);o&&(n=o)}catch{}return e=s.length,n},reset:()=>{n=null,e=0}}}function Xo(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Fn(n,e){let{config:s,message:t,onPropsUpdate:r}=e,o=nn.get(n.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,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 Vo(){let n=$n();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Nn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function On(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var Wr=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Dn(n){let{onSubmit:e,onDismiss:s,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:c=Wr}=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 y=null,u=document.createElement("div");u.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let g=document.createElement("h3");g.className="tvw-feedback-title",g.textContent=t,C.appendChild(g);let j=document.createElement("p");j.className="tvw-feedback-subtitle",j.textContent=r,C.appendChild(j),u.appendChild(C);let $=document.createElement("div");$.className="tvw-feedback-rating tvw-feedback-rating-csat",$.setAttribute("role","radiogroup"),$.setAttribute("aria-label","Satisfaction rating from 1 to 5");let m=[];for(let x=1;x<=5;x++){let S=document.createElement("button");S.type="button",S.className="tvw-feedback-rating-btn tvw-feedback-star-btn",S.setAttribute("role","radio"),S.setAttribute("aria-checked","false"),S.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${c[x-1]}`),S.title=c[x-1],S.dataset.rating=String(x),S.innerHTML=`
17
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
- `,S.addEventListener("click",()=>{w=x,h.forEach((X,B)=>{let j=B<x;X.classList.toggle("selected",j),X.setAttribute("aria-checked",B===x-1?"true":"false")})}),h.push(S),I.appendChild(S)}u.appendChild(I);let b=null;if(c){let x=document.createElement("div");x.className="tvw-feedback-comment-container",b=document.createElement("textarea"),b.className="tvw-feedback-comment",b.placeholder=o,b.rows=3,b.setAttribute("aria-label","Additional comments"),x.appendChild(b),u.appendChild(x)}let W=document.createElement("div");W.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=l,v.addEventListener("click",()=>{s==null||s(),f.remove()});let D=document.createElement("button");return D.type="button",D.className="tvw-feedback-btn tvw-feedback-btn-submit",D.textContent=i,D.addEventListener("click",async()=>{if(w===null){I.classList.add("tvw-feedback-shake"),setTimeout(()=>I.classList.remove("tvw-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let x=(b==null?void 0:b.value.trim())||void 0;await e(w,x),f.remove()}catch(x){D.disabled=!1,D.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),W.appendChild(v),W.appendChild(D),u.appendChild(W),f.appendChild(u),f}function Un(n){let{onSubmit:e,onDismiss:s,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:d="Not likely",highLabel:f="Very likely"}=n,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-nps",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Net Promoter Score feedback");let u=null,C=document.createElement("div");C.className="tvw-feedback-content";let g=document.createElement("div");g.className="tvw-feedback-header";let U=document.createElement("h3");U.className="tvw-feedback-title",U.textContent=t,g.appendChild(U);let I=document.createElement("p");I.className="tvw-feedback-subtitle",I.textContent=r,g.appendChild(I),C.appendChild(g);let h=document.createElement("div");h.className="tvw-feedback-rating tvw-feedback-rating-nps",h.setAttribute("role","radiogroup"),h.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="tvw-feedback-labels";let W=document.createElement("span");W.className="tvw-feedback-label-low",W.textContent=d;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,b.appendChild(W),b.appendChild(v);let D=document.createElement("div");D.className="tvw-feedback-numbers";let x=[];for(let Z=0;Z<=10;Z++){let _=document.createElement("button");_.type="button",_.className="tvw-feedback-rating-btn tvw-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${Z} out of 10`),_.textContent=String(Z),_.dataset.rating=String(Z),Z<=6?_.classList.add("tvw-feedback-detractor"):Z<=8?_.classList.add("tvw-feedback-passive"):_.classList.add("tvw-feedback-promoter"),_.addEventListener("click",()=>{u=Z,x.forEach((K,Q)=>{K.classList.toggle("selected",Q===Z),K.setAttribute("aria-checked",Q===Z?"true":"false")})}),x.push(_),D.appendChild(_)}h.appendChild(b),h.appendChild(D),C.appendChild(h);let S=null;if(c){let Z=document.createElement("div");Z.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),Z.appendChild(S),C.appendChild(Z)}let X=document.createElement("div");X.className="tvw-feedback-actions";let B=document.createElement("button");B.type="button",B.className="tvw-feedback-btn tvw-feedback-btn-skip",B.textContent=l,B.addEventListener("click",()=>{s==null||s(),w.remove()});let j=document.createElement("button");return j.type="button",j.className="tvw-feedback-btn tvw-feedback-btn-submit",j.textContent=i,j.addEventListener("click",async()=>{if(u===null){D.classList.add("tvw-feedback-shake"),setTimeout(()=>D.classList.remove("tvw-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let Z=(S==null?void 0:S.value.trim())||void 0;await e(u,Z),w.remove()}catch(Z){j.disabled=!1,j.textContent=i,console.error("[NPS Feedback] Failed to submit:",Z)}}),X.appendChild(B),X.appendChild(j),C.appendChild(X),w.appendChild(C),w}var on="vanilla-agent-chat-history",Cr=30*1e3,us=n=>!n||typeof n!="object"?{}:{...n},Uo=n=>n.map(e=>({...e,streaming:!1})),zo=(n,e)=>{let s=n!=null&&n.markdown?mn(n.markdown):null;return t=>{var i,l,c;let r=(i=t.text)!=null?i:"",o=(l=t.message.rawContent)!=null?l:null;if(e){let d=e.process({text:r,raw:o!=null?o:r,message:t.message,streaming:t.streaming});d!==null&&(r=d.text,d.persist||(t.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...t,text:r,raw:(c=o!=null?o:t.text)!=null?c:""}):s?s(r):En(r)}},zn=(n,e,s)=>{var de,pe,Pe,ge,De,it,ht,hs,ms,fs,ws,ys,vs,bs;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Fn(e),r=yn.getForInstance(t.plugins);t.components&&nn.registerAll(t.components);let o=Do(),i=(de=t.storageAdapter)!=null?de:Nn(),l={},c=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")c=a;else if(a){let p=a;p.metadata&&(l=us(p.metadata)),(pe=p.messages)!=null&&pe.length&&(t={...t,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let d=()=>l,f=a=>{var E;l=(E=a({...l}))!=null?E:{},Mt()},w=t.actionParsers&&t.actionParsers.length?t.actionParsers:[vn],u=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick],C=bn({parsers:w,handlers:u,getMetadata:d,updateMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let g=(ge=(Pe=t.launcher)==null?void 0:Pe.enabled)!=null?ge:!0,U=(it=(De=t.launcher)==null?void 0:De.autoExpand)!=null?it:!1,I=U,h=g,b=g?U:!0,W=zo(t,C),v=(hs=(ht=t.features)==null?void 0:ht.showReasoning)!=null?hs:!0,D=(fs=(ms=t.features)==null?void 0:ms.showToolCalls)!=null?fs:!0,x={onCopy:a=>{var p,E;o.emit("message:copy",a),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(a.id,"copy").catch(O=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",O)}),(E=(p=t.messageActions)==null?void 0:p.onCopy)==null||E.call(p,a)},onFeedback:a=>{var p,E;o.emit("message:feedback",a),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(a.messageId,a.type).catch(O=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",O)}),(E=(p=t.messageActions)==null?void 0:p.onFeedback)==null||E.call(p,a)}},S=(ws=t.statusIndicator)!=null?ws:{},X=a=>{var p,E,O,k;return a==="idle"?(p=S.idleText)!=null?p:Xe.idle:a==="connecting"?(E=S.connectingText)!=null?E:Xe.connecting:a==="connected"?(O=S.connectedText)!=null?O:Xe.connected:a==="error"?(k=S.errorText)!=null?k:Xe.error:Xe[a]},{wrapper:B,panel:j}=Po(t),Z=Ro(t,g),{container:_,body:K,messagesWrapper:Q,suggestions:ne,textarea:re,sendButton:q,sendButtonWrapper:qe,composerForm:Ve,statusText:nt,introTitle:bt,introSubtitle:Ct,closeButton:Y,iconHolder:fe,headerTitle:mt,headerSubtitle:ft,header:Ge,footer:st}=Z,H=Z.micButton,He=Z.micButtonWrapper,at=r.find(a=>a.renderHeader);if(at!=null&&at.renderHeader){let a=at.renderHeader({config:t,defaultRenderer:()=>{let p=Ot({config:t,showClose:g});return Qt(_,p,t),p.header},onClose:()=>Ke(!1,"user")});if(a){let p=_.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Ge=a)}}let lt=r.find(a=>a.renderComposer);if(lt!=null&&lt.renderComposer){let a=lt.renderComposer({config:t,defaultRenderer:()=>en({config:t}).footer,onSubmit:p=>{R&&!R.isStreaming()&&R.sendMessage(p)},disabled:!1});a&&(st.replaceWith(a),st=a)}(()=>{var O,k;let a=(k=(O=t.layout)==null?void 0:O.slots)!=null?k:{},p=ee=>{switch(ee){case"body-top":return _.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Q;case"footer-top":return ne;case"composer":return Ve;case"footer-bottom":return nt;default:return null}},E=(ee,N)=>{var T;switch(ee){case"header-left":case"header-center":case"header-right":if(ee==="header-left")Ge.insertBefore(N,Ge.firstChild);else if(ee==="header-right")Ge.appendChild(N);else{let z=Ge.querySelector(".tvw-flex-col");z?(T=z.parentNode)==null||T.insertBefore(N,z.nextSibling):Ge.appendChild(N)}break;case"body-top":let G=K.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(N):K.insertBefore(N,K.firstChild);break;case"body-bottom":K.appendChild(N);break;case"footer-top":ne.replaceWith(N);break;case"footer-bottom":nt.replaceWith(N);break;default:break}};for(let[ee,N]of Object.entries(a))if(N)try{let T=N({config:t,defaultContent:()=>p(ee)});T&&E(ee,T)}catch(T){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ee}":`,T)}})(),j.appendChild(_),n.appendChild(B);let wt=()=>{var ae,Re,ct,le,ut,$t,Pt,kt,Ut,Rt,zt,pt,It,Ft,An,gn;let a=(Re=(ae=t.launcher)==null?void 0:ae.sidebarMode)!=null?Re:!1,p=a||((le=(ct=t.launcher)==null?void 0:ct.fullHeight)!=null?le:!1),E=(ut=t.theme)!=null?ut:{},O=(Pt=($t=t.launcher)==null?void 0:$t.position)!=null?Pt:"bottom-left",k=O==="bottom-left"||O==="top-left",ee=a?"none":"1px solid var(--tvw-cw-border)",N=a?k?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",T=a?"0":"16px",G=(kt=E.panelBorder)!=null?kt:ee,z=(Ut=E.panelShadow)!=null?Ut:N,P=(Rt=E.panelBorderRadius)!=null?Rt:T;n.style.cssText="",B.style.cssText="",j.style.cssText="",_.style.cssText="",K.style.cssText="",st.style.cssText="";let J=(pt=(zt=t==null?void 0:t.launcher)==null?void 0:zt.width)!=null?pt:t==null?void 0:t.launcherWidth,Be=J!=null?J:"min(400px, calc(100vw - 24px))";a||(j.style.width=Be,j.style.maxWidth=Be),j.style.boxShadow=z,j.style.borderRadius=P,_.style.border=G,_.style.borderRadius=P;let he=((It=t.launcher)==null?void 0:It.enabled)===!1;if(p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",B.style.display="flex",B.style.flexDirection="column",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.maxHeight="100%",B.style.height="100%",he&&(B.style.overflow="hidden"),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",_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.overflow="hidden",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",st.style.flexShrink="0"),B.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!a&&!he&&((Ft=vt[O])!=null?Ft:vt["bottom-right"]).split(" ").forEach(Vt=>B.classList.add(Vt)),a){let Yt=(gn=(An=t.launcher)==null?void 0:An.sidebarWidth)!=null?gn:"420px";B.style.cssText=`
20
+ `,S.addEventListener("click",()=>{y=x,m.forEach((Y,R)=>{let O=R<x;Y.classList.toggle("selected",O),Y.setAttribute("aria-checked",R===x-1?"true":"false")})}),m.push(S),$.appendChild(S)}u.appendChild($);let b=null;if(d){let x=document.createElement("div");x.className="tvw-feedback-comment-container",b=document.createElement("textarea"),b.className="tvw-feedback-comment",b.placeholder=o,b.rows=3,b.setAttribute("aria-label","Additional comments"),x.appendChild(b),u.appendChild(x)}let W=document.createElement("div");W.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=l,v.addEventListener("click",()=>{s==null||s(),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(y===null){$.classList.add("tvw-feedback-shake"),setTimeout(()=>$.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let x=(b==null?void 0:b.value.trim())||void 0;await e(y,x),w.remove()}catch(x){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),W.appendChild(v),W.appendChild(N),u.appendChild(W),w.appendChild(u),w}function _n(n){let{onSubmit:e,onDismiss:s,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:w="Very likely"}=n,y=document.createElement("div");y.className="tvw-feedback-container tvw-feedback-nps",y.setAttribute("role","dialog"),y.setAttribute("aria-label","Net Promoter Score feedback");let u=null,C=document.createElement("div");C.className="tvw-feedback-content";let g=document.createElement("div");g.className="tvw-feedback-header";let j=document.createElement("h3");j.className="tvw-feedback-title",j.textContent=t,g.appendChild(j);let $=document.createElement("p");$.className="tvw-feedback-subtitle",$.textContent=r,g.appendChild($),C.appendChild(g);let m=document.createElement("div");m.className="tvw-feedback-rating tvw-feedback-rating-nps",m.setAttribute("role","radiogroup"),m.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="tvw-feedback-labels";let W=document.createElement("span");W.className="tvw-feedback-label-low",W.textContent=c;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=w,b.appendChild(W),b.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let x=[];for(let G=0;G<=10;G++){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 ${G} out of 10`),D.textContent=String(G),D.dataset.rating=String(G),G<=6?D.classList.add("tvw-feedback-detractor"):G<=8?D.classList.add("tvw-feedback-passive"):D.classList.add("tvw-feedback-promoter"),D.addEventListener("click",()=>{u=G,x.forEach((U,Q)=>{U.classList.toggle("selected",Q===G),U.setAttribute("aria-checked",Q===G?"true":"false")})}),x.push(D),N.appendChild(D)}m.appendChild(b),m.appendChild(N),C.appendChild(m);let S=null;if(d){let G=document.createElement("div");G.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"),G.appendChild(S),C.appendChild(G)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let R=document.createElement("button");R.type="button",R.className="tvw-feedback-btn tvw-feedback-btn-skip",R.textContent=l,R.addEventListener("click",()=>{s==null||s(),y.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(u===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let G=(S==null?void 0:S.value.trim())||void 0;await e(u,G),y.remove()}catch(G){O.disabled=!1,O.textContent=i,console.error("[NPS Feedback] Failed to submit:",G)}}),Y.appendChild(R),Y.appendChild(O),C.appendChild(Y),y.appendChild(C),y}var on="vanilla-agent-chat-history",Lr=30*1e3,ms=n=>!n||typeof n!="object"?{}:{...n},Go=n=>n.map(e=>({...e,streaming:!1})),Qo=(n,e)=>{let s=n!=null&&n.markdown?dn(n.markdown):null;return t=>{var i,l,d;let r=(i=t.text)!=null?i:"",o=(l=t.message.rawContent)!=null?l:null;if(e){let c=e.process({text:r,raw:o!=null?o:r,message:t.message,streaming:t.streaming});c!==null&&(r=c.text,c.persist||(t.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...t,text:r,raw:(d=o!=null?o:t.text)!=null?d:""}):s?s(r):xn(r)}},jn=(n,e,s)=>{var Re,fe,_e,rt,mt,ws,ys,vs,bs,Cs,xs,Ss,As,Ts;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Pn(e),r=pn.getForInstance(t.plugins);t.components&&nn.registerAll(t.components);let o=Yo(),i=(Re=t.storageAdapter)!=null?Re:In(),l={},d=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")d=a;else if(a){let p=a;p.metadata&&(l=ms(p.metadata)),(fe=p.messages)!=null&&fe.length&&(t={...t,initialMessages:p.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()},y=t.actionParsers&&t.actionParsers.length?t.actionParsers:[gn],u=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick],C=mn({parsers:y,handlers:u,getMetadata:c,updateMetadata:w,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let g=(rt=(_e=t.launcher)==null?void 0:_e.enabled)!=null?rt:!0,j=(ws=(mt=t.launcher)==null?void 0:mt.autoExpand)!=null?ws:!1,$=j,m=g,b=g?j:!0,W=Qo(t,C),v=(vs=(ys=t.features)==null?void 0:ys.showReasoning)!=null?vs:!0,N=(Cs=(bs=t.features)==null?void 0:bs.showToolCalls)!=null?Cs:!0,x={onCopy:a=>{var p,T;o.emit("message:copy",a),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(a.id,"copy").catch(F=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",F)}),(T=(p=t.messageActions)==null?void 0:p.onCopy)==null||T.call(p,a)},onFeedback:a=>{var p,T;o.emit("message:feedback",a),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(a.messageId,a.type).catch(F=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",F)}),(T=(p=t.messageActions)==null?void 0:p.onFeedback)==null||T.call(p,a)}},S=(xs=t.statusIndicator)!=null?xs:{},Y=a=>{var p,T,F,B;return a==="idle"?(p=S.idleText)!=null?p:Ve.idle:a==="connecting"?(T=S.connectingText)!=null?T:Ve.connecting:a==="connected"?(F=S.connectedText)!=null?F:Ve.connected:a==="error"?(B=S.errorText)!=null?B:Ve.error:Ve[a]},{wrapper:R,panel:O}=_o(t),G=jo(t,g),{container:D,body:U,messagesWrapper:Q,suggestions:ie,textarea:de,sendButton:_,sendButtonWrapper:ze,composerForm:Ge,statusText:nt,introTitle:xt,introSubtitle:St,closeButton:q,iconHolder:ve,headerTitle:ht,headerSubtitle:ft,header:Qe,footer:st}=G,I=G.micButton,Be=G.micButtonWrapper,at=r.find(a=>a.renderHeader);if(at!=null&&at.renderHeader){let a=at.renderHeader({config:t,defaultRenderer:()=>{let p=Ot({config:t,showClose:g});return Zt(D,p,t),p.header},onClose:()=>Ke(!1,"user")});if(a){let p=D.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Qe=a)}}let lt=r.find(a=>a.renderComposer);if(lt!=null&&lt.renderComposer){let a=lt.renderComposer({config:t,defaultRenderer:()=>en({config:t}).footer,onSubmit:p=>{E&&!E.isStreaming()&&E.sendMessage(p)},disabled:!1});a&&(st.replaceWith(a),st=a)}(()=>{var F,B;let a=(B=(F=t.layout)==null?void 0:F.slots)!=null?B:{},p=ne=>{switch(ne){case"body-top":return D.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Q;case"footer-top":return ie;case"composer":return Ge;case"footer-bottom":return nt;default:return null}},T=(ne,pe)=>{var h;switch(ne){case"header-left":case"header-center":case"header-right":if(ne==="header-left")Qe.insertBefore(pe,Qe.firstChild);else if(ne==="header-right")Qe.appendChild(pe);else{let J=Qe.querySelector(".tvw-flex-col");J?(h=J.parentNode)==null||h.insertBefore(pe,J.nextSibling):Qe.appendChild(pe)}break;case"body-top":let ee=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ee?ee.replaceWith(pe):U.insertBefore(pe,U.firstChild);break;case"body-bottom":U.appendChild(pe);break;case"footer-top":ie.replaceWith(pe);break;case"footer-bottom":nt.replaceWith(pe);break;default:break}};for(let[ne,pe]of Object.entries(a))if(pe)try{let h=pe({config:t,defaultContent:()=>p(ne)});h&&T(ne,h)}catch(h){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ne}":`,h)}})(),O.appendChild(D),n.appendChild(R);let wt=()=>{var ue,Pe,it,Xe,he,Ut,Rt,Pt,kt,vn,It,zt,dt,$t,Ft,bn;let a=(Pe=(ue=t.launcher)==null?void 0:ue.sidebarMode)!=null?Pe:!1,p=a||((Xe=(it=t.launcher)==null?void 0:it.fullHeight)!=null?Xe:!1),T=(he=t.theme)!=null?he:{},F=(Rt=(Ut=t.launcher)==null?void 0:Ut.position)!=null?Rt:"bottom-left",B=F==="bottom-left"||F==="top-left",ne=a?"none":"1px solid var(--tvw-cw-border)",pe=a?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)",h=a?"0":"16px",ee=(Pt=T.panelBorder)!=null?Pt:ne,J=(kt=T.panelShadow)!=null?kt:pe,oe=(vn=T.panelBorderRadius)!=null?vn:h;n.style.cssText="",R.style.cssText="",O.style.cssText="",D.style.cssText="",U.style.cssText="",st.style.cssText="";let P=(zt=(It=t==null?void 0:t.launcher)==null?void 0:It.width)!=null?zt:t==null?void 0:t.launcherWidth,te=P!=null?P:"min(400px, calc(100vw - 24px))";a||(O.style.width=te,O.style.maxWidth=te),O.style.boxShadow=J,O.style.borderRadius=oe,D.style.border=ee,D.style.borderRadius=oe;let we=((dt=t.launcher)==null?void 0:dt.enabled)===!1;if(p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",R.style.display="flex",R.style.flexDirection="column",R.style.flex="1 1 0%",R.style.minHeight="0",R.style.maxHeight="100%",R.style.height="100%",we&&(R.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",D.style.display="flex",D.style.flexDirection="column",D.style.flex="1 1 0%",D.style.minHeight="0",D.style.maxHeight="100%",D.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",st.style.flexShrink="0"),R.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&&(($t=Ct[F])!=null?$t:Ct["bottom-right"]).split(" ").forEach(Vt=>R.classList.add(Vt)),a){let Jt=(bn=(Ft=t.launcher)==null?void 0:Ft.sidebarWidth)!=null?bn:"420px";R.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
24
- width: ${Yt} !important;
24
+ width: ${Jt} !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
- ${k?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
- `,j.style.cssText=`
31
+ ${B?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
+ `,O.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: ${z} !important;
44
- border-radius: ${P} !important;
45
- `,j.style.setProperty("width","100%","important"),j.style.setProperty("max-width","100%","important"),_.style.cssText=`
43
+ box-shadow: ${J} !important;
44
+ border-radius: ${oe} !important;
45
+ `,O.style.setProperty("width","100%","important"),O.style.setProperty("max-width","100%","important"),D.style.cssText=`
46
46
  display: flex !important;
47
47
  flex-direction: column !important;
48
48
  flex: 1 1 0% !important;
@@ -51,17 +51,18 @@
51
51
  min-height: 0 !important;
52
52
  max-height: 100% !important;
53
53
  overflow: hidden !important;
54
- border-radius: ${P} !important;
55
- border: ${G} !important;
54
+ border-radius: ${oe} !important;
55
+ border: ${ee} !important;
56
56
  `,st.style.cssText=`
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!he){let Yt="max-height: -moz-available !important; max-height: stretch !important;",Vt=a?"":"padding-top: 1.25em !important;";B.style.cssText+=Yt+Vt}};wt(),Gn(n,t);let Ie=[],ot=No(ne),Ue=null,R,dt=!1,Se=!0,Oe=0,te=0,Ae=null,Te=!1,ze=0,Ye=!1,xt=125,Bt=2e3,yt=5,Et=50,St=new Map,ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Ht=(vs=(ys=t.voiceRecognition)==null?void 0:ys.autoResume)!=null?vs:!1,Le=a=>{o.emit("voice:state",{active:ye.active,source:a,timestamp:Date.now()})},Je=()=>{f(a=>({...a,voiceState:{active:ye.active,timestamp:Date.now(),manuallyDeactivated:ye.manuallyDeactivated}}))},At=()=>{var O,k;if(((O=t.voiceRecognition)==null?void 0:O.enabled)===!1)return;let a=us(l.voiceState),p=!!a.active,E=Number((k=a.timestamp)!=null?k:0);ye.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-E<Cr&&setTimeout(()=>{ye.active||(ye.manuallyDeactivated=!1,Ne("restore"))},1e3)},Dt=()=>R?Uo(R.getMessages()).filter(a=>!a.__skipPersist):[];function Mt(a){if(!(i!=null&&i.save))return;let E={messages:a?Uo(a):R?Dt():[],metadata:l};try{let O=i.save(E);O instanceof Promise&&O.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(O){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",O)}}let jt=(a=!1)=>{if(!Se)return;let p=Date.now();Te&&p<ze&&!a||(Te&&p>=ze&&(Te=!1),!(!a&&!dt)&&(p-te<xt||(te=p,Ae&&cancelAnimationFrame(Ae),Ae=requestAnimationFrame(()=>{Te||!Se||(Ye=!0,K.scrollTop=K.scrollHeight,Oe=K.scrollTop,requestAnimationFrame(()=>{Ye=!1}),Ae=null)}))))},Wt=null,Cn=()=>B.querySelector("#vanilla-agent-scroll-container")||K,xn=(a,p=500)=>{let E=a.scrollTop,O=a.clientHeight,k=a.scrollHeight,ee=k-E;if(E+O>=k-2||Math.abs(ee)<5)return;Wt!==null&&(cancelAnimationFrame(Wt),Wt=null);let T=performance.now(),G=P=>1-Math.pow(1-P,3),z=P=>{let J=a.scrollHeight;J!==k&&(k=J,ee=k-E);let Be=P-T,he=Math.min(Be/p,1),ae=G(he),Re=E+ee*ae;a.scrollTop=Re,he<1?Wt=requestAnimationFrame(z):(a.scrollTop=a.scrollHeight,Wt=null)};Wt=requestAnimationFrame(z)},Sn=a=>{let p=new Map;a.forEach(E=>{let O=St.get(E.id);p.set(E.id,{streaming:E.streaming,role:E.role}),!O&&E.role==="assistant"&&o.emit("assistant:message",E),E.role==="assistant"&&(O!=null&&O.streaming)&&E.streaming===!1&&o.emit("assistant:complete",E)}),St.clear(),p.forEach((E,O)=>{St.set(O,E)})},_t=(a,p,E)=>{a.innerHTML="";let O=document.createDocumentFragment();p.forEach(T=>{var Be,he;let G=null,z=r.find(ae=>!!(T.variant==="reasoning"&&ae.renderReasoning||T.variant==="tool"&&ae.renderToolCall||!T.variant&&ae.renderMessage)),P=(Be=t.layout)==null?void 0:Be.messages;if(z)if(T.variant==="reasoning"&&T.reasoning&&z.renderReasoning){if(!v)return;G=z.renderReasoning({message:T,defaultRenderer:()=>os(T),config:t})}else if(T.variant==="tool"&&T.toolCall&&z.renderToolCall){if(!D)return;G=z.renderToolCall({message:T,defaultRenderer:()=>is(T,t),config:t})}else z.renderMessage&&(G=z.renderMessage({message:T,defaultRenderer:()=>{let ae=tn(T,E,P,t.messageActions,x);return T.role!=="user"&&as(ae,T,t,R),ae},config:t}));if(!G&&T.role==="assistant"&&!T.variant&&t.enableComponentStreaming!==!1&&jn(T)){let Re=_n(T);if(Re){let ct=Dn(Re,{config:t,message:T,transform:E});if(ct){let le=document.createElement("div");if(le.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),le.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let ut=document.createElement("div");ut.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ut.innerHTML=E({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),le.appendChild(ut)}le.appendChild(ct),G=le}}}if(!G)if(T.variant==="reasoning"&&T.reasoning){if(!v)return;G=os(T)}else if(T.variant==="tool"&&T.toolCall){if(!D)return;G=is(T,t)}else{let ae=(he=t.layout)==null?void 0:he.messages;ae!=null&&ae.renderUserMessage&&T.role==="user"?G=ae.renderUserMessage({message:T,config:t,streaming:!!T.streaming}):ae!=null&&ae.renderAssistantMessage&&T.role==="assistant"?G=ae.renderAssistantMessage({message:T,config:t,streaming:!!T.streaming}):G=tn(T,E,ae,t.messageActions,x),T.role!=="user"&&G&&as(G,T,t,R)}let J=document.createElement("div");J.className="tvw-flex",T.role==="user"&&J.classList.add("tvw-justify-end"),J.appendChild(G),O.appendChild(J)});let k=p.some(T=>T.role==="assistant"&&T.streaming),ee=p[p.length-1],N=(ee==null?void 0:ee.role)==="assistant"&&!ee.streaming;if(dt&&p.some(T=>T.role==="user")&&!k&&!N){let T=wn(),G=document.createElement("div");G.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),G.appendChild(T);let z=document.createElement("div");z.className="tvw-flex",z.appendChild(G),O.appendChild(z)}a.appendChild(O),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let T=Cn();xn(T)})})},qt=()=>{g&&(b?(B.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"),y?y.element.style.display="none":F&&(F.style.display="none")):(B.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"),y?y.element.style.display="":F&&(F.style.display="")))},Ke=(a,p="user")=>{if(!g||b===a)return;let E=b;b=a,qt(),b&&(be(),jt(!0));let O={open:b,source:p,timestamp:Date.now()};b&&!E?o.emit("widget:opened",O):!b&&E&&o.emit("widget:closed",O),o.emit("widget:state",{open:b,launcherEnabled:g,voiceActive:ye.active,streaming:R.isStreaming()})},Xt=a=>{q.disabled=a,H&&(H.disabled=a),ot.buttons.forEach(p=>{p.disabled=a})},cn=()=>{var k,ee,N,T,G,z,P,J,Be,he,ae,Re,ct,le;bt.textContent=(ee=(k=t.copy)==null?void 0:k.welcomeTitle)!=null?ee:"Hello \u{1F44B}",Ct.textContent=(T=(N=t.copy)==null?void 0:N.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",re.placeholder=(z=(G=t.copy)==null?void 0:G.inputPlaceholder)!=null?z:"How can I help...",((J=(P=t.sendButton)==null?void 0:P.useIcon)!=null?J:!1)||(q.textContent=(he=(Be=t.copy)==null?void 0:Be.sendButtonLabel)!=null?he:"Send");let p=(Re=(ae=t.theme)==null?void 0:ae.inputFontFamily)!=null?Re:"sans-serif",E=(le=(ct=t.theme)==null?void 0:ct.inputFontWeight)!=null?le:"400",O=ut=>{switch(ut){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};re.style.fontFamily=O(p),re.style.fontWeight=E};R=new Zt(t,{onMessagesChanged(a){_t(Q,a,W),R&&(a.some(O=>O.role==="user")?ot.render([],R,re,a):ot.render(t.suggestionChips,R,re,a,t.suggestionChipsConfig)),jt(!dt),Sn(a);let p=[...a].reverse().find(E=>E.role==="user");ye.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Mt(a)},onStatusChanged(a){var O;let p=(O=t.statusIndicator)!=null?O:{},E=k=>{var ee,N,T,G;return k==="idle"?(ee=p.idleText)!=null?ee:Xe.idle:k==="connecting"?(N=p.connectingText)!=null?N:Xe.connecting:k==="connected"?(T=p.connectedText)!=null?T:Xe.connected:k==="error"?(G=p.errorText)!=null?G:Xe.error:Xe[k]};nt.textContent=E(a)},onStreamingChanged(a){dt=a,Xt(a),R&&_t(Q,R.getMessages(),W),a||jt(!0)}}),c&&c.then(a=>{var p;a&&(a.metadata&&(l=us(a.metadata),C.syncFromMetadata()),(p=a.messages)!=null&&p.length&&R.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let un=a=>{a.preventDefault();let p=re.value.trim();p&&(re.value="",R.sendMessage(p))},pn=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),q.click())},A=null,V=!1,ie=null,ve=null,Fe=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ne=(a="user")=>{var ee,N,T,G;if(V||R.isStreaming())return;let p=Fe();if(!p)return;A=new p;let O=(N=((ee=t.voiceRecognition)!=null?ee:{}).pauseDuration)!=null?N:2e3;A.continuous=!0,A.interimResults=!0,A.lang="en-US";let k=re.value;A.onresult=z=>{let P="",J="";for(let he=0;he<z.results.length;he++){let ae=z.results[he],Re=ae[0].transcript;ae.isFinal?P+=Re+" ":J=Re}let Be=k+P+J;re.value=Be,ie&&clearTimeout(ie),(P||J)&&(ie=window.setTimeout(()=>{let he=re.value.trim();he&&A&&V&&(ue(),re.value="",R.sendMessage(he,{viaVoice:!0}))},O))},A.onerror=z=>{z.error!=="no-speech"&&ue()},A.onend=()=>{if(V){let z=re.value.trim();z&&z!==k.trim()&&(re.value="",R.sendMessage(z,{viaVoice:!0})),ue()}};try{if(A.start(),V=!0,ye.active=!0,a!=="system"&&(ye.manuallyDeactivated=!1),Le(a),Je(),H){ve={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor};let z=(T=t.voiceRecognition)!=null?T:{},P=(G=z.recordingBackgroundColor)!=null?G:"#ef4444",J=z.recordingIconColor,Be=z.recordingBorderColor;if(H.classList.add("tvw-voice-recording"),H.style.backgroundColor=P,J){H.style.color=J;let he=H.querySelector("svg");he&&he.setAttribute("stroke",J)}Be&&(H.style.borderColor=Be),H.setAttribute("aria-label","Stop voice recognition")}}catch{ue("system")}},ue=(a="user")=>{if(V){if(V=!1,ie&&(clearTimeout(ie),ie=null),A){try{A.stop()}catch{}A=null}if(ye.active=!1,Le(a),Je(),H){if(H.classList.remove("tvw-voice-recording"),ve){H.style.backgroundColor=ve.backgroundColor,H.style.color=ve.color,H.style.borderColor=ve.borderColor;let p=H.querySelector("svg");p&&p.setAttribute("stroke",ve.color||"currentColor"),ve=null}H.setAttribute("aria-label","Start voice recognition")}}},$=(a,p)=>{var Re,ct,le,ut,$t,Pt,kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let O=m("div","tvw-send-button-wrapper"),k=m("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");k.type="button",k.setAttribute("aria-label","Start voice recognition");let ee=(Re=a==null?void 0:a.iconName)!=null?Re:"mic",N=(ct=p==null?void 0:p.size)!=null?ct:"40px",T=(le=a==null?void 0:a.iconSize)!=null?le:N,G=parseFloat(T)||24,z=(ut=a==null?void 0:a.backgroundColor)!=null?ut:p==null?void 0:p.backgroundColor,P=($t=a==null?void 0:a.iconColor)!=null?$t:p==null?void 0:p.textColor;k.style.width=T,k.style.height=T,k.style.minWidth=T,k.style.minHeight=T,k.style.fontSize="18px",k.style.lineHeight="1";let J=P||"currentColor",Be=ce(ee,G,J,1.5);Be?(k.appendChild(Be),k.style.color=J):(k.textContent="\u{1F3A4}",k.style.color=J),z?k.style.backgroundColor=z:k.classList.add("tvw-bg-cw-primary"),P?k.style.color=P:!P&&!(p!=null&&p.textColor)&&k.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(k.style.borderWidth=a.borderWidth,k.style.borderStyle="solid"),a!=null&&a.borderColor&&(k.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(k.style.paddingLeft=a.paddingX,k.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(k.style.paddingTop=a.paddingY,k.style.paddingBottom=a.paddingY),O.appendChild(k);let he=(Pt=a==null?void 0:a.tooltipText)!=null?Pt:"Start voice recognition";if(((kt=a==null?void 0:a.showTooltip)!=null?kt:!1)&&he){let Ut=m("div","tvw-send-button-tooltip");Ut.textContent=he,O.appendChild(Ut)}return{micButton:k,micButtonWrapper:O}},rt=()=>{if(V){let a=re.value.trim();ye.manuallyDeactivated=!0,Je(),ue("user"),a&&(re.value="",R.sendMessage(a))}else ye.manuallyDeactivated=!1,Je(),Ne("user")};H&&(H.addEventListener("click",rt),Ie.push(()=>{ue("system"),H&&H.removeEventListener("click",rt)}));let se=o.on("assistant:complete",()=>{Ht&&(ye.active||ye.manuallyDeactivated||Ht==="assistant"&&!ye.lastUserMessageWasVoice||setTimeout(()=>{!ye.active&&!ye.manuallyDeactivated&&Ne("auto")},600))});Ie.push(se);let M=()=>{Ke(!b,"user")},y=null,F=null;if(g){let a=r.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:t,defaultRenderer:()=>fn(t,M).element,onToggle:M});p&&(F=p)}F||(y=fn(t,M))}y?n.appendChild(y.element):F&&n.appendChild(F),qt(),ot.render(t.suggestionChips,R,re,void 0,t.suggestionChipsConfig),cn(),Xt(R.isStreaming()),jt(!0),At();let be=()=>{var E,O,k,ee,N,T,G,z;let a=(O=(E=t.launcher)==null?void 0:E.sidebarMode)!=null?O:!1,p=a||((ee=(k=t.launcher)==null?void 0:k.fullHeight)!=null?ee:!1);if(!g){j.style.height="",j.style.width="";return}if(!a){let P=(T=(N=t==null?void 0:t.launcher)==null?void 0:N.width)!=null?T:t==null?void 0:t.launcherWidth,J=P!=null?P:"min(400px, calc(100vw - 24px))";j.style.width=J,j.style.maxWidth=J}if(!p){let P=window.innerHeight,J=64,Be=(z=(G=t.launcher)==null?void 0:G.heightOffset)!=null?z:0,he=Math.max(200,P-J),ae=Math.min(640,he),Re=Math.max(200,ae-Be);j.style.height=`${Re}px`}};be(),window.addEventListener("resize",be),Ie.push(()=>window.removeEventListener("resize",be)),Oe=K.scrollTop;let Ee=()=>{let a=K.scrollTop,p=K.scrollHeight,E=K.clientHeight,O=p-a-E,k=Math.abs(a-Oe);if(Oe=a,!Ye&&!(k<=yt)){if(!Se&&O<Et){Te=!1,Se=!0;return}Se&&O>Et&&(Te=!0,ze=Date.now()+Bt,Se=!1)}};K.addEventListener("scroll",Ee,{passive:!0}),Ie.push(()=>K.removeEventListener("scroll",Ee)),Ie.push(()=>{Ae&&cancelAnimationFrame(Ae)});let Ze=()=>{Y&&(Ue&&(Y.removeEventListener("click",Ue),Ue=null),g?(Y.style.display="",Ue=()=>{b=!1,qt()},Y.addEventListener("click",Ue)):Y.style.display="none")};Ze(),(()=>{let{clearChatButton:a}=Z;a&&a.addEventListener("click",()=>{R.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let E=i.clear();E instanceof Promise&&E.catch(O=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",O)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},C.syncFromMetadata()})})(),Ve.addEventListener("submit",un),re.addEventListener("keydown",pn),Ie.push(()=>{Ve.removeEventListener("submit",un),re.removeEventListener("keydown",pn)}),Ie.push(()=>{R.cancel()}),y?Ie.push(()=>{y==null||y.destroy()}):F&&Ie.push(()=>{F==null||F.remove()});let Ce={update(a){var gn,Yt,Vt,Cs,xs,Ss,As,Ts,Es,Ms,Ws,ks,Ls,Bs,Hs,$s,Ps,Rs,Is,Fs,Ns,Os,Ds,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs,Qs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,ho,mo,fo,wo,yo,vo,bo,Co;let p=t.toolCall;t={...t,...a},wt(),Gn(n,t);let E=yn.getForInstance(t.plugins);if(r.length=0,r.push(...E),g=(Yt=(gn=t.launcher)==null?void 0:gn.enabled)!=null?Yt:!0,U=(Cs=(Vt=t.launcher)==null?void 0:Vt.autoExpand)!=null?Cs:!1,v=(Ss=(xs=t.features)==null?void 0:xs.showReasoning)!=null?Ss:!0,D=(Ts=(As=t.features)==null?void 0:As.showToolCalls)!=null?Ts:!0,((Es=t.launcher)==null?void 0:Es.enabled)===!1&&y&&(y.destroy(),y=null),((Ms=t.launcher)==null?void 0:Ms.enabled)===!1&&F&&(F.remove(),F=null),((Ws=t.launcher)==null?void 0:Ws.enabled)!==!1&&!y&&!F){let L=r.find(we=>we.renderLauncher);if(L!=null&&L.renderLauncher){let we=L.renderLauncher({config:t,defaultRenderer:()=>fn(t,M).element,onToggle:M});we&&(F=we,n.appendChild(F))}F||(y=fn(t,M),n.appendChild(y.element))}y&&y.update(t),mt&&((ks=t.launcher)==null?void 0:ks.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((Ls=t.launcher)==null?void 0:Ls.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),g!==h?g?Ke(U,"auto"):(b=!0,qt()):U!==I&&Ke(U,"auto"),I=U,h=g,be(),Ze(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&R&&_t(Q,R.getMessages(),W);let N=(Bs=t.launcher)!=null?Bs:{},T=(Hs=N.headerIconHidden)!=null?Hs:!1,G=N.headerIconName,z=($s=N.headerIconSize)!=null?$s:"48px";if(fe){let L=_.querySelector(".tvw-border-b-cw-divider"),we=L==null?void 0:L.querySelector(".tvw-flex-col");if(T)fe.style.display="none",L&&we&&!L.contains(we)&&L.insertBefore(we,L.firstChild);else{if(fe.style.display="",fe.style.height=z,fe.style.width=z,L&&we&&(L.contains(fe)?fe.nextSibling!==we&&(fe.remove(),L.insertBefore(fe,we)):L.insertBefore(fe,we)),G){let We=parseFloat(z)||24,xe=ce(G,We*.6,"#ffffff",2);xe?fe.replaceChildren(xe):fe.textContent=(Ps=N.agentIconText)!=null?Ps:"\u{1F4AC}"}else if(N.iconUrl){let We=fe.querySelector("img");if(We)We.src=N.iconUrl,We.style.height=z,We.style.width=z;else{let xe=document.createElement("img");xe.src=N.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=z,xe.style.width=z,fe.replaceChildren(xe)}}else{let We=fe.querySelector("svg"),xe=fe.querySelector("img");(We||xe)&&fe.replaceChildren(),fe.textContent=(Rs=N.agentIconText)!=null?Rs:"\u{1F4AC}"}let oe=fe.querySelector("img");oe&&(oe.style.height=z,oe.style.width=z)}}if(Y){let L=(Is=N.closeButtonSize)!=null?Is:"32px",we=(Fs=N.closeButtonPlacement)!=null?Fs:"inline";Y.style.height=L,Y.style.width=L;let{closeButtonWrapper:oe}=Z,We=we==="top-right",xe=oe==null?void 0:oe.classList.contains("tvw-absolute");if(oe&&We!==xe)if(oe.remove(),We)oe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",_.style.position="relative",_.appendChild(oe);else{let me=(Os=(Ns=N.clearChat)==null?void 0:Ns.placement)!=null?Os:"inline",et=(js=(Ds=N.clearChat)==null?void 0:Ds.enabled)!=null?js:!0;oe.className=et&&me==="inline"?"":"tvw-ml-auto";let tt=_.querySelector(".tvw-border-b-cw-divider");tt&&tt.appendChild(oe)}if(N.closeButtonColor?(Y.style.color=N.closeButtonColor,Y.classList.remove("tvw-text-cw-muted")):(Y.style.color="",Y.classList.add("tvw-text-cw-muted")),N.closeButtonBackgroundColor?(Y.style.backgroundColor=N.closeButtonBackgroundColor,Y.classList.remove("hover:tvw-bg-gray-100")):(Y.style.backgroundColor="",Y.classList.add("hover:tvw-bg-gray-100")),N.closeButtonBorderWidth||N.closeButtonBorderColor){let me=N.closeButtonBorderWidth||"0px",et=N.closeButtonBorderColor||"transparent";Y.style.border=`${me} solid ${et}`,Y.classList.remove("tvw-border-none")}else Y.style.border="",Y.classList.add("tvw-border-none");N.closeButtonBorderRadius?(Y.style.borderRadius=N.closeButtonBorderRadius,Y.classList.remove("tvw-rounded-full")):(Y.style.borderRadius="",Y.classList.add("tvw-rounded-full")),N.closeButtonPaddingX?(Y.style.paddingLeft=N.closeButtonPaddingX,Y.style.paddingRight=N.closeButtonPaddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),N.closeButtonPaddingY?(Y.style.paddingTop=N.closeButtonPaddingY,Y.style.paddingBottom=N.closeButtonPaddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let Qe=(_s=N.closeButtonIconName)!=null?_s:"x",_e=(qs=N.closeButtonIconText)!=null?qs:"\xD7";Y.innerHTML="";let gt=ce(Qe,"20px",N.closeButtonColor||"",2);gt?Y.appendChild(gt):Y.textContent=_e;let Nt=(Us=N.closeButtonTooltipText)!=null?Us:"Close chat",Me=(zs=N.closeButtonShowTooltip)!=null?zs:!0;if(Y.setAttribute("aria-label",Nt),oe&&(oe._cleanupTooltip&&(oe._cleanupTooltip(),delete oe._cleanupTooltip),Me&&Nt)){let me=null,et=()=>{if(me||!Y)return;me=m("div","tvw-clear-chat-tooltip"),me.textContent=Nt;let Gt=m("div");Gt.className="tvw-clear-chat-tooltip-arrow",me.appendChild(Gt);let Kn=Y.getBoundingClientRect();me.style.position="fixed",me.style.left=`${Kn.left+Kn.width/2}px`,me.style.top=`${Kn.top-8}px`,me.style.transform="translate(-50%, -100%)",document.body.appendChild(me)},tt=()=>{me&&me.parentNode&&(me.parentNode.removeChild(me),me=null)};oe.addEventListener("mouseenter",et),oe.addEventListener("mouseleave",tt),Y.addEventListener("focus",et),Y.addEventListener("blur",tt),oe._cleanupTooltip=()=>{tt(),oe&&(oe.removeEventListener("mouseenter",et),oe.removeEventListener("mouseleave",tt)),Y&&(Y.removeEventListener("focus",et),Y.removeEventListener("blur",tt))}}}let{clearChatButton:P,clearChatButtonWrapper:J}=Z;if(P){let L=(Ys=N.clearChat)!=null?Ys:{},we=(Js=L.enabled)!=null?Js:!0,oe=(Ks=L.placement)!=null?Ks:"inline";if(J){J.style.display=we?"":"none";let We=oe==="top-right",xe=J.classList.contains("tvw-absolute");if(We!==xe&&we){if(J.remove(),We)J.className="tvw-absolute tvw-top-4 tvw-z-50",J.style.right="48px",_.style.position="relative",_.appendChild(J);else{J.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",J.style.right="";let _e=_.querySelector(".tvw-border-b-cw-divider"),gt=Z.closeButtonWrapper;_e&&gt&&gt.parentElement===_e?_e.insertBefore(J,gt):_e&&_e.appendChild(J)}let Qe=Z.closeButtonWrapper;Qe&&!Qe.classList.contains("tvw-absolute")&&(We?Qe.classList.add("tvw-ml-auto"):Qe.classList.remove("tvw-ml-auto"))}}if(we){let We=(Xs=L.size)!=null?Xs:"32px";P.style.height=We,P.style.width=We;let xe=(Vs=L.iconName)!=null?Vs:"refresh-cw",Qe=(Gs=L.iconColor)!=null?Gs:"";P.innerHTML="";let _e=ce(xe,"20px",Qe||"",2);if(_e&&P.appendChild(_e),Qe?(P.style.color=Qe,P.classList.remove("tvw-text-cw-muted")):(P.style.color="",P.classList.add("tvw-text-cw-muted")),L.backgroundColor?(P.style.backgroundColor=L.backgroundColor,P.classList.remove("hover:tvw-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let Me=L.borderWidth||"0px",me=L.borderColor||"transparent";P.style.border=`${Me} solid ${me}`,P.classList.remove("tvw-border-none")}else P.style.border="",P.classList.add("tvw-border-none");L.borderRadius?(P.style.borderRadius=L.borderRadius,P.classList.remove("tvw-rounded-full")):(P.style.borderRadius="",P.classList.add("tvw-rounded-full")),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 gt=(Zs=L.tooltipText)!=null?Zs:"Clear chat",Nt=(Qs=L.showTooltip)!=null?Qs:!0;if(P.setAttribute("aria-label",gt),J&&(J._cleanupTooltip&&(J._cleanupTooltip(),delete J._cleanupTooltip),Nt&&gt)){let Me=null,me=()=>{if(Me||!P)return;Me=m("div","tvw-clear-chat-tooltip"),Me.textContent=gt;let tt=m("div");tt.className="tvw-clear-chat-tooltip-arrow",Me.appendChild(tt);let Gt=P.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${Gt.left+Gt.width/2}px`,Me.style.top=`${Gt.top-8}px`,Me.style.transform="translate(-50%, -100%)",document.body.appendChild(Me)},et=()=>{Me&&Me.parentNode&&(Me.parentNode.removeChild(Me),Me=null)};J.addEventListener("mouseenter",me),J.addEventListener("mouseleave",et),P.addEventListener("focus",me),P.addEventListener("blur",et),J._cleanupTooltip=()=>{et(),J&&(J.removeEventListener("mouseenter",me),J.removeEventListener("mouseleave",et)),P&&(P.removeEventListener("focus",me),P.removeEventListener("blur",et))}}}}let Be=t.actionParsers&&t.actionParsers.length?t.actionParsers:[vn],he=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick];C=bn({parsers:Be,handlers:he,getMetadata:d,updateMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),W=zo(t,C),R.updateConfig(t),_t(Q,R.getMessages(),W),ot.render(t.suggestionChips,R,re,void 0,t.suggestionChipsConfig),cn(),Xt(R.isStreaming());let ae=((eo=t.voiceRecognition)==null?void 0:eo.enabled)===!0,Re=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ct=ae&&Re;if(Ve.classList.remove("tvw-gap-1","tvw-gap-3"),Ve.classList.add(ct?"tvw-gap-1":"tvw-gap-3"),ae&&Re)if(!H||!He){let L=$(t.voiceRecognition,t.sendButton);L&&(H=L.micButton,He=L.micButtonWrapper,Ve.insertBefore(He,qe),H.addEventListener("click",rt),H.disabled=R.isStreaming())}else{let L=(to=t.voiceRecognition)!=null?to:{},we=(no=t.sendButton)!=null?no:{},oe=(so=L.iconName)!=null?so:"mic",We=(oo=we.size)!=null?oo:"40px",xe=(ro=L.iconSize)!=null?ro:We,Qe=parseFloat(xe)||24;H.style.width=xe,H.style.height=xe,H.style.minWidth=xe,H.style.minHeight=xe;let _e=(ao=(io=L.iconColor)!=null?io:we.textColor)!=null?ao:"currentColor";H.innerHTML="";let gt=ce(oe,Qe,_e,2);gt?H.appendChild(gt):H.textContent="\u{1F3A4}";let Nt=(lo=L.backgroundColor)!=null?lo:we.backgroundColor;Nt?(H.style.backgroundColor=Nt,H.classList.remove("tvw-bg-cw-primary")):(H.style.backgroundColor="",H.classList.add("tvw-bg-cw-primary")),_e?(H.style.color=_e,H.classList.remove("tvw-text-white")):!_e&&!we.textColor&&(H.style.color="",H.classList.add("tvw-text-white")),L.borderWidth?(H.style.borderWidth=L.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),L.borderColor?H.style.borderColor=L.borderColor:H.style.borderColor="",L.paddingX?(H.style.paddingLeft=L.paddingX,H.style.paddingRight=L.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),L.paddingY?(H.style.paddingTop=L.paddingY,H.style.paddingBottom=L.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Me=He==null?void 0:He.querySelector(".tvw-send-button-tooltip"),me=(co=L.tooltipText)!=null?co:"Start voice recognition";if(((uo=L.showTooltip)!=null?uo:!1)&&me)if(Me)Me.textContent=me,Me.style.display="";else{let tt=document.createElement("div");tt.className="tvw-send-button-tooltip",tt.textContent=me,He==null||He.insertBefore(tt,H)}else Me&&(Me.style.display="none");He.style.display="",H.disabled=R.isStreaming()}else H&&He&&(He.style.display="none",V&&ue());let le=(po=t.sendButton)!=null?po:{},ut=(go=le.useIcon)!=null?go:!1,$t=(ho=le.iconText)!=null?ho:"\u2191",Pt=le.iconName,kt=(mo=le.tooltipText)!=null?mo:"Send message",Ut=(fo=le.showTooltip)!=null?fo:!1,Rt=(wo=le.size)!=null?wo:"40px",zt=le.backgroundColor,pt=le.textColor;if(ut){if(q.style.width=Rt,q.style.height=Rt,q.style.minWidth=Rt,q.style.minHeight=Rt,q.style.fontSize="18px",q.style.lineHeight="1",q.innerHTML="",Pt){let L=parseFloat(Rt)||24,we=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",oe=ce(Pt,L,we,2);oe?(q.appendChild(oe),q.style.color=we):(q.textContent=$t,pt?q.style.color=pt:q.classList.add("tvw-text-white"))}else q.textContent=$t,pt?q.style.color=pt:q.classList.add("tvw-text-white");q.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",zt?(q.style.backgroundColor=zt,q.classList.remove("tvw-bg-cw-primary")):q.classList.add("tvw-bg-cw-primary")}else q.textContent=(vo=(yo=t.copy)==null?void 0:yo.sendButtonLabel)!=null?vo:"Send",q.style.width="",q.style.height="",q.style.minWidth="",q.style.minHeight="",q.style.fontSize="",q.style.lineHeight="",q.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",zt?(q.style.backgroundColor=zt,q.classList.remove("tvw-bg-cw-accent")):q.classList.add("tvw-bg-cw-accent"),pt?q.style.color=pt:q.classList.add("tvw-text-white");le.borderWidth?(q.style.borderWidth=le.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),le.borderColor?q.style.borderColor=le.borderColor:q.style.borderColor="",le.paddingX?(q.style.paddingLeft=le.paddingX,q.style.paddingRight=le.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),le.paddingY?(q.style.paddingTop=le.paddingY,q.style.paddingBottom=le.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let It=qe==null?void 0:qe.querySelector(".tvw-send-button-tooltip");if(Ut&&kt)if(It)It.textContent=kt,It.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=kt,qe==null||qe.insertBefore(L,q)}else It&&(It.style.display="none");let Ft=(bo=t.statusIndicator)!=null?bo:{},An=(Co=Ft.visible)!=null?Co:!0;if(nt.style.display=An?"":"none",R){let L=R.getStatus(),we=oe=>{var We,xe,Qe,_e;return oe==="idle"?(We=Ft.idleText)!=null?We:Xe.idle:oe==="connecting"?(xe=Ft.connectingText)!=null?xe:Xe.connecting:oe==="connected"?(Qe=Ft.connectedText)!=null?Qe:Xe.connected:oe==="error"?(_e=Ft.errorText)!=null?_e:Xe.error:Xe[oe]};nt.textContent=we(L)}},open(){g&&Ke(!0,"api")},close(){g&&Ke(!1,"api")},toggle(){g&&Ke(!b,"api")},clearChat(){R.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},C.syncFromMetadata()},setMessage(a){return!re||R.isStreaming()?!1:(!b&&g&&Ke(!0,"system"),re.value=a,re.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(R.isStreaming())return!1;let p=(a==null?void 0:a.trim())||re.value.trim();return p?(!b&&g&&Ke(!0,"system"),re.value="",R.sendMessage(p),!0):!1},startVoiceRecognition(){return V||R.isStreaming()||!Fe()?!1:(!b&&g&&Ke(!0,"system"),ye.manuallyDeactivated=!1,Je(),Ne("user"),!0)},stopVoiceRecognition(){return V?(ye.manuallyDeactivated=!0,Je(),ue("user"),!0):!1},injectTestMessage(a){!b&&g&&Ke(!0,"system"),R.injectTestEvent(a)},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){f(a)},on(a,p){return o.on(a,p)},off(a,p){o.off(a,p)},isOpen(){return g&&b},isVoiceActive(){return ye.active},getState(){return{open:g&&b,launcherEnabled:g,voiceActive:ye.active,streaming:R.isStreaming()}},showCSATFeedback(a){!b&&g&&Ke(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let E=qn({onSubmit:async(O,k)=>{var ee;R.isClientTokenMode()&&await R.submitCSATFeedback(O,k),(ee=a==null?void 0:a.onSubmit)==null||ee.call(a,O,k)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!b&&g&&Ke(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let E=Un({onSubmit:async(O,k)=>{var ee;R.isClientTokenMode()&&await R.submitNPSFeedback(O,k),(ee=a==null?void 0:a.onSubmit)==null||ee.call(a,O,k)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,p){return R.submitCSATFeedback(a,p)},async submitNPSFeedback(a,p){return R.submitNPSFeedback(a,p)},destroy(){Ie.forEach(a=>a()),B.remove(),y==null||y.destroy(),F==null||F.remove(),Ue&&Y.removeEventListener("click",Ue)}};if((((bs=s==null?void 0:s.debugTools)!=null?bs:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:Ce,getMessages:Ce.getMessages,getStatus:Ce.getStatus,getMetadata:Ce.getPersistentMetadata,updateMetadata:Ce.updatePersistentMetadata,clearHistory:()=>Ce.clearChat(),setVoiceActive:E=>E?Ce.startVoiceRecognition():Ce.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Ie.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return Ce};var ps={},xr=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},Sr=()=>{try{if(typeof ps!="undefined"&&ps.url)return new URL("../widget.css",ps.url).href}catch{}return null},Yo=n=>{let e=Sr(),s=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let r=t.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else s();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},gs=n=>{var d,f,w,u;let e=xr(n.target),s=document.createElement("div");s.className="vanilla-agent-host";let t=(w=(f=(d=n.config)==null?void 0:d.launcher)==null?void 0:f.enabled)!=null?w:!0;t||(s.style.height="100%"),e.appendChild(s);let r=n.useShadowDom===!0,o,i;if(r){let C=s.attachShadow({mode:"open"});i=C,o=document.createElement("div"),o.id="vanilla-agent-root",t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),C.appendChild(o),Yo(C)}else i=s,o=document.createElement("div"),o.id="vanilla-agent-root",t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),s.appendChild(o),Yo(s);let l=zn(o,n.config,{debugTools:n.debugTools});(u=n.onReady)==null||u.call(n);let c={...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]=c),c};function Ar(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function Yn(n){var e,s;return(s=(e=n.parserType)!=null?e:Ar(n.streamParser))!=null?s:"plain"}function rn(n,e){let s=[];return n.toolCall&&(s.push(`${e}toolCall: {`),Object.entries(n.toolCall).forEach(([t,r])=>{typeof r=="string"&&s.push(`${e} ${t}: "${r}",`)}),s.push(`${e}},`)),s}function an(n,e){let s=[];return n.messageActions&&Object.entries(n.messageActions).some(([r,o])=>r!=="onFeedback"&&r!=="onCopy"&&o!==void 0)&&(s.push(`${e}messageActions: {`),Object.entries(n.messageActions).forEach(([r,o])=>{r==="onFeedback"||r==="onCopy"||(typeof o=="string"?s.push(`${e} ${r}: "${o}",`):typeof o=="boolean"&&s.push(`${e} ${r}: ${o},`))}),s.push(`${e}},`)),s}function ln(n,e){let s=[];if(n.markdown){let t=n.markdown.options&&Object.keys(n.markdown.options).length>0,r=n.markdown.disableDefaultStyles!==void 0;(t||r)&&(s.push(`${e}markdown: {`),t&&(s.push(`${e} options: {`),Object.entries(n.markdown.options).forEach(([o,i])=>{typeof i=="string"?s.push(`${e} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${e} ${o}: ${i},`)}),s.push(`${e} },`)),r&&s.push(`${e} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),s.push(`${e}},`))}return s}function dn(n,e){let s=[];if(n.layout){let t=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");(t||r)&&(s.push(`${e}layout: {`),t&&(s.push(`${e} header: {`),Object.entries(n.layout.header).forEach(([o,i])=>{o!=="render"&&(typeof i=="string"?s.push(`${e} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${e} ${o}: ${i},`))}),s.push(`${e} },`)),r&&(s.push(`${e} messages: {`),Object.entries(n.layout.messages).forEach(([o,i])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof i=="object"&&i!==null?(s.push(`${e} avatar: {`),Object.entries(i).forEach(([l,c])=>{typeof c=="string"?s.push(`${e} ${l}: "${c}",`):typeof c=="boolean"&&s.push(`${e} ${l}: ${c},`)}),s.push(`${e} },`)):o==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([c])=>c!=="format")&&(s.push(`${e} timestamp: {`),Object.entries(i).forEach(([c,d])=>{c!=="format"&&(typeof d=="string"?s.push(`${e} ${c}: "${d}",`):typeof d=="boolean"&&s.push(`${e} ${c}: ${d},`))}),s.push(`${e} },`)):typeof i=="string"?s.push(`${e} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${e} ${o}: ${i},`))}),s.push(`${e} },`)),s.push(`${e}},`))}return s}function Jo(n,e="esm"){let s={...n};return delete s.postprocessMessage,delete s.initialMessages,e==="esm"?Tr(s):e==="script-installer"?Wr(s):e==="script-advanced"?Lr(s):e==="react-component"?Er(s):e==="react-advanced"?Mr(s):kr(s)}function Tr(n){let e=Yn(n),s=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...rn(n," ")),t.push(...an(n," ")),t.push(...ln(n," ")),t.push(...dn(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
61
- `)}function Er(n){let e=Yn(n),s=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...rn(n," ")),t.push(...an(n," ")),t.push(...ln(n," ")),t.push(...dn(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
62
- `)}function Mr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...rn(n," ")),e.push(...an(n," ")),e.push(...ln(n," ")),e.push(...dn(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
63
- `)}function Wr(n){let e=Yn(n),s=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...rn(n," ")),t.push(...an(n," ")),t.push(...ln(n," ")),t.push(...dn(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
64
- `)}function kr(n){let e=Yn(n),s=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...rn(n," ")),t.push(...an(n," ")),t.push(...ln(n," ")),t.push(...dn(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
65
- `)}function Lr(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),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(...rn(n," ")),e.push(...an(n," ")),e.push(...ln(n," ")),e.push(...dn(n," ")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" }),"),e.push(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
66
- `)}var Br=gs;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_WIDGET_CONFIG,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getHeaderLayout,hasComponentDirective,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,pluginRegistry,renderComponentDirective});
60
+ `}if(!we){let Jt="max-height: -moz-available !important; max-height: stretch !important;",Vt=a?"":"padding-top: 1.25em !important;";R.style.cssText+=Jt+Vt}};wt(),Bn(n,t);let He=[],Je=null,yt=()=>{Je&&(Je(),Je=null),t.colorScheme==="auto"&&(Je=Do(()=>{Bn(n,t)}))};yt(),He.push(()=>{Je&&(Je(),Je=null)});let ot=zo(ie),Ye=null,E,$e=!1,V=!0,Le=0,Ie=0,Fe=null,Ne=!1,ut=0,At=!1,vt=125,Lt=2e3,Bt=5,Dt=50,Et=new Map,Z={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},pt=(As=(Ss=t.voiceRecognition)==null?void 0:Ss.autoResume)!=null?As:!1,bt=a=>{o.emit("voice:state",{active:Z.active,source:a,timestamp:Date.now()})},gt=()=>{w(a=>({...a,voiceState:{active:Z.active,timestamp:Date.now(),manuallyDeactivated:Z.manuallyDeactivated}}))},Ht=()=>{var F,B;if(((F=t.voiceRecognition)==null?void 0:F.enabled)===!1)return;let a=ms(l.voiceState),p=!!a.active,T=Number((B=a.timestamp)!=null?B:0);Z.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-T<Lr&&setTimeout(()=>{Z.active||(Z.manuallyDeactivated=!1,L("restore"))},1e3)},hn=()=>E?Go(E.getMessages()).filter(a=>!a.__skipPersist):[];function rn(a){if(!(i!=null&&i.save))return;let T={messages:a?Go(a):E?hn():[],metadata:l};try{let F=i.save(T);F instanceof Promise&&F.catch(B=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",B)})}catch(F){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",F)}}let _t=(a=!1)=>{if(!V)return;let p=Date.now();Ne&&p<ut&&!a||(Ne&&p>=ut&&(Ne=!1),!(!a&&!$e)&&(p-Ie<vt||(Ie=p,Fe&&cancelAnimationFrame(Fe),Fe=requestAnimationFrame(()=>{Ne||!V||(At=!0,U.scrollTop=U.scrollHeight,Le=U.scrollTop,requestAnimationFrame(()=>{At=!1}),Fe=null)}))))},Mt=null,fn=()=>R.querySelector("#vanilla-agent-scroll-container")||U,wn=(a,p=500)=>{let T=a.scrollTop,F=a.clientHeight,B=a.scrollHeight,ne=B-T;if(T+F>=B-2||Math.abs(ne)<5)return;Mt!==null&&(cancelAnimationFrame(Mt),Mt=null);let h=performance.now(),ee=oe=>1-Math.pow(1-oe,3),J=oe=>{let P=a.scrollHeight;P!==B&&(B=P,ne=B-T);let te=oe-h,we=Math.min(te/p,1),ue=ee(we),Pe=T+ne*ue;a.scrollTop=Pe,we<1?Mt=requestAnimationFrame(J):(a.scrollTop=a.scrollHeight,Mt=null)};Mt=requestAnimationFrame(J)},yn=a=>{let p=new Map;a.forEach(T=>{let F=Et.get(T.id);p.set(T.id,{streaming:T.streaming,role:T.role}),!F&&T.role==="assistant"&&o.emit("assistant:message",T),T.role==="assistant"&&(F!=null&&F.streaming)&&T.streaming===!1&&o.emit("assistant:complete",T)}),Et.clear(),p.forEach((T,F)=>{Et.set(F,T)})},jt=(a,p,T)=>{a.innerHTML="";let F=document.createDocumentFragment();p.forEach(h=>{var te,we;let ee=null,J=r.find(ue=>!!(h.variant==="reasoning"&&ue.renderReasoning||h.variant==="tool"&&ue.renderToolCall||!h.variant&&ue.renderMessage)),oe=(te=t.layout)==null?void 0:te.messages;if(J)if(h.variant==="reasoning"&&h.reasoning&&J.renderReasoning){if(!v)return;ee=J.renderReasoning({message:h,defaultRenderer:()=>rs(h),config:t})}else if(h.variant==="tool"&&h.toolCall&&J.renderToolCall){if(!N)return;ee=J.renderToolCall({message:h,defaultRenderer:()=>as(h,t),config:t})}else J.renderMessage&&(ee=J.renderMessage({message:h,defaultRenderer:()=>{let ue=tn(h,T,oe,t.messageActions,x);return h.role!=="user"&&ls(ue,h,t,E),ue},config:t}));if(!ee&&h.role==="assistant"&&!h.variant&&t.enableComponentStreaming!==!1&&Nn(h)){let Pe=On(h);if(Pe){let it=Fn(Pe,{config:t,message:h,transform:T});if(it){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.setAttribute("data-message-id",h.id),h.content&&h.content.trim()){let he=document.createElement("div");he.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",he.innerHTML=T({text:h.content,message:h,streaming:!!h.streaming,raw:h.rawContent}),Xe.appendChild(he)}Xe.appendChild(it),ee=Xe}}}if(!ee)if(h.variant==="reasoning"&&h.reasoning){if(!v)return;ee=rs(h)}else if(h.variant==="tool"&&h.toolCall){if(!N)return;ee=as(h,t)}else{let ue=(we=t.layout)==null?void 0:we.messages;ue!=null&&ue.renderUserMessage&&h.role==="user"?ee=ue.renderUserMessage({message:h,config:t,streaming:!!h.streaming}):ue!=null&&ue.renderAssistantMessage&&h.role==="assistant"?ee=ue.renderAssistantMessage({message:h,config:t,streaming:!!h.streaming}):ee=tn(h,T,ue,t.messageActions,x),h.role!=="user"&&ee&&ls(ee,h,t,E)}let P=document.createElement("div");P.className="tvw-flex",h.role==="user"&&P.classList.add("tvw-justify-end"),P.appendChild(ee),F.appendChild(P)});let B=p.some(h=>h.role==="assistant"&&h.streaming),ne=p[p.length-1],pe=(ne==null?void 0:ne.role)==="assistant"&&!ne.streaming;if($e&&p.some(h=>h.role==="user")&&!B&&!pe){let h=un(),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.appendChild(h);let J=document.createElement("div");J.className="tvw-flex",J.appendChild(ee),F.appendChild(J)}a.appendChild(F),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let h=fn();wn(h)})})},qt=()=>{g&&(b?(R.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"),K?K.element.style.display="none":X&&(X.style.display="none")):(R.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"),K?K.element.style.display="":X&&(X.style.display="")))},Ke=(a,p="user")=>{if(!g||b===a)return;let T=b;b=a,qt(),b&&(je(),_t(!0));let F={open:b,source:p,timestamp:Date.now()};b&&!T?o.emit("widget:opened",F):!b&&T&&o.emit("widget:closed",F),o.emit("widget:state",{open:b,launcherEnabled:g,voiceActive:Z.active,streaming:E.isStreaming()})},Xt=a=>{_.disabled=a,I&&(I.disabled=a),ot.buttons.forEach(p=>{p.disabled=a})},an=()=>{var B,ne,pe,h,ee,J,oe,P,te,we,ue,Pe,it,Xe;xt.textContent=(ne=(B=t.copy)==null?void 0:B.welcomeTitle)!=null?ne:"Hello \u{1F44B}",St.textContent=(h=(pe=t.copy)==null?void 0:pe.welcomeSubtitle)!=null?h:"Ask anything about your account or products.",de.placeholder=(J=(ee=t.copy)==null?void 0:ee.inputPlaceholder)!=null?J:"How can I help...",((P=(oe=t.sendButton)==null?void 0:oe.useIcon)!=null?P:!1)||(_.textContent=(we=(te=t.copy)==null?void 0:te.sendButtonLabel)!=null?we:"Send");let p=(Pe=(ue=t.theme)==null?void 0:ue.inputFontFamily)!=null?Pe:"sans-serif",T=(Xe=(it=t.theme)==null?void 0:it.inputFontWeight)!=null?Xe:"400",F=he=>{switch(he){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'}};de.style.fontFamily=F(p),de.style.fontWeight=T};E=new Qt(t,{onMessagesChanged(a){jt(Q,a,W),E&&(a.some(F=>F.role==="user")?ot.render([],E,de,a):ot.render(t.suggestionChips,E,de,a,t.suggestionChipsConfig)),_t(!$e),yn(a);let p=[...a].reverse().find(T=>T.role==="user");Z.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),rn(a)},onStatusChanged(a){var F;let p=(F=t.statusIndicator)!=null?F:{},T=B=>{var ne,pe,h,ee;return B==="idle"?(ne=p.idleText)!=null?ne:Ve.idle:B==="connecting"?(pe=p.connectingText)!=null?pe:Ve.connecting:B==="connected"?(h=p.connectedText)!=null?h:Ve.connected:B==="error"?(ee=p.errorText)!=null?ee:Ve.error:Ve[B]};nt.textContent=T(a)},onStreamingChanged(a){$e=a,Xt(a),E&&jt(Q,E.getMessages(),W),a||_t(!0)}}),d&&d.then(a=>{var p;a&&(a.metadata&&(l=ms(a.metadata),C.syncFromMetadata()),(p=a.messages)!=null&&p.length&&E.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let M=a=>{a.preventDefault();let p=de.value.trim();p&&(de.value="",E.sendMessage(p))},ce=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),_.click())},se=null,me=!1,Se=null,Ee=null,Me=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,L=(a="user")=>{var ne,pe,h,ee;if(me||E.isStreaming())return;let p=Me();if(!p)return;se=new p;let F=(pe=((ne=t.voiceRecognition)!=null?ne:{}).pauseDuration)!=null?pe:2e3;se.continuous=!0,se.interimResults=!0,se.lang="en-US";let B=de.value;se.onresult=J=>{let oe="",P="";for(let we=0;we<J.results.length;we++){let ue=J.results[we],Pe=ue[0].transcript;ue.isFinal?oe+=Pe+" ":P=Pe}let te=B+oe+P;de.value=te,Se&&clearTimeout(Se),(oe||P)&&(Se=window.setTimeout(()=>{let we=de.value.trim();we&&se&&me&&(Oe(),de.value="",E.sendMessage(we,{viaVoice:!0}))},F))},se.onerror=J=>{J.error!=="no-speech"&&Oe()},se.onend=()=>{if(me){let J=de.value.trim();J&&J!==B.trim()&&(de.value="",E.sendMessage(J,{viaVoice:!0})),Oe()}};try{if(se.start(),me=!0,Z.active=!0,a!=="system"&&(Z.manuallyDeactivated=!1),bt(a),gt(),I){Ee={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor};let J=(h=t.voiceRecognition)!=null?h:{},oe=(ee=J.recordingBackgroundColor)!=null?ee:"#ef4444",P=J.recordingIconColor,te=J.recordingBorderColor;if(I.classList.add("tvw-voice-recording"),I.style.backgroundColor=oe,P){I.style.color=P;let we=I.querySelector("svg");we&&we.setAttribute("stroke",P)}te&&(I.style.borderColor=te),I.setAttribute("aria-label","Stop voice recognition")}}catch{Oe("system")}},Oe=(a="user")=>{if(me){if(me=!1,Se&&(clearTimeout(Se),Se=null),se){try{se.stop()}catch{}se=null}if(Z.active=!1,bt(a),gt(),I){if(I.classList.remove("tvw-voice-recording"),Ee){I.style.backgroundColor=Ee.backgroundColor,I.style.color=Ee.color,I.style.borderColor=Ee.borderColor;let p=I.querySelector("svg");p&&p.setAttribute("stroke",Ee.color||"currentColor"),Ee=null}I.setAttribute("aria-label","Start voice recognition")}}},ae=(a,p)=>{var Pe,it,Xe,he,Ut,Rt,Pt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let F=f("div","tvw-send-button-wrapper"),B=f("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 ne=(Pe=a==null?void 0:a.iconName)!=null?Pe:"mic",pe=(it=p==null?void 0:p.size)!=null?it:"40px",h=(Xe=a==null?void 0:a.iconSize)!=null?Xe:pe,ee=parseFloat(h)||24,J=(he=a==null?void 0:a.backgroundColor)!=null?he:p==null?void 0:p.backgroundColor,oe=(Ut=a==null?void 0:a.iconColor)!=null?Ut:p==null?void 0:p.textColor;B.style.width=h,B.style.height=h,B.style.minWidth=h,B.style.minHeight=h,B.style.fontSize="18px",B.style.lineHeight="1";let P=oe||"currentColor",te=ge(ne,ee,P,1.5);te?(B.appendChild(te),B.style.color=P):(B.textContent="\u{1F3A4}",B.style.color=P),J?B.style.backgroundColor=J:B.classList.add("tvw-bg-cw-primary"),oe?B.style.color=oe:!oe&&!(p!=null&&p.textColor)&&B.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(B.style.borderWidth=a.borderWidth,B.style.borderStyle="solid"),a!=null&&a.borderColor&&(B.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(B.style.paddingLeft=a.paddingX,B.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(B.style.paddingTop=a.paddingY,B.style.paddingBottom=a.paddingY),F.appendChild(B);let we=(Rt=a==null?void 0:a.tooltipText)!=null?Rt:"Start voice recognition";if(((Pt=a==null?void 0:a.showTooltip)!=null?Pt:!1)&&we){let kt=f("div","tvw-send-button-tooltip");kt.textContent=we,F.appendChild(kt)}return{micButton:B,micButtonWrapper:F}},k=()=>{if(me){let a=de.value.trim();Z.manuallyDeactivated=!0,gt(),Oe("user"),a&&(de.value="",E.sendMessage(a))}else Z.manuallyDeactivated=!1,gt(),L("user")};I&&(I.addEventListener("click",k),He.push(()=>{Oe("system"),I&&I.removeEventListener("click",k)}));let A=o.on("assistant:complete",()=>{pt&&(Z.active||Z.manuallyDeactivated||pt==="assistant"&&!Z.lastUserMessageWasVoice||setTimeout(()=>{!Z.active&&!Z.manuallyDeactivated&&L("auto")},600))});He.push(A);let z=()=>{Ke(!b,"user")},K=null,X=null;if(g){let a=r.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:t,defaultRenderer:()=>cn(t,z).element,onToggle:z});p&&(X=p)}X||(K=cn(t,z))}K?n.appendChild(K.element):X&&n.appendChild(X),qt(),ot.render(t.suggestionChips,E,de,void 0,t.suggestionChipsConfig),an(),Xt(E.isStreaming()),_t(!0),Ht();let je=()=>{var T,F,B,ne,pe,h,ee,J;let a=(F=(T=t.launcher)==null?void 0:T.sidebarMode)!=null?F:!1,p=a||((ne=(B=t.launcher)==null?void 0:B.fullHeight)!=null?ne:!1);if(!g){O.style.height="",O.style.width="";return}if(!a){let oe=(h=(pe=t==null?void 0:t.launcher)==null?void 0:pe.width)!=null?h:t==null?void 0:t.launcherWidth,P=oe!=null?oe:"min(400px, calc(100vw - 24px))";O.style.width=P,O.style.maxWidth=P}if(!p){let oe=window.innerHeight,P=64,te=(J=(ee=t.launcher)==null?void 0:ee.heightOffset)!=null?J:0,we=Math.max(200,oe-P),ue=Math.min(640,we),Pe=Math.max(200,ue-te);O.style.height=`${Pe}px`}};je(),window.addEventListener("resize",je),He.push(()=>window.removeEventListener("resize",je)),Le=U.scrollTop;let ke=()=>{let a=U.scrollTop,p=U.scrollHeight,T=U.clientHeight,F=p-a-T,B=Math.abs(a-Le);if(Le=a,!At&&!(B<=Bt)){if(!V&&F<Dt){Ne=!1,V=!0;return}V&&F>Dt&&(Ne=!0,ut=Date.now()+Lt,V=!1)}};U.addEventListener("scroll",ke,{passive:!0}),He.push(()=>U.removeEventListener("scroll",ke)),He.push(()=>{Fe&&cancelAnimationFrame(Fe)});let De=()=>{q&&(Ye&&(q.removeEventListener("click",Ye),Ye=null),g?(q.style.display="",Ye=()=>{b=!1,qt()},q.addEventListener("click",Ye)):q.style.display="none")};De(),(()=>{let{clearChatButton:a}=G;a&&a.addEventListener("click",()=>{E.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(F=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",F)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}l={},C.syncFromMetadata()})})(),Ge.addEventListener("submit",M),de.addEventListener("keydown",ce),He.push(()=>{Ge.removeEventListener("submit",M),de.removeEventListener("keydown",ce)}),He.push(()=>{E.cancel()}),K?He.push(()=>{K==null||K.destroy()}):X&&He.push(()=>{X==null||X.remove()});let re={update(a){var Jt,Vt,Es,Ms,ks,Ws,Ls,Bs,Hs,Rs,Ps,Is,$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;let p=t.toolCall,T=t.colorScheme;t={...t,...a},wt(),Bn(n,t),t.colorScheme!==T&&yt();let F=pn.getForInstance(t.plugins);if(r.length=0,r.push(...F),g=(Vt=(Jt=t.launcher)==null?void 0:Jt.enabled)!=null?Vt:!0,j=(Ms=(Es=t.launcher)==null?void 0:Es.autoExpand)!=null?Ms:!1,v=(Ws=(ks=t.features)==null?void 0:ks.showReasoning)!=null?Ws:!0,N=(Bs=(Ls=t.features)==null?void 0:Ls.showToolCalls)!=null?Bs:!0,((Hs=t.launcher)==null?void 0:Hs.enabled)===!1&&K&&(K.destroy(),K=null),((Rs=t.launcher)==null?void 0:Rs.enabled)===!1&&X&&(X.remove(),X=null),((Ps=t.launcher)==null?void 0:Ps.enabled)!==!1&&!K&&!X){let H=r.find(be=>be.renderLauncher);if(H!=null&&H.renderLauncher){let be=H.renderLauncher({config:t,defaultRenderer:()=>cn(t,z).element,onToggle:z});be&&(X=be,n.appendChild(X))}X||(K=cn(t,z),n.appendChild(K.element))}K&&K.update(t),ht&&((Is=t.launcher)==null?void 0:Is.title)!==void 0&&(ht.textContent=t.launcher.title),ft&&(($s=t.launcher)==null?void 0:$s.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),g!==m?g?Ke(j,"auto"):(b=!0,qt()):j!==$&&Ke(j,"auto"),$=j,m=g,je(),De(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&E&&jt(Q,E.getMessages(),W);let h=(Fs=t.launcher)!=null?Fs:{},ee=(Ns=h.headerIconHidden)!=null?Ns:!1,J=h.headerIconName,oe=(Os=h.headerIconSize)!=null?Os:"48px";if(ve){let H=D.querySelector(".tvw-border-b-cw-divider"),be=H==null?void 0:H.querySelector(".tvw-flex-col");if(ee)ve.style.display="none",H&&be&&!H.contains(be)&&H.insertBefore(be,H.firstChild);else{if(ve.style.display="",ve.style.height=oe,ve.style.width=oe,H&&be&&(H.contains(ve)?ve.nextSibling!==be&&(ve.remove(),H.insertBefore(ve,be)):H.insertBefore(ve,be)),J){let We=parseFloat(oe)||24,xe=ge(J,We*.6,"#ffffff",2);xe?ve.replaceChildren(xe):ve.textContent=(Ds=h.agentIconText)!=null?Ds:"\u{1F4AC}"}else if(h.iconUrl){let We=ve.querySelector("img");if(We)We.src=h.iconUrl,We.style.height=oe,We.style.width=oe;else{let xe=document.createElement("img");xe.src=h.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=oe,xe.style.width=oe,ve.replaceChildren(xe)}}else{let We=ve.querySelector("svg"),xe=ve.querySelector("img");(We||xe)&&ve.replaceChildren(),ve.textContent=(_s=h.agentIconText)!=null?_s:"\u{1F4AC}"}let le=ve.querySelector("img");le&&(le.style.height=oe,le.style.width=oe)}}if(q){let H=(js=h.closeButtonSize)!=null?js:"32px",be=(qs=h.closeButtonPlacement)!=null?qs:"inline";q.style.height=H,q.style.width=H;let{closeButtonWrapper:le}=G,We=be==="top-right",xe=le==null?void 0:le.classList.contains("tvw-absolute");if(le&&We!==xe)if(le.remove(),We)le.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",D.style.position="relative",D.appendChild(le);else{let ye=(zs=(Us=h.clearChat)==null?void 0:Us.placement)!=null?zs:"inline",et=(Ys=(Js=h.clearChat)==null?void 0:Js.enabled)!=null?Ys:!0;le.className=et&&ye==="inline"?"":"tvw-ml-auto";let tt=D.querySelector(".tvw-border-b-cw-divider");tt&&tt.appendChild(le)}if(h.closeButtonColor?(q.style.color=h.closeButtonColor,q.classList.remove("tvw-text-cw-muted")):(q.style.color="",q.classList.add("tvw-text-cw-muted")),h.closeButtonBackgroundColor?(q.style.backgroundColor=h.closeButtonBackgroundColor,q.classList.remove("hover:tvw-bg-gray-100")):(q.style.backgroundColor="",q.classList.add("hover:tvw-bg-gray-100")),h.closeButtonBorderWidth||h.closeButtonBorderColor){let ye=h.closeButtonBorderWidth||"0px",et=h.closeButtonBorderColor||"transparent";q.style.border=`${ye} solid ${et}`,q.classList.remove("tvw-border-none")}else q.style.border="",q.classList.add("tvw-border-none");h.closeButtonBorderRadius?(q.style.borderRadius=h.closeButtonBorderRadius,q.classList.remove("tvw-rounded-full")):(q.style.borderRadius="",q.classList.add("tvw-rounded-full")),h.closeButtonPaddingX?(q.style.paddingLeft=h.closeButtonPaddingX,q.style.paddingRight=h.closeButtonPaddingX):(q.style.paddingLeft="",q.style.paddingRight=""),h.closeButtonPaddingY?(q.style.paddingTop=h.closeButtonPaddingY,q.style.paddingBottom=h.closeButtonPaddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Ze=(Ks=h.closeButtonIconName)!=null?Ks:"x",Ue=(Xs=h.closeButtonIconText)!=null?Xs:"\xD7";q.innerHTML="";let ct=ge(Ze,"20px",h.closeButtonColor||"",2);ct?q.appendChild(ct):q.textContent=Ue;let Nt=(Vs=h.closeButtonTooltipText)!=null?Vs:"Close chat",Ae=(Gs=h.closeButtonShowTooltip)!=null?Gs:!0;if(q.setAttribute("aria-label",Nt),le&&(le._cleanupTooltip&&(le._cleanupTooltip(),delete le._cleanupTooltip),Ae&&Nt)){let ye=null,et=()=>{if(ye||!q)return;ye=f("div","tvw-clear-chat-tooltip"),ye.textContent=Nt;let Gt=f("div");Gt.className="tvw-clear-chat-tooltip-arrow",ye.appendChild(Gt);let Xn=q.getBoundingClientRect();ye.style.position="fixed",ye.style.left=`${Xn.left+Xn.width/2}px`,ye.style.top=`${Xn.top-8}px`,ye.style.transform="translate(-50%, -100%)",document.body.appendChild(ye)},tt=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};le.addEventListener("mouseenter",et),le.addEventListener("mouseleave",tt),q.addEventListener("focus",et),q.addEventListener("blur",tt),le._cleanupTooltip=()=>{tt(),le&&(le.removeEventListener("mouseenter",et),le.removeEventListener("mouseleave",tt)),q&&(q.removeEventListener("focus",et),q.removeEventListener("blur",tt))}}}let{clearChatButton:P,clearChatButtonWrapper:te}=G;if(P){let H=(Qs=h.clearChat)!=null?Qs:{},be=(Zs=H.enabled)!=null?Zs:!0,le=(eo=H.placement)!=null?eo:"inline";if(te){te.style.display=be?"":"none";let We=le==="top-right",xe=te.classList.contains("tvw-absolute");if(We!==xe&&be){if(te.remove(),We)te.className="tvw-absolute tvw-top-4 tvw-z-50",te.style.right="48px",D.style.position="relative",D.appendChild(te);else{te.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",te.style.right="";let Ue=D.querySelector(".tvw-border-b-cw-divider"),ct=G.closeButtonWrapper;Ue&&ct&&ct.parentElement===Ue?Ue.insertBefore(te,ct):Ue&&Ue.appendChild(te)}let Ze=G.closeButtonWrapper;Ze&&!Ze.classList.contains("tvw-absolute")&&(We?Ze.classList.add("tvw-ml-auto"):Ze.classList.remove("tvw-ml-auto"))}}if(be){let We=(to=H.size)!=null?to:"32px";P.style.height=We,P.style.width=We;let xe=(no=H.iconName)!=null?no:"refresh-cw",Ze=(so=H.iconColor)!=null?so:"";P.innerHTML="";let Ue=ge(xe,"20px",Ze||"",2);if(Ue&&P.appendChild(Ue),Ze?(P.style.color=Ze,P.classList.remove("tvw-text-cw-muted")):(P.style.color="",P.classList.add("tvw-text-cw-muted")),H.backgroundColor?(P.style.backgroundColor=H.backgroundColor,P.classList.remove("hover:tvw-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:tvw-bg-gray-100")),H.borderWidth||H.borderColor){let Ae=H.borderWidth||"0px",ye=H.borderColor||"transparent";P.style.border=`${Ae} solid ${ye}`,P.classList.remove("tvw-border-none")}else P.style.border="",P.classList.add("tvw-border-none");H.borderRadius?(P.style.borderRadius=H.borderRadius,P.classList.remove("tvw-rounded-full")):(P.style.borderRadius="",P.classList.add("tvw-rounded-full")),H.paddingX?(P.style.paddingLeft=H.paddingX,P.style.paddingRight=H.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),H.paddingY?(P.style.paddingTop=H.paddingY,P.style.paddingBottom=H.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let ct=(oo=H.tooltipText)!=null?oo:"Clear chat",Nt=(ro=H.showTooltip)!=null?ro:!0;if(P.setAttribute("aria-label",ct),te&&(te._cleanupTooltip&&(te._cleanupTooltip(),delete te._cleanupTooltip),Nt&&ct)){let Ae=null,ye=()=>{if(Ae||!P)return;Ae=f("div","tvw-clear-chat-tooltip"),Ae.textContent=ct;let tt=f("div");tt.className="tvw-clear-chat-tooltip-arrow",Ae.appendChild(tt);let Gt=P.getBoundingClientRect();Ae.style.position="fixed",Ae.style.left=`${Gt.left+Gt.width/2}px`,Ae.style.top=`${Gt.top-8}px`,Ae.style.transform="translate(-50%, -100%)",document.body.appendChild(Ae)},et=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};te.addEventListener("mouseenter",ye),te.addEventListener("mouseleave",et),P.addEventListener("focus",ye),P.addEventListener("blur",et),te._cleanupTooltip=()=>{et(),te&&(te.removeEventListener("mouseenter",ye),te.removeEventListener("mouseleave",et)),P&&(P.removeEventListener("focus",ye),P.removeEventListener("blur",et))}}}}let we=t.actionParsers&&t.actionParsers.length?t.actionParsers:[gn],ue=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick];C=mn({parsers:we,handlers:ue,getMetadata:c,updateMetadata:w,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),W=Qo(t,C),E.updateConfig(t),jt(Q,E.getMessages(),W),ot.render(t.suggestionChips,E,de,void 0,t.suggestionChipsConfig),an(),Xt(E.isStreaming());let Pe=((io=t.voiceRecognition)==null?void 0:io.enabled)===!0,it=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Xe=Pe&&it;if(Ge.classList.remove("tvw-gap-1","tvw-gap-3"),Ge.classList.add(Xe?"tvw-gap-1":"tvw-gap-3"),Pe&&it)if(!I||!Be){let H=ae(t.voiceRecognition,t.sendButton);H&&(I=H.micButton,Be=H.micButtonWrapper,Ge.insertBefore(Be,ze),I.addEventListener("click",k),I.disabled=E.isStreaming())}else{let H=(ao=t.voiceRecognition)!=null?ao:{},be=(lo=t.sendButton)!=null?lo:{},le=(co=H.iconName)!=null?co:"mic",We=(uo=be.size)!=null?uo:"40px",xe=(po=H.iconSize)!=null?po:We,Ze=parseFloat(xe)||24;I.style.width=xe,I.style.height=xe,I.style.minWidth=xe,I.style.minHeight=xe;let Ue=(mo=(go=H.iconColor)!=null?go:be.textColor)!=null?mo:"currentColor";I.innerHTML="";let ct=ge(le,Ze,Ue,2);ct?I.appendChild(ct):I.textContent="\u{1F3A4}";let Nt=(ho=H.backgroundColor)!=null?ho:be.backgroundColor;Nt?(I.style.backgroundColor=Nt,I.classList.remove("tvw-bg-cw-primary")):(I.style.backgroundColor="",I.classList.add("tvw-bg-cw-primary")),Ue?(I.style.color=Ue,I.classList.remove("tvw-text-white")):!Ue&&!be.textColor&&(I.style.color="",I.classList.add("tvw-text-white")),H.borderWidth?(I.style.borderWidth=H.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),H.borderColor?I.style.borderColor=H.borderColor:I.style.borderColor="",H.paddingX?(I.style.paddingLeft=H.paddingX,I.style.paddingRight=H.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),H.paddingY?(I.style.paddingTop=H.paddingY,I.style.paddingBottom=H.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let Ae=Be==null?void 0:Be.querySelector(".tvw-send-button-tooltip"),ye=(fo=H.tooltipText)!=null?fo:"Start voice recognition";if(((wo=H.showTooltip)!=null?wo:!1)&&ye)if(Ae)Ae.textContent=ye,Ae.style.display="";else{let tt=document.createElement("div");tt.className="tvw-send-button-tooltip",tt.textContent=ye,Be==null||Be.insertBefore(tt,I)}else Ae&&(Ae.style.display="none");Be.style.display="",I.disabled=E.isStreaming()}else I&&Be&&(Be.style.display="none",me&&Oe());let he=(yo=t.sendButton)!=null?yo:{},Ut=(vo=he.useIcon)!=null?vo:!1,Rt=(bo=he.iconText)!=null?bo:"\u2191",Pt=he.iconName,kt=(Co=he.tooltipText)!=null?Co:"Send message",vn=(xo=he.showTooltip)!=null?xo:!1,It=(So=he.size)!=null?So:"40px",zt=he.backgroundColor,dt=he.textColor;if(Ut){if(_.style.width=It,_.style.height=It,_.style.minWidth=It,_.style.minHeight=It,_.style.fontSize="18px",_.style.lineHeight="1",_.innerHTML="",Pt){let H=parseFloat(It)||24,be=dt&&typeof dt=="string"&&dt.trim()?dt.trim():"currentColor",le=ge(Pt,H,be,2);le?(_.appendChild(le),_.style.color=be):(_.textContent=Rt,dt?_.style.color=dt:_.classList.add("tvw-text-white"))}else _.textContent=Rt,dt?_.style.color=dt:_.classList.add("tvw-text-white");_.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",zt?(_.style.backgroundColor=zt,_.classList.remove("tvw-bg-cw-primary")):_.classList.add("tvw-bg-cw-primary")}else _.textContent=(To=(Ao=t.copy)==null?void 0:Ao.sendButtonLabel)!=null?To:"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",zt?(_.style.backgroundColor=zt,_.classList.remove("tvw-bg-cw-accent")):_.classList.add("tvw-bg-cw-accent"),dt?_.style.color=dt:_.classList.add("tvw-text-white");he.borderWidth?(_.style.borderWidth=he.borderWidth,_.style.borderStyle="solid"):(_.style.borderWidth="",_.style.borderStyle=""),he.borderColor?_.style.borderColor=he.borderColor:_.style.borderColor="",he.paddingX?(_.style.paddingLeft=he.paddingX,_.style.paddingRight=he.paddingX):(_.style.paddingLeft="",_.style.paddingRight=""),he.paddingY?(_.style.paddingTop=he.paddingY,_.style.paddingBottom=he.paddingY):(_.style.paddingTop="",_.style.paddingBottom="");let $t=ze==null?void 0:ze.querySelector(".tvw-send-button-tooltip");if(vn&&kt)if($t)$t.textContent=kt,$t.style.display="";else{let H=document.createElement("div");H.className="tvw-send-button-tooltip",H.textContent=kt,ze==null||ze.insertBefore(H,_)}else $t&&($t.style.display="none");let Ft=(Eo=t.statusIndicator)!=null?Eo:{},bn=(Mo=Ft.visible)!=null?Mo:!0;if(nt.style.display=bn?"":"none",E){let H=E.getStatus(),be=le=>{var We,xe,Ze,Ue;return le==="idle"?(We=Ft.idleText)!=null?We:Ve.idle:le==="connecting"?(xe=Ft.connectingText)!=null?xe:Ve.connecting:le==="connected"?(Ze=Ft.connectedText)!=null?Ze:Ve.connected:le==="error"?(Ue=Ft.errorText)!=null?Ue:Ve.error:Ve[le]};nt.textContent=be(H)}},open(){g&&Ke(!0,"api")},close(){g&&Ke(!1,"api")},toggle(){g&&Ke(!b,"api")},clearChat(){E.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},C.syncFromMetadata()},setMessage(a){return!de||E.isStreaming()?!1:(!b&&g&&Ke(!0,"system"),de.value=a,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(E.isStreaming())return!1;let p=(a==null?void 0:a.trim())||de.value.trim();return p?(!b&&g&&Ke(!0,"system"),de.value="",E.sendMessage(p),!0):!1},startVoiceRecognition(){return me||E.isStreaming()||!Me()?!1:(!b&&g&&Ke(!0,"system"),Z.manuallyDeactivated=!1,gt(),L("user"),!0)},stopVoiceRecognition(){return me?(Z.manuallyDeactivated=!0,gt(),Oe("user"),!0):!1},injectTestMessage(a){!b&&g&&Ke(!0,"system"),E.injectTestEvent(a)},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){w(a)},on(a,p){return o.on(a,p)},off(a,p){o.off(a,p)},isOpen(){return g&&b},isVoiceActive(){return Z.active},getState(){return{open:g&&b,launcherEnabled:g,voiceActive:Z.active,streaming:E.isStreaming()}},showCSATFeedback(a){!b&&g&&Ke(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let T=Dn({onSubmit:async(F,B)=>{var ne;E.isClientTokenMode()&&await E.submitCSATFeedback(F,B),(ne=a==null?void 0:a.onSubmit)==null||ne.call(a,F,B)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!b&&g&&Ke(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let T=_n({onSubmit:async(F,B)=>{var ne;E.isClientTokenMode()&&await E.submitNPSFeedback(F,B),(ne=a==null?void 0:a.onSubmit)==null||ne.call(a,F,B)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,p){return E.submitCSATFeedback(a,p)},async submitNPSFeedback(a,p){return E.submitNPSFeedback(a,p)},destroy(){He.forEach(a=>a()),R.remove(),K==null||K.destroy(),X==null||X.remove(),Ye&&q.removeEventListener("click",Ye)}};if((((Ts=s==null?void 0:s.debugTools)!=null?Ts:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:re,getMessages:re.getMessages,getStatus:re.getStatus,getMetadata:re.getPersistentMetadata,updateMetadata:re.updatePersistentMetadata,clearHistory:()=>re.clearChat(),setVoiceActive:T=>T?re.startVoiceRecognition():re.stopVoiceRecognition()};window.AgentWidgetBrowser=p,He.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return re};var hs={},Br=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},Hr=()=>{try{if(typeof hs!="undefined"&&hs.url)return new URL("../widget.css",hs.url).href}catch{}return null},Zo=n=>{let e=Hr(),s=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let r=t.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else s();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},fs=n=>{var c,w,y,u;let e=Br(n.target),s=document.createElement("div");s.className="vanilla-agent-host";let t=(y=(w=(c=n.config)==null?void 0:c.launcher)==null?void 0:w.enabled)!=null?y:!0;t||(s.style.height="100%"),e.appendChild(s);let r=n.useShadowDom===!0,o,i;if(r){let C=s.attachShadow({mode:"open"});i=C,o=document.createElement("div"),o.id="vanilla-agent-root",t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),C.appendChild(o),Zo(C)}else i=s,o=document.createElement("div"),o.id="vanilla-agent-root",t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),s.appendChild(o),Zo(s);let l=jn(o,n.config,{debugTools:n.debugTools});(u=n.onReady)==null||u.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 Rr(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function qn(n){var e,s;return(s=(e=n.parserType)!=null?e:Rr(n.streamParser))!=null?s:"plain"}function Un(n,e){let s=[];return n.toolCall&&(s.push(`${e}toolCall: {`),Object.entries(n.toolCall).forEach(([t,r])=>{typeof r=="string"&&s.push(`${e} ${t}: "${r}",`)}),s.push(`${e}},`)),s}function zn(n,e){let s=[];return n.messageActions&&Object.entries(n.messageActions).some(([r,o])=>r!=="onFeedback"&&r!=="onCopy"&&o!==void 0)&&(s.push(`${e}messageActions: {`),Object.entries(n.messageActions).forEach(([r,o])=>{r==="onFeedback"||r==="onCopy"||(typeof o=="string"?s.push(`${e} ${r}: "${o}",`):typeof o=="boolean"&&s.push(`${e} ${r}: ${o},`))}),s.push(`${e}},`)),s}function Jn(n,e){let s=[];if(n.markdown){let t=n.markdown.options&&Object.keys(n.markdown.options).length>0,r=n.markdown.disableDefaultStyles!==void 0;(t||r)&&(s.push(`${e}markdown: {`),t&&(s.push(`${e} options: {`),Object.entries(n.markdown.options).forEach(([o,i])=>{typeof i=="string"?s.push(`${e} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${e} ${o}: ${i},`)}),s.push(`${e} },`)),r&&s.push(`${e} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),s.push(`${e}},`))}return s}function Yn(n,e){let s=[];if(n.layout){let t=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");(t||r)&&(s.push(`${e}layout: {`),t&&(s.push(`${e} header: {`),Object.entries(n.layout.header).forEach(([o,i])=>{o!=="render"&&(typeof i=="string"?s.push(`${e} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${e} ${o}: ${i},`))}),s.push(`${e} },`)),r&&(s.push(`${e} messages: {`),Object.entries(n.layout.messages).forEach(([o,i])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof i=="object"&&i!==null?(s.push(`${e} avatar: {`),Object.entries(i).forEach(([l,d])=>{typeof d=="string"?s.push(`${e} ${l}: "${d}",`):typeof d=="boolean"&&s.push(`${e} ${l}: ${d},`)}),s.push(`${e} },`)):o==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(s.push(`${e} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?s.push(`${e} ${d}: "${c}",`):typeof c=="boolean"&&s.push(`${e} ${d}: ${c},`))}),s.push(`${e} },`)):typeof i=="string"?s.push(`${e} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${e} ${o}: ${i},`))}),s.push(`${e} },`)),s.push(`${e}},`))}return s}function er(n,e="esm"){let s={...n};return delete s.postprocessMessage,delete s.initialMessages,e==="esm"?Pr(s):e==="script-installer"?Fr(s):e==="script-advanced"?Or(s):e==="react-component"?Ir(s):e==="react-advanced"?$r(s):Nr(s)}function Pr(n){let e=qn(n),s=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...Un(n," ")),t.push(...zn(n," ")),t.push(...Jn(n," ")),t.push(...Yn(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
61
+ `)}function Ir(n){let e=qn(n),s=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...Un(n," ")),t.push(...zn(n," ")),t.push(...Jn(n," ")),t.push(...Yn(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
62
+ `)}function $r(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...Un(n," ")),e.push(...zn(n," ")),e.push(...Jn(n," ")),e.push(...Yn(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
63
+ `)}function tr(n){var r;let e=qn(n),s=e!=="plain",t={};if(n.apiUrl&&(t.apiUrl=n.apiUrl),n.flowId&&(t.flowId=n.flowId),s&&(t.parserType=e),n.theme&&(t.theme=n.theme),n.launcher&&(t.launcher=n.launcher),n.copy&&(t.copy=n.copy),n.sendButton&&(t.sendButton=n.sendButton),n.voiceRecognition&&(t.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(t.statusIndicator=n.statusIndicator),n.features&&(t.features=n.features),((r=n.suggestionChips)==null?void 0:r.length)>0&&(t.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(t.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(t.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&&(t.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&&(t.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&&(t.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,y])=>{w!=="format"&&(typeof y=="string"||typeof y=="boolean")&&(c[w]=y)}),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&&(t.layout=o)}return t}function Fr(n){let e=tr(n);return`<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js" data-config='${JSON.stringify(e,null,0).replace(/'/g,"&#39;")}'></script>`}function Nr(n){let e=qn(n),s=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...Un(n," ")),t.push(...zn(n," ")),t.push(...Jn(n," ")),t.push(...Yn(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
64
+ `)}function Or(n){let e=tr(n);return["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(e,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);"," });"," };",""," // Boot sequence: load CSS, then JS, then initialize"," loadCSS();"," loadJS(function() {"," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', init);"," } else {"," init();"," }"," });","})();","</script>"].join(`
67
+ `)}var Dr=fs;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});
67
68
  //# sourceMappingURL=index.cjs.map