vanilla-agent 1.22.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var Fo=Object.create;var bn=Object.defineProperty;var Do=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var jo=Object.getPrototypeOf,_o=Object.prototype.hasOwnProperty;var qo=(n,e)=>{for(var s in e)bn(n,s,{get:e[s],enumerable:!0})},ho=(n,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of No(e))!_o.call(n,r)&&r!==s&&bn(n,r,{get:()=>e[r],enumerable:!(t=Do(e,r))||t.enumerable});return n};var Uo=(n,e,s)=>(s=n!=null?Fo(jo(n)):{},ho(e||!n||!n.__esModule?bn(s,"default",{value:n,enumerable:!0}):s,n)),zo=n=>ho(bn({},"__esModule",{value:!0}),n);var xr={};qo(xr,{AgentWidgetClient:()=>Yt,AgentWidgetSession:()=>Zt,DEFAULT_WIDGET_CONFIG:()=>ke,attachHeaderToContainer:()=>Qt,buildComposer:()=>en,buildDefaultHeader:()=>qn,buildExpandedHeader:()=>zn,buildHeader:()=>Dt,buildHeaderWithLayout:()=>Ln,buildMinimalHeader:()=>Un,componentRegistry:()=>nn,createActionManager:()=>mn,createAgentExperience:()=>$n,createBubbleWithLayout:()=>Wo,createComponentMiddleware:()=>Ro,createComponentStreamParser:()=>Hn,createDirectivePostprocessor:()=>vo,createFlexibleJsonStreamParser:()=>So,createJsonStreamParser:()=>En,createLocalStorageAdapter:()=>Bn,createMarkdownProcessor:()=>dn,createMarkdownProcessorFromConfig:()=>cn,createMessageActions:()=>Yn,createPlainTextParser:()=>An,createRegexJsonParser:()=>Tn,createStandardBubble:()=>tn,createTypingIndicator:()=>un,createXmlParser:()=>Wn,default:()=>Cr,defaultActionHandlers:()=>Kt,defaultJsonActionParser:()=>hn,directivePostprocessor:()=>bo,escapeHtml:()=>Cn,extractComponentDirectiveFromMessage:()=>Pn,generateCodeSnippet:()=>Oo,getHeaderLayout:()=>Jn,hasComponentDirective:()=>In,headerLayouts:()=>Mn,initAgentWidget:()=>os,isComponentDirectiveType:()=>Ho,markdownPostprocessor:()=>Nn,mergeWithDefaults:()=>kn,pluginRegistry:()=>gn,renderComponentDirective:()=>Rn});module.exports=zo(xr);var fo=require("marked"),Jo=n=>{if(n)return n},dn=n=>{var r,o;let e=n==null?void 0:n.markedOptions,s=new fo.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=Jo(n==null?void 0:n.renderer);return t&&s.use({renderer:t}),i=>s.parse(i)},cn=n=>n?dn({markedOptions:n.options,renderer:n.renderer}):dn(),Yo=dn(),Nn=n=>Yo(n),Cn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),wo=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),mo=n=>`%%FORM_PLACEHOLDER_${n}%%`,yo=(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=mo(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=mo(e.length);return e.push({token:o,type:r}),o}),s},vo=n=>{let e=cn(n);return s=>{let t=[],r=yo(s,t),o=e(r);return t.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="tvw-form-directive" data-tv-form="${wo(l)}"></div>`;o=o.replace(d,c)}),o}},bo=n=>{let e=[],s=yo(n,e),t=Nn(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="${wo(o)}"></div>`;t=t.replace(i,d)}),t};var kt=require("partial-json"),xn=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),jn=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},Ko=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`},Co=n=>n.status==="complete"?Ko(n):n.status==="pending"?"Waiting":"",Xo=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 xo=n=>n.status==="complete"?Xo(n):"Using tool...",Vo=()=>{let n=null,e=0,s=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=t.match(r);if(o&&o[1])try{return o[1].replace(/\\n/g,`
3
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let 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()=>{}}},Sn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},An=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Tn=()=>{var e;let n=Vo();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)}},En=()=>{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,kt.parse)(s,kt.STR|kt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?xn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=xn(r.text)))}catch{}return e=s.length,n!==null?{text:n,raw:s}:null},close:()=>{}}},So=n=>{let e=null,s=0,r=n||(o=>{if(!o||typeof o!="object")return null;let i=l=>typeof l=="string"?xn(l):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?xn(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,kt.parse)(o,kt.STR|kt.OBJ),d=r(l);d!==null&&(e=d)}catch{}return s=o.length,{text:e||"",raw:o}},close:()=>{}}},Wn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Go="https://api.travrse.ai/v1/dispatch",Zo="https://api.travrse.ai";function Qo(n){switch(n){case"json":return En;case"regex-json":return Tn;case"xml":return Wn;case"plain":default:return An}}var Yt=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;var s,t,r;this.apiUrl=(s=e.apiUrl)!=null?s:Go,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:Qo(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$/,""))||Zo;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}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 y=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:y}),y}let u={session_id:d.sessionId,messages:e.messages.map(y=>({role:y.role,content:y.rawContent||y.content}))};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let c=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:t.signal});if(!c.ok){let y=await c.json().catch(()=>({error:"Chat request failed"}));if(c.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let b=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:b}),b}if(c.status===429){let b=new Error(y.hint||"Message limit reached for this session.");throw s({type:"error",error:b}),b}let m=new Error(y.error||"Failed to send message");throw s({type:"error",error:m}),m}if(!c.body){let y=new Error("No response body received");throw s({type:"error",error:y}),y}s({type:"status",status:"connected"});try{await this.streamResponse(c.body,s)}finally{s({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&s({type:"error",error:u}),u}}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){var De,oe,$,qe,Xe,tt,bt,Ct,q,he,mt,ft,Ve,nt,L,Re,it,at,Tt,wt,$e,st,Ue,U,lt,Ae,Oe,Z,Te,Ee,ze,Je,xt,Bt,yt,Et,St,we,Ht,Be,Ye,At,Nt,Wt,jt,Mt,fn,wn,yn,Fn,_t,qt,ot,Xt,rn,an;let t=e.getReader(),r=new TextDecoder,o="",i=Date.now(),l=0,d=()=>i+l++,u=S=>{let X=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,te=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,be=S.tools?S.tools.map(xe=>({...xe,chunks:xe.chunks?[...xe.chunks]:void 0})):void 0;return{...S,reasoning:X,toolCall:te,tools:be}},c=S=>{s({type:"message",message:u(S)})},y=null,m={current:null},b=new Map,f=new Map,D={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},h=S=>{if(S==null)return null;try{return String(S)}catch{return null}},x=S=>{var X,te,be,xe,Ne;return h((Ne=(xe=(be=(te=(X=S.stepId)!=null?X:S.step_id)!=null?te:S.step)!=null?be:S.parentId)!=null?xe:S.flowStepId)!=null?Ne:S.flow_step_id)},R=S=>{var X,te,be,xe,Ne,Se,A;return h((A=(Se=(Ne=(xe=(be=(te=(X=S.callId)!=null?X:S.call_id)!=null?te:S.requestId)!=null?be:S.request_id)!=null?xe:S.toolCallId)!=null?Ne:S.tool_call_id)!=null?Se:S.stepId)!=null?A:S.step_id)},w=()=>y||(y={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},c(y),y),K=(S,X)=>{D.lastId=X,S&&D.byStep.set(S,X)},T=(S,X)=>{var Ne;let te=(Ne=S.reasoningId)!=null?Ne:S.id,be=x(S);if(te){let Se=String(te);return K(be,Se),Se}if(be){let Se=D.byStep.get(be);if(Se)return D.lastId=Se,Se}if(D.lastId&&!X)return D.lastId;if(!X)return null;let xe=`reason-${d()}`;return K(be,xe),xe},O=S=>{let X=b.get(S);if(X)return X;let te={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:S,status:"streaming",chunks:[]}};return b.set(S,te),c(te),te},ee=(S,X)=>{j.lastId=X,S&&j.byCall.set(S,X)},P=(S,X)=>{var Ne;let te=(Ne=S.toolId)!=null?Ne:S.id,be=R(S);if(te){let Se=String(te);return ee(be,Se),Se}if(be){let Se=j.byCall.get(be);if(Se)return j.lastId=Se,Se}if(j.lastId&&!X)return j.lastId;if(!X)return null;let xe=`tool-${d()}`;return ee(be,xe),xe},Y=S=>{let X=f.get(S);if(X)return X;let te={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:S,status:"pending"}};return f.set(S,te),c(te),te},fe=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let X=Number(S);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let te=Date.parse(S);if(!Number.isNaN(te))return te}return Date.now()},J=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},F=new Map,ne=new Map;for(;;){let{done:S,value:X}=await t.read();if(S)break;o+=r.decode(X,{stream:!0});let te=o.split(`
1
+ "use strict";var Uo=Object.create;var Cn=Object.defineProperty;var zo=Object.getOwnPropertyDescriptor;var Jo=Object.getOwnPropertyNames;var Yo=Object.getPrototypeOf,Ko=Object.prototype.hasOwnProperty;var Xo=(n,e)=>{for(var s in e)Cn(n,s,{get:e[s],enumerable:!0})},yo=(n,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jo(e))!Ko.call(n,r)&&r!==s&&Cn(n,r,{get:()=>e[r],enumerable:!(t=zo(e,r))||t.enumerable});return n};var Vo=(n,e,s)=>(s=n!=null?Uo(Yo(n)):{},yo(e||!n||!n.__esModule?Cn(s,"default",{value:n,enumerable:!0}):s,n)),Go=n=>yo(Cn({},"__esModule",{value:!0}),n);var Wr={};Xo(Wr,{AgentWidgetClient:()=>Yt,AgentWidgetSession:()=>Zt,DEFAULT_WIDGET_CONFIG:()=>ke,attachHeaderToContainer:()=>Qt,buildComposer:()=>en,buildDefaultHeader:()=>Kn,buildExpandedHeader:()=>Vn,buildHeader:()=>Ot,buildHeaderWithLayout:()=>Hn,buildMinimalHeader:()=>Xn,componentRegistry:()=>nn,createActionManager:()=>fn,createAgentExperience:()=>_n,createBubbleWithLayout:()=>Po,createCSATFeedback:()=>On,createComponentMiddleware:()=>Oo,createComponentStreamParser:()=>In,createDirectivePostprocessor:()=>So,createFlexibleJsonStreamParser:()=>Mo,createJsonStreamParser:()=>Mn,createLocalStorageAdapter:()=>Rn,createMarkdownProcessor:()=>cn,createMarkdownProcessorFromConfig:()=>un,createMessageActions:()=>Zn,createNPSFeedback:()=>Dn,createPlainTextParser:()=>Tn,createRegexJsonParser:()=>En,createStandardBubble:()=>tn,createTypingIndicator:()=>gn,createXmlParser:()=>Wn,default:()=>Mr,defaultActionHandlers:()=>Kt,defaultJsonActionParser:()=>mn,directivePostprocessor:()=>Ao,escapeHtml:()=>xn,extractComponentDirectiveFromMessage:()=>Nn,generateAssistantMessageId:()=>Ln,generateCodeSnippet:()=>qo,generateMessageId:()=>ko,generateUserMessageId:()=>kn,getHeaderLayout:()=>Gn,hasComponentDirective:()=>Fn,headerLayouts:()=>Bn,initAgentWidget:()=>ds,isComponentDirectiveType:()=>No,markdownPostprocessor:()=>zn,mergeWithDefaults:()=>Pn,pluginRegistry:()=>hn,renderComponentDirective:()=>$n});module.exports=Go(Wr);var bo=require("marked"),Zo=n=>{if(n)return n},cn=n=>{var r,o;let e=n==null?void 0:n.markedOptions,s=new bo.Marked({gfm:(r=e==null?void 0:e.gfm)!=null?r:!0,breaks:(o=e==null?void 0:e.breaks)!=null?o:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),t=Zo(n==null?void 0:n.renderer);return t&&s.use({renderer:t}),a=>s.parse(a)},un=n=>n?cn({markedOptions:n.options,renderer:n.renderer}):cn(),Qo=cn(),zn=n=>Qo(n),xn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Co=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vo=n=>`%%FORM_PLACEHOLDER_${n}%%`,xo=(n,e)=>{let s=n;return s=s.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let o=JSON.parse(r.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=vo(e.length);return e.push({token:a,type:String(o.type)}),a}}catch{return t}return t}),s=s.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let o=vo(e.length);return e.push({token:o,type:r}),o}),s},So=n=>{let e=un(n);return s=>{let t=[],r=xo(s,t),o=e(r);return t.forEach(({token:a,type:l})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${Co(l)}"></div>`;o=o.replace(p,f)}),o}},Ao=n=>{let e=[],s=xo(n,e),t=zn(s);return e.forEach(({token:r,type:o})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="tvw-form-directive" data-tv-form="${Co(o)}"></div>`;t=t.replace(a,p)}),t};var Lt=require("partial-json"),Sn=n=>n.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Jn=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},er=n=>{var a,l;let e=(a=n.completedAt)!=null?a:Date.now(),s=(l=n.startedAt)!=null?l:e,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-s))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},To=n=>n.status==="complete"?er(n):n.status==="pending"?"Waiting":"",tr=n=>{var r,o,a;let s=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((r=n.completedAt)!=null?r:Date.now())-((a=(o=n.startedAt)!=null?o:n.completedAt)!=null?a:Date.now())))/1e3;return s<.1?"Used tool for <0.1 seconds":`Used tool for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`};var Eo=n=>n.status==="complete"?tr(n):"Using tool...",nr=()=>{let n=null,e=0,s=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=t.match(r);if(o&&o[1])try{return o[1].replace(/\\n/g,`
3
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=t.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let o=s(t);return o!==null&&(n=o),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},An=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Tn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},En=()=>{var e;let n=nr();return{processChunk:async s=>{let t=s.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(s)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Mn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:s=>{let t=s.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(s.length<=e)return n!==null||n===""?{text:n||"",raw:s}:null;try{let r=(0,Lt.parse)(s,Lt.STR|Lt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?Sn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=Sn(r.text)))}catch{}return e=s.length,n!==null?{text:n,raw:s}:null},close:()=>{}}},Mo=n=>{let e=null,s=0,r=n||(o=>{if(!o||typeof o!="object")return null;let a=l=>typeof l=="string"?Sn(l):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Sn(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>e,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=s)return e!==null?{text:e,raw:o}:null;try{let l=(0,Lt.parse)(o,Lt.STR|Lt.OBJ),p=r(l);p!==null&&(e=p)}catch{}return s=o.length,{text:e||"",raw:o}},close:()=>{}}},Wn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var sr="https://api.travrse.ai/v1/dispatch",Wo="https://api.travrse.ai";function or(n){switch(n){case"json":return Mn;case"regex-json":return En;case"xml":return Wn;case"plain":default:return Tn}}var Yt=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;var s,t,r;this.apiUrl=(s=e.apiUrl)!=null?s:sr,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:or(e.parserType),this.contextProviders=(r=e.contextProviders)!=null?r:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(e){var t;let s=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wo;return e==="init"?`${s}/v1/client/init`:`${s}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var e,s;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(s=(e=this.config).onSessionInit)==null||s.call(e,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.clientToken,flow_id:this.config.flowId})});if(!e.ok){let t=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${t.hint||t.error}`):e.status===403?new Error(`Origin not allowed: ${t.hint||t.error}`):new Error(t.error||"Failed to initialize session")}let s=await e.json();return{sessionId:s.session_id,expiresAt:new Date(s.expires_at),flow:s.flow,config:{welcomeMessage:s.config.welcome_message,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var s;return`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wo}/v1/client/feedback`}async sendFeedback(e){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.message_id)throw new Error(`message_id is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:e,type:s})}async submitCSATFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:e,comment:s})}async submitNPSFeedback(e,s){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:e,comment:s})}async dispatch(e,s){return this.isClientTokenMode()?this.dispatchClientToken(e,s):this.dispatchProxy(e,s)}async dispatchClientToken(e,s){var r,o,a,l;let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),s({type:"status",status:"connecting"});try{let p=await this.initSession();if(new Date>=new Date(p.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(r=this.config).onSessionExpired)==null||o.call(r);let d=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:d}),d}let c=await this.buildPayload(e.messages),f={session_id:p.sessionId,messages:e.messages.map(d=>({id:d.id,role:d.role,content:d.rawContent||d.content})),...e.assistantMessageId&&{assistant_message_id:e.assistantMessageId},...c.metadata&&{metadata:c.metadata},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",f);let w=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f),signal:t.signal});if(!w.ok){let d=await w.json().catch(()=>({error:"Chat request failed"}));if(w.status===401){this.clientSession=null,(l=(a=this.config).onSessionExpired)==null||l.call(a);let g=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:g}),g}if(w.status===429){let g=new Error(d.hint||"Message limit reached for this session.");throw s({type:"error",error:g}),g}let C=new Error(d.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!w.body){let d=new Error("No response body received");throw s({type:"error",error:d}),d}s({type:"status",status:"connected"});try{await this.streamResponse(w.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(p){let c=p instanceof Error?p:new Error(String(p));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&s({type:"error",error:c}),c}}async dispatchProxy(e,s){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),s({type:"status",status:"connecting"});let r=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();o={...o,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal},r)}catch(l){let p=l instanceof Error?l:new Error(String(l));throw s({type:"error",error:p}),p}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal});if(!a.ok||!a.body){let l=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw s({type:"error",error:l}),l}s({type:"status",status:"connected"});try{await this.streamResponse(a.body,s)}finally{s({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((r,o)=>{let a=new Date(r.createdAt).getTime(),l=new Date(o.createdAt).getTime();return a-l}).map(r=>({role:r.role,content:r.rawContent||r.content,createdAt:r.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:e,config:this.config});a&&typeof a=="object"&&Object.assign(r,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(e,s,t,r,o){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(e);if(a===null)return!1;let l=()=>{if(t.current)return t.current;let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return t.current=p,r(p),p};if(a.text!==void 0){let p=l();p.content+=a.text,r(p)}return a.done&&(t.current&&(t.current.streaming=!1,r(t.current)),s({type:"status",status:"idle"})),a.error&&s({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(e,s,t){var re,q,qe,Ve,nt,bt,Ct,J,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,$e,ot,Ue,I,dt,Se,Oe,te,Ae,Te,ze,Je,xt,Bt,yt,Et,St,ye,Ht,Le,Ye,At,Dt,Mt,_t,Wt,wn,yn,vn,qn,jt,qt,Ke,Xt,rn,an,ln;let r=e.getReader(),o=new TextDecoder,a="",l=Date.now(),p=0,c=()=>l+p++,f=A=>{let V=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,ie=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,ve=A.tools?A.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...A,reasoning:V,toolCall:ie,tools:ve}},w=A=>{s({type:"message",message:f(A)})},d=null,C={current:null},g=new Map,U=new Map,$={lastId:null,byStep:new Map},h={lastId:null,byCall:new Map},b=A=>{if(A==null)return null;try{return String(A)}catch{return null}},W=A=>{var V,ie,ve,Fe,Ne;return b((Ne=(Fe=(ve=(ie=(V=A.stepId)!=null?V:A.step_id)!=null?ie:A.step)!=null?ve:A.parentId)!=null?Fe:A.flowStepId)!=null?Ne:A.flow_step_id)},v=A=>{var V,ie,ve,Fe,Ne,ue,P;return b((P=(ue=(Ne=(Fe=(ve=(ie=(V=A.callId)!=null?V:A.call_id)!=null?ie:A.requestId)!=null?ve:A.request_id)!=null?Fe:A.toolCallId)!=null?Ne:A.tool_call_id)!=null?ue:A.stepId)!=null?P:A.step_id)},D=()=>d||(d={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},w(d),d),x=(A,V)=>{$.lastId=V,A&&$.byStep.set(A,V)},S=(A,V)=>{var Ne;let ie=(Ne=A.reasoningId)!=null?Ne:A.id,ve=W(A);if(ie){let ue=String(ie);return x(ve,ue),ue}if(ve){let ue=$.byStep.get(ve);if(ue)return $.lastId=ue,ue}if($.lastId&&!V)return $.lastId;if(!V)return null;let Fe=`reason-${c()}`;return x(ve,Fe),Fe},X=A=>{let V=g.get(A);if(V)return V;let ie={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:A,status:"streaming",chunks:[]}};return g.set(A,ie),w(ie),ie},B=(A,V)=>{h.lastId=V,A&&h.byCall.set(A,V)},_=(A,V)=>{var Ne;let ie=(Ne=A.toolId)!=null?Ne:A.id,ve=v(A);if(ie){let ue=String(ie);return B(ve,ue),ue}if(ve){let ue=h.byCall.get(ve);if(ue)return h.lastId=ue,ue}if(h.lastId&&!V)return h.lastId;if(!V)return null;let Fe=`tool-${c()}`;return B(ve,Fe),Fe},Z=A=>{let V=U.get(A);if(V)return V;let ie={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:A,status:"pending"}};return U.set(A,ie),w(ie),ie},j=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let V=Number(A);if(!Number.isNaN(V)&&Number.isFinite(V))return V;let ie=Date.parse(A);if(!Number.isNaN(ie))return ie}return Date.now()},K=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},Q=new Map,ne=new Map;for(;;){let{done:A,value:V}=await r.read();if(A)break;a+=o.decode(V,{stream:!0});let ie=a.split(`
5
5
 
6
- `);o=(De=te.pop())!=null?De:"";for(let be of te){let xe=be.split(`
7
- `),Ne="message",Se="";for(let Q of xe)Q.startsWith("event:")?Ne=Q.replace("event:","").trim():Q.startsWith("data:")&&(Se+=Q.replace("data:","").trim());if(!Se)continue;let A;try{A=JSON.parse(Se)}catch(Q){s({type:"error",error:Q instanceof Error?Q:new Error("Failed to parse chat stream payload")});continue}let gt=Ne!=="message"?Ne:(oe=A.type)!=null?oe:"message";if(this.parseSSEEvent){m.current=y;let Q=await this.handleCustomSSEEvent(A,s,m,c,d);if(m.current&&!y&&(y=m.current),Q)continue}if(gt==="reason_start"){let Q=($=T(A,!0))!=null?$:`reason-${d()}`,E=O(Q);E.reasoning=(qe=E.reasoning)!=null?qe:{id:Q,status:"streaming",chunks:[]},E.reasoning.startedAt=(tt=E.reasoning.startedAt)!=null?tt:fe((Xe=A.startedAt)!=null?Xe:A.timestamp),E.reasoning.completedAt=void 0,E.reasoning.durationMs=void 0,E.streaming=!0,E.reasoning.status="streaming",c(E)}else if(gt==="reason_chunk"){let Q=(Ct=(bt=T(A,!1))!=null?bt:T(A,!0))!=null?Ct:`reason-${d()}`,E=O(Q);E.reasoning=(q=E.reasoning)!=null?q:{id:Q,status:"streaming",chunks:[]},E.reasoning.startedAt=(mt=E.reasoning.startedAt)!=null?mt:fe((he=A.startedAt)!=null?he:A.timestamp);let v=(nt=(Ve=(ft=A.reasoningText)!=null?ft:A.text)!=null?Ve:A.delta)!=null?nt:"";if(v&&A.hidden!==!0&&E.reasoning.chunks.push(String(v)),E.reasoning.status=A.done?"complete":"streaming",A.done){E.reasoning.completedAt=fe((L=A.completedAt)!=null?L:A.timestamp);let B=(Re=E.reasoning.startedAt)!=null?Re:Date.now();E.reasoning.durationMs=Math.max(0,((it=E.reasoning.completedAt)!=null?it:Date.now())-B)}E.streaming=E.reasoning.status!=="complete",c(E)}else if(gt==="reason_complete"){let Q=(Tt=(at=T(A,!1))!=null?at:T(A,!0))!=null?Tt:`reason-${d()}`,E=b.get(Q);if(E!=null&&E.reasoning){E.reasoning.status="complete",E.reasoning.completedAt=fe((wt=A.completedAt)!=null?wt:A.timestamp);let B=($e=E.reasoning.startedAt)!=null?$e:Date.now();E.reasoning.durationMs=Math.max(0,((st=E.reasoning.completedAt)!=null?st:Date.now())-B),E.streaming=!1,c(E)}let v=x(A);v&&D.byStep.delete(v)}else if(gt==="tool_start"){let Q=(Ue=P(A,!0))!=null?Ue:`tool-${d()}`,E=Y(Q),v=(U=E.toolCall)!=null?U:{id:Q,status:"pending"};v.name=(lt=A.toolName)!=null?lt:v.name,v.status="running",A.args!==void 0&&(v.args=A.args),v.startedAt=(Oe=v.startedAt)!=null?Oe:fe((Ae=A.startedAt)!=null?Ae:A.timestamp),v.completedAt=void 0,v.durationMs=void 0,E.toolCall=v,E.streaming=!0,c(E)}else if(gt==="tool_chunk"){let Q=(Te=(Z=P(A,!1))!=null?Z:P(A,!0))!=null?Te:`tool-${d()}`,E=Y(Q),v=(Ee=E.toolCall)!=null?Ee:{id:Q,status:"running"};v.startedAt=(Je=v.startedAt)!=null?Je:fe((ze=A.startedAt)!=null?ze:A.timestamp);let B=(yt=(Bt=(xt=A.text)!=null?xt:A.delta)!=null?Bt:A.message)!=null?yt:"";B&&(v.chunks=(Et=v.chunks)!=null?Et:[],v.chunks.push(String(B))),v.status="running",E.toolCall=v,E.streaming=!0,c(E)}else if(gt==="tool_complete"){let Q=(we=(St=P(A,!1))!=null?St:P(A,!0))!=null?we:`tool-${d()}`,E=Y(Q),v=(Ht=E.toolCall)!=null?Ht:{id:Q,status:"running"};if(v.status="complete",A.result!==void 0&&(v.result=A.result),typeof A.duration=="number"&&(v.duration=A.duration),v.completedAt=fe((Be=A.completedAt)!=null?Be:A.timestamp),typeof A.duration=="number")v.durationMs=A.duration;else{let V=(Ye=v.startedAt)!=null?Ye:Date.now();v.durationMs=Math.max(0,((At=v.completedAt)!=null?At:Date.now())-V)}E.toolCall=v,E.streaming=!1,c(E);let B=R(A);B&&j.byCall.delete(B)}else if(gt==="step_chunk"){let Q=A.stepType,E=A.executionType;if(Q==="tool"||E==="context")continue;let v=w(),B=(Mt=(jt=(Wt=(Nt=A.text)!=null?Nt:A.delta)!=null?Wt:A.content)!=null?jt:A.chunk)!=null?Mt:"";if(B){let ye=((fn=ne.get(v.id))!=null?fn:"")+B;v.rawContent=ye,F.has(v.id)||F.set(v.id,this.createStreamParser());let Ge=F.get(v.id),Me=ye.trim().startsWith("{")||ye.trim().startsWith("[");if(Me&&ne.set(v.id,ye),Ge.__isPlainTextParser===!0){v.content+=B,ne.delete(v.id),F.delete(v.id),v.rawContent=void 0,c(v);continue}let ve=Ge.processChunk(ye);if(ve instanceof Promise)ve.then(de=>{var Ie;let ce=typeof de=="string"?de:(Ie=de==null?void 0:de.text)!=null?Ie:null;if(ce!==null&&ce.trim()!==""){let pe=y;pe&&pe.id===v.id&&(pe.content=ce,c(pe))}else if(!Me&&!ye.trim().startsWith("<")){let pe=y;pe&&pe.id===v.id&&(pe.content+=B,ne.delete(pe.id),F.delete(pe.id),pe.rawContent=void 0,c(pe))}}).catch(()=>{v.content+=B,ne.delete(v.id),F.delete(v.id),v.rawContent=void 0,c(v)});else{let de=typeof ve=="string"?ve:(wn=ve==null?void 0:ve.text)!=null?wn:null;de!==null&&de.trim()!==""?(v.content=de,c(v)):!Me&&!ye.trim().startsWith("<")&&(v.content+=B,ne.delete(v.id),F.delete(v.id),v.rawContent=void 0,c(v))}}if(A.isComplete){let V=(Fn=(yn=A.result)==null?void 0:yn.response)!=null?Fn:v.content;if(V){let ye=ne.get(v.id),Ge=ye!=null?ye:J(V);v.rawContent=Ge;let Me=F.get(v.id),_e=null,ve=!1;if(Me&&(_e=Me.getExtractedText(),_e===null&&(_e=Sn(Ge)),_e===null)){let de=Me.processChunk(Ge);de instanceof Promise?(ve=!0,de.then(ce=>{var pe;let Ie=typeof ce=="string"?ce:(pe=ce==null?void 0:ce.text)!=null?pe:null;if(Ie!==null){let Fe=y;Fe&&Fe.id===v.id&&(Fe.content=Ie,Fe.streaming=!1,F.delete(Fe.id),ne.delete(Fe.id),c(Fe))}})):_e=typeof de=="string"?de:(_t=de==null?void 0:de.text)!=null?_t:null}if(!ve){_e!==null&&_e.trim()!==""?v.content=_e:ne.has(v.id)||(v.content=J(V));let de=F.get(v.id);if(de){let ce=(qt=de.close)==null?void 0:qt.call(de);ce instanceof Promise&&ce.catch(()=>{}),F.delete(v.id)}ne.delete(v.id),v.streaming=!1,c(v)}}}}else if(gt==="step_complete"){let Q=A.stepType,E=A.executionType;if(Q==="tool"||E==="context")continue;let v=(ot=A.result)==null?void 0:ot.response,B=w();if(v!=null){let V=F.get(B.id),ye=!1,Ge=!1;if(V){let Me=V.getExtractedText(),_e=ne.get(B.id),ve=_e!=null?_e:J(v);if(B.rawContent=ve,Me!==null&&Me.trim()!=="")B.content=Me,ye=!0;else{let de=Sn(ve);if(de!==null)B.content=de,ye=!0;else{let ce=V.processChunk(ve);if(ce instanceof Promise)Ge=!0,ce.then(Ie=>{var Fe;let pe=typeof Ie=="string"?Ie:(Fe=Ie==null?void 0:Ie.text)!=null?Fe:null;if(pe!==null&&pe.trim()!==""){let rt=y;rt&&rt.id===B.id&&(rt.content=pe,rt.streaming=!1,F.delete(rt.id),ne.delete(rt.id),c(rt))}else{let rt=V.getExtractedText(),ht=y;ht&&ht.id===B.id&&(rt!==null&&rt.trim()!==""?ht.content=rt:ne.has(ht.id)||(ht.content=J(v)),ht.streaming=!1,F.delete(ht.id),ne.delete(ht.id),c(ht))}});else{let Ie=typeof ce=="string"?ce:(Xt=ce==null?void 0:ce.text)!=null?Xt:null;if(Ie!==null&&Ie.trim()!=="")B.content=Ie,ye=!0;else{let pe=V.getExtractedText();pe!==null&&pe.trim()!==""&&(B.content=pe,ye=!0)}}}}}if(!Ge){if(!B.rawContent){let Me=ne.get(B.id);B.rawContent=Me!=null?Me:J(v)}if(!ye&&!ne.has(B.id)&&(B.content=J(v)),V){let Me=(rn=V.close)==null?void 0:rn.call(V);Me instanceof Promise&&Me.catch(()=>{})}F.delete(B.id),ne.delete(B.id),B.streaming=!1,c(B)}}else F.delete(B.id),ne.delete(B.id),B.streaming=!1,c(B)}else if(gt==="flow_complete"){let Q=(an=A.result)==null?void 0:an.response;if(Q!=null){let E=w(),v=ne.get(E.id),B=v!=null?v:J(Q);E.rawContent=B;let V=J(Q),ye=F.get(E.id);if(ye){let _e=Sn(B);if(_e!==null)V=_e;else{let ve=ye.processChunk(B);ve instanceof Promise&&ve.then(ce=>{var pe;let Ie=typeof ce=="string"?ce:(pe=ce==null?void 0:ce.text)!=null?pe:null;if(Ie!==null){let Fe=y;Fe&&Fe.id===E.id&&(Fe.content=Ie,Fe.streaming=!1,c(Fe))}});let de=ye.getExtractedText();de!==null&&(V=de)}}F.delete(E.id),ne.delete(E.id);let Ge=V!==E.content,Me=E.streaming!==!1;Ge&&(E.content=V),E.streaming=!1,(Ge||Me)&&c(E)}else if(y!==null){let E=y;F.delete(E.id),ne.delete(E.id),E.streaming!==!1&&(E.streaming=!1,c(E))}s({type:"status",status:"idle"})}else gt==="error"&&A.error&&s({type:"error",error:A.error instanceof Error?A.error:new Error(String(A.error))})}}}};var Zt=class{constructor(e={},s){this.config=e;this.callbacks=s;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=e=>{var s,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(s=this.callbacks).onError)==null||t.call(s,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(r=>{var o;return{...r,sequence:(o=r.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var e,s;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(s=(e=this.callbacks).onError)==null||s.call(e,t instanceof Error?t:new Error(String(t))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(s)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}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 l,d,u,c,y;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let r={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(s==null?void 0:s.viaVoice)||!1};this.appendMessage(r),this.setStreaming(!0);let o=new AbortController;this.abortController=o;let i=[...this.messages];try{await this.client.dispatch({messages:i,signal:o.signal},this.handleEvent)}catch(m){let b={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m instanceof Error?(u=(d=this.callbacks).onError)==null||u.call(d,m):(y=(c=this.callbacks).onError)==null||y.call(c,new Error(String(m)))}}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,u;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=(u=t.sequence)!=null?u:0;return i!==l?i-l:s.id.localeCompare(t.id)})}};var _n=(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 er=Uo(require("lucide"),1),le=(n,e=24,s="currentColor",t=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),o=er[r];return o?tr(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 tr(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(([u,c])=>{u!=="stroke"&&d.setAttribute(u,String(c))}),r.appendChild(d)}}}),r}var p=(n,e)=>{let s=document.createElement(n);return e&&(s.className=e),s};var Ke={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var vt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var pn=(n,e)=>{let s=p("button");s.type="button",s.innerHTML=`
6
+ `);a=(re=ie.pop())!=null?re:"";for(let ve of ie){let Fe=ve.split(`
7
+ `),Ne="message",ue="";for(let se of Fe)se.startsWith("event:")?Ne=se.replace("event:","").trim():se.startsWith("data:")&&(ue+=se.replace("data:","").trim());if(!ue)continue;let P;try{P=JSON.parse(ue)}catch(se){s({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let rt=Ne!=="message"?Ne:(q=P.type)!=null?q:"message";if(this.parseSSEEvent){C.current=d;let se=await this.handleCustomSSEEvent(P,s,C,w,c);if(C.current&&!d&&(d=C.current),se)continue}if(rt==="reason_start"){let se=(qe=S(P,!0))!=null?qe:`reason-${c()}`,M=X(se);M.reasoning=(Ve=M.reasoning)!=null?Ve:{id:se,status:"streaming",chunks:[]},M.reasoning.startedAt=(bt=M.reasoning.startedAt)!=null?bt:j((nt=P.startedAt)!=null?nt:P.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",w(M)}else if(rt==="reason_chunk"){let se=(J=(Ct=S(P,!1))!=null?Ct:S(P,!0))!=null?J:`reason-${c()}`,M=X(se);M.reasoning=(fe=M.reasoning)!=null?fe:{id:se,status:"streaming",chunks:[]},M.reasoning.startedAt=(ft=M.reasoning.startedAt)!=null?ft:j((mt=P.startedAt)!=null?mt:P.timestamp);let y=(H=(st=(Ge=P.reasoningText)!=null?Ge:P.text)!=null?st:P.delta)!=null?H:"";if(y&&P.hidden!==!0&&M.reasoning.chunks.push(String(y)),M.reasoning.status=P.done?"complete":"streaming",P.done){M.reasoning.completedAt=j((He=P.completedAt)!=null?He:P.timestamp);let F=(at=M.reasoning.startedAt)!=null?at:Date.now();M.reasoning.durationMs=Math.max(0,((lt=M.reasoning.completedAt)!=null?lt:Date.now())-F)}M.streaming=M.reasoning.status!=="complete",w(M)}else if(rt==="reason_complete"){let se=(wt=(Tt=S(P,!1))!=null?Tt:S(P,!0))!=null?wt:`reason-${c()}`,M=g.get(se);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=j(($e=P.completedAt)!=null?$e:P.timestamp);let F=(ot=M.reasoning.startedAt)!=null?ot:Date.now();M.reasoning.durationMs=Math.max(0,((Ue=M.reasoning.completedAt)!=null?Ue:Date.now())-F),M.streaming=!1,w(M)}let y=W(P);y&&$.byStep.delete(y)}else if(rt==="tool_start"){let se=(I=_(P,!0))!=null?I:`tool-${c()}`,M=Z(se),y=(dt=M.toolCall)!=null?dt:{id:se,status:"pending"};y.name=(Se=P.toolName)!=null?Se:y.name,y.status="running",P.args!==void 0&&(y.args=P.args),y.startedAt=(te=y.startedAt)!=null?te:j((Oe=P.startedAt)!=null?Oe:P.timestamp),y.completedAt=void 0,y.durationMs=void 0,M.toolCall=y,M.streaming=!0,w(M)}else if(rt==="tool_chunk"){let se=(Te=(Ae=_(P,!1))!=null?Ae:_(P,!0))!=null?Te:`tool-${c()}`,M=Z(se),y=(ze=M.toolCall)!=null?ze:{id:se,status:"running"};y.startedAt=(xt=y.startedAt)!=null?xt:j((Je=P.startedAt)!=null?Je:P.timestamp);let F=(Et=(yt=(Bt=P.text)!=null?Bt:P.delta)!=null?yt:P.message)!=null?Et:"";F&&(y.chunks=(St=y.chunks)!=null?St:[],y.chunks.push(String(F))),y.status="running",M.toolCall=y,M.streaming=!0,w(M)}else if(rt==="tool_complete"){let se=(Ht=(ye=_(P,!1))!=null?ye:_(P,!0))!=null?Ht:`tool-${c()}`,M=Z(se),y=(Le=M.toolCall)!=null?Le:{id:se,status:"running"};if(y.status="complete",P.result!==void 0&&(y.result=P.result),typeof P.duration=="number"&&(y.duration=P.duration),y.completedAt=j((Ye=P.completedAt)!=null?Ye:P.timestamp),typeof P.duration=="number")y.durationMs=P.duration;else{let be=(At=y.startedAt)!=null?At:Date.now();y.durationMs=Math.max(0,((Dt=y.completedAt)!=null?Dt:Date.now())-be)}M.toolCall=y,M.streaming=!1,w(M);let F=v(P);F&&h.byCall.delete(F)}else if(rt==="step_chunk"){let se=P.stepType,M=P.executionType;if(se==="tool"||M==="context")continue;let y=D(),F=(wn=(Wt=(_t=(Mt=P.text)!=null?Mt:P.delta)!=null?_t:P.content)!=null?Wt:P.chunk)!=null?wn:"";if(F){let Ee=((yn=ne.get(y.id))!=null?yn:"")+F;y.rawContent=Ee,Q.has(y.id)||Q.set(y.id,this.createStreamParser());let Ze=Q.get(y.id),Pe=Ee.trim().startsWith("{")||Ee.trim().startsWith("[");if(Pe&&ne.set(y.id,Ee),Ze.__isPlainTextParser===!0){y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y);continue}let _e=Ze.processChunk(Ee);if(_e instanceof Promise)_e.then(de=>{var Re;let pe=typeof de=="string"?de:(Re=de==null?void 0:de.text)!=null?Re:null;if(pe!==null&&pe.trim()!==""){let ge=d;ge&&ge.id===y.id&&(ge.content=pe,w(ge))}else if(!Pe&&!Ee.trim().startsWith("<")){let ge=d;ge&&ge.id===y.id&&(ge.content+=F,ne.delete(ge.id),Q.delete(ge.id),ge.rawContent=void 0,w(ge))}}).catch(()=>{y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y)});else{let de=typeof _e=="string"?_e:(vn=_e==null?void 0:_e.text)!=null?vn:null;de!==null&&de.trim()!==""?(y.content=de,w(y)):!Pe&&!Ee.trim().startsWith("<")&&(y.content+=F,ne.delete(y.id),Q.delete(y.id),y.rawContent=void 0,w(y))}}if(P.isComplete){let be=(jt=(qn=P.result)==null?void 0:qn.response)!=null?jt:y.content;if(be){let Ee=ne.get(y.id),Ze=Ee!=null?Ee:K(be);y.rawContent=Ze;let Pe=Q.get(y.id),Ce=null,_e=!1;if(Pe&&(Ce=Pe.getExtractedText(),Ce===null&&(Ce=An(Ze)),Ce===null)){let de=Pe.processChunk(Ze);de instanceof Promise?(_e=!0,de.then(pe=>{var ge;let Re=typeof pe=="string"?pe:(ge=pe==null?void 0:pe.text)!=null?ge:null;if(Re!==null){let De=d;De&&De.id===y.id&&(De.content=Re,De.streaming=!1,Q.delete(De.id),ne.delete(De.id),w(De))}})):Ce=typeof de=="string"?de:(qt=de==null?void 0:de.text)!=null?qt:null}if(!_e){Ce!==null&&Ce.trim()!==""?y.content=Ce:ne.has(y.id)||(y.content=K(be));let de=Q.get(y.id);if(de){let pe=(Ke=de.close)==null?void 0:Ke.call(de);pe instanceof Promise&&pe.catch(()=>{}),Q.delete(y.id)}ne.delete(y.id),y.streaming=!1,w(y)}}}}else if(rt==="step_complete"){let se=P.stepType,M=P.executionType;if(se==="tool"||M==="context")continue;let y=(Xt=P.result)==null?void 0:Xt.response,F=D();if(y!=null){let be=Q.get(F.id),Ee=!1,Ze=!1;if(be){let Pe=be.getExtractedText(),Ce=ne.get(F.id),_e=Ce!=null?Ce:K(y);if(F.rawContent=_e,Pe!==null&&Pe.trim()!=="")F.content=Pe,Ee=!0;else{let de=An(_e);if(de!==null)F.content=de,Ee=!0;else{let pe=be.processChunk(_e);if(pe instanceof Promise)Ze=!0,pe.then(Re=>{var De;let ge=typeof Re=="string"?Re:(De=Re==null?void 0:Re.text)!=null?De:null;if(ge!==null&&ge.trim()!==""){let it=d;it&&it.id===F.id&&(it.content=ge,it.streaming=!1,Q.delete(it.id),ne.delete(it.id),w(it))}else{let it=be.getExtractedText(),ht=d;ht&&ht.id===F.id&&(it!==null&&it.trim()!==""?ht.content=it:ne.has(ht.id)||(ht.content=K(y)),ht.streaming=!1,Q.delete(ht.id),ne.delete(ht.id),w(ht))}});else{let Re=typeof pe=="string"?pe:(rn=pe==null?void 0:pe.text)!=null?rn:null;if(Re!==null&&Re.trim()!=="")F.content=Re,Ee=!0;else{let ge=be.getExtractedText();ge!==null&&ge.trim()!==""&&(F.content=ge,Ee=!0)}}}}}if(!Ze){if(!F.rawContent){let Pe=ne.get(F.id);F.rawContent=Pe!=null?Pe:K(y)}if(!Ee&&!ne.has(F.id)&&(F.content=K(y)),be){let Pe=(an=be.close)==null?void 0:an.call(be);Pe instanceof Promise&&Pe.catch(()=>{})}Q.delete(F.id),ne.delete(F.id),F.streaming=!1,w(F)}}else Q.delete(F.id),ne.delete(F.id),F.streaming=!1,w(F)}else if(rt==="flow_complete"){let se=(ln=P.result)==null?void 0:ln.response;if(se!=null){let M=D(),y=ne.get(M.id),F=y!=null?y:K(se);M.rawContent=F;let be=K(se),Ee=Q.get(M.id);if(Ee){let Ce=An(F);if(Ce!==null)be=Ce;else{let _e=Ee.processChunk(F);_e instanceof Promise&&_e.then(pe=>{var ge;let Re=typeof pe=="string"?pe:(ge=pe==null?void 0:pe.text)!=null?ge:null;if(Re!==null){let De=d;De&&De.id===M.id&&(De.content=Re,De.streaming=!1,w(De))}});let de=Ee.getExtractedText();de!==null&&(be=de)}}Q.delete(M.id),ne.delete(M.id);let Ze=be!==M.content,Pe=M.streaming!==!1;Ze&&(M.content=be),M.streaming=!1,(Ze||Pe)&&w(M)}else if(d!==null){let M=d;Q.delete(M.id),ne.delete(M.id),M.streaming!==!1&&(M.streaming=!1,w(M))}s({type:"status",status:"idle"})}else rt==="error"&&P.error&&s({type:"error",error:P.error instanceof Error?P.error:new Error(String(P.error))})}}}};function ko(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${n}_${e}`}function kn(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Ln(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Zt=class{constructor(e={},s){this.config=e;this.callbacks=s;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=e=>{var s,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(s=this.callbacks).onError)==null||t.call(s,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(r=>{var o;return{...r,sequence:(o=r.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var e,s;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(s=(e=this.callbacks).onError)==null||s.call(e,t instanceof Error?t:new Error(String(t))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(s)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,s){return this.client.submitMessageFeedback(e,s)}async submitCSATFeedback(e,s){return this.client.submitCSATFeedback(e,s)}async submitNPSFeedback(e,s){return this.client.submitNPSFeedback(e,s)}updateConfig(e){this.config={...this.config,...e},this.client=new Yt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,s){var c,f,w,d,C;let t=e.trim();if(!t)return;(c=this.abortController)==null||c.abort();let r=kn(),o=Ln(),a={id:r,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(s==null?void 0:s.viaVoice)||!1};this.appendMessage(a),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:l.signal,assistantMessageId:o},this.handleEvent)}catch(g){let U={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(U),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(w=(f=this.callbacks).onError)==null||w.call(f,g):(C=(d=this.callbacks).onError)==null||C.call(d,new Error(String(g)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let s=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,s]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let s=this.ensureSequence(e),t=this.messages.findIndex(r=>r.id===s.id);if(t===-1){this.appendMessage(s);return}this.messages=this.messages.map((r,o)=>o===t?{...r,...s}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((s,t)=>{var p,c;let r=new Date(s.createdAt).getTime(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let a=(p=s.sequence)!=null?p:0,l=(c=t.sequence)!=null?c:0;return a!==l?a-l:s.id.localeCompare(t.id)})}};var Yn=(n,e)=>{var t;let s=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(s).forEach(([r,o])=>{if(o==null||o==="")return;let a=r.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${a}`,String(o))})};var rr=Vo(require("lucide"),1),ce=(n,e=24,s="currentColor",t=2)=>{try{let r=n.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=rr[r];return o?ir(o,e,s,t):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function ir(n,e,s,t){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",s),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],l=o[1];if(l){let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([c,f])=>{c!=="stroke"&&p.setAttribute(c,String(f))}),r.appendChild(p)}}}),r}var m=(n,e)=>{let s=document.createElement(n);return e&&(s.className=e),s};var Xe={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var vt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var pn=(n,e)=>{let s=m("button");s.type="button",s.innerHTML=`
8
8
  <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
10
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -12,8 +12,12 @@
12
12
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,s.addEventListener("click",e);let t=o=>{var h,x,R,w,K,T,O,ee,P,Y,fe,J;let i=(h=o.launcher)!=null?h:{},l=s.querySelector("[data-role='launcher-title']");l&&(l.textContent=(x=i.title)!=null?x:"Chat Assistant");let d=s.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(R=i.subtitle)!=null?R:"Get answers fast");let u=s.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let c=s.querySelector("[data-role='launcher-icon']");if(c)if(i.agentIconHidden)c.style.display="none";else{let F=(w=i.agentIconSize)!=null?w:"40px";if(c.style.height=F,c.style.width=F,c.innerHTML="",i.agentIconName){let ne=parseFloat(F)||24,De=le(i.agentIconName,ne*.6,"#ffffff",2);De?(c.appendChild(De),c.style.display=""):(c.textContent=(K=i.agentIconText)!=null?K:"\u{1F4AC}",c.style.display="")}else i.iconUrl?c.style.display="none":(c.textContent=(T=i.agentIconText)!=null?T:"\u{1F4AC}",c.style.display="")}let y=s.querySelector("[data-role='launcher-image']");if(y){let F=(O=i.agentIconSize)!=null?O:"40px";y.style.height=F,y.style.width=F,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let m=s.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let F=(ee=i.callToActionIconSize)!=null?ee:"32px";m.style.height=F,m.style.width=F,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("tvw-bg-cw-primary")):(m.style.backgroundColor="",m.classList.add("tvw-bg-cw-primary"));let ne=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,ne=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display="",m.innerHTML="",i.callToActionIconName){let De=parseFloat(F)||24,oe=Math.max(De-ne,8),$=le(i.callToActionIconName,oe,"currentColor",2);$?m.appendChild($):m.textContent=(P=i.callToActionIconText)!=null?P:"\u2197"}else m.textContent=(Y=i.callToActionIconText)!=null?Y:"\u2197"}let b=i.position&&vt[i.position]?vt[i.position]:vt["bottom-right"],f="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=`${f} ${b}`;let D="1px solid #e5e7eb",j="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";s.style.border=(fe=i.border)!=null?fe:D,s.style.boxShadow=(J=i.shadow)!=null?J:j},r=()=>{s.removeEventListener("click",e),s.remove()};return n&&t(n),{element:s,update:t,destroy:r}};var Dt=n=>{var Y,fe,J,F,ne,De,oe,$,qe,Xe,tt,bt,Ct,q,he,mt,ft,Ve,nt,L,Re,it,at,Tt,wt,$e,st,Ue,U,lt,Ae,Oe;let{config:e,showClose:s=!0}=n,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(Y=e==null?void 0:e.launcher)!=null?Y:{},o=(fe=r.headerIconSize)!=null?fe:"48px",i=(J=r.closeButtonSize)!=null?J:"32px",l=(F=r.closeButtonPlacement)!=null?F:"inline",d=(ne=r.headerIconHidden)!=null?ne:!1,u=r.headerIconName,c=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(c.style.height=o,c.style.width=o,!d)if(u){let Z=parseFloat(o)||24,Te=le(u,Z*.6,"#ffffff",2);Te?c.replaceChildren(Te):c.textContent=(oe=(De=e==null?void 0:e.launcher)==null?void 0:De.agentIconText)!=null?oe:"\u{1F4AC}"}else if(($=e==null?void 0:e.launcher)!=null&&$.iconUrl){let Z=p("img");Z.src=e.launcher.iconUrl,Z.alt="",Z.className="tvw-rounded-xl tvw-object-cover",Z.style.height=o,Z.style.width=o,c.replaceChildren(Z)}else c.textContent=(Xe=(qe=e==null?void 0:e.launcher)==null?void 0:qe.agentIconText)!=null?Xe:"\u{1F4AC}";let y=p("div","tvw-flex tvw-flex-col"),m=p("span","tvw-text-base tvw-font-semibold");m.textContent=(bt=(tt=e==null?void 0:e.launcher)==null?void 0:tt.title)!=null?bt:"Chat Assistant";let b=p("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(q=(Ct=e==null?void 0:e.launcher)==null?void 0:Ct.subtitle)!=null?q:"Here to help you get answers fast",y.append(m,b),d?t.append(y):t.append(c,y);let f=(he=r.clearChat)!=null?he:{},D=(mt=f.enabled)!=null?mt:!0,j=(ft=f.placement)!=null?ft:"inline",h=null,x=null;if(D){let Z=(Ve=f.size)!=null?Ve:"32px",Te=(nt=f.iconName)!=null?nt:"refresh-cw",Ee=(L=f.iconColor)!=null?L:"",ze=(Re=f.backgroundColor)!=null?Re:"",Je=(it=f.borderWidth)!=null?it:"",xt=(at=f.borderColor)!=null?at:"",Bt=(Tt=f.borderRadius)!=null?Tt:"",yt=(wt=f.paddingX)!=null?wt:"",Et=($e=f.paddingY)!=null?$e:"",St=(st=f.tooltipText)!=null?st:"Clear chat",we=(Ue=f.showTooltip)!=null?Ue:!0;x=p("div",j==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),j==="top-right"&&(x.style.right="48px"),h=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),h.style.height=Z,h.style.width=Z,h.type="button",h.setAttribute("aria-label",St);let Ht=le(Te,"20px",Ee||"",2);if(Ht&&h.appendChild(Ht),Ee&&(h.style.color=Ee,h.classList.remove("tvw-text-cw-muted")),ze&&(h.style.backgroundColor=ze,h.classList.remove("hover:tvw-bg-gray-100")),Je||xt){let Be=Je||"0px",Ye=xt||"transparent";h.style.border=`${Be} solid ${Ye}`,h.classList.remove("tvw-border-none")}if(Bt&&(h.style.borderRadius=Bt,h.classList.remove("tvw-rounded-full")),yt?(h.style.paddingLeft=yt,h.style.paddingRight=yt):(h.style.paddingLeft="",h.style.paddingRight=""),Et?(h.style.paddingTop=Et,h.style.paddingBottom=Et):(h.style.paddingTop="",h.style.paddingBottom=""),x.appendChild(h),we&&St&&h&&x){let Be=null,Ye=()=>{if(Be||!h)return;Be=p("div","tvw-clear-chat-tooltip"),Be.textContent=St;let Nt=p("div");Nt.className="tvw-clear-chat-tooltip-arrow",Be.appendChild(Nt);let Wt=h.getBoundingClientRect();Be.style.position="fixed",Be.style.left=`${Wt.left+Wt.width/2}px`,Be.style.top=`${Wt.top-8}px`,Be.style.transform="translate(-50%, -100%)",document.body.appendChild(Be)},At=()=>{Be&&Be.parentNode&&(Be.parentNode.removeChild(Be),Be=null)};x.addEventListener("mouseenter",Ye),x.addEventListener("mouseleave",At),h.addEventListener("focus",Ye),h.addEventListener("blur",At),x._cleanupTooltip=()=>{At(),x&&(x.removeEventListener("mouseenter",Ye),x.removeEventListener("mouseleave",At)),h&&(h.removeEventListener("focus",Ye),h.removeEventListener("blur",At))}}j==="inline"&&t.appendChild(x)}let R=p("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":D&&j==="inline"?"":"tvw-ml-auto"),w=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");w.style.height=i,w.style.width=i,w.type="button";let K=(U=r.closeButtonTooltipText)!=null?U:"Close chat",T=(lt=r.closeButtonShowTooltip)!=null?lt:!0;w.setAttribute("aria-label",K),w.style.display=s?"":"none";let O=(Ae=r.closeButtonIconName)!=null?Ae:"x",ee=(Oe=r.closeButtonIconText)!=null?Oe:"\xD7",P=le(O,"20px",r.closeButtonColor||"",2);if(P?w.appendChild(P):w.textContent=ee,r.closeButtonColor?(w.style.color=r.closeButtonColor,w.classList.remove("tvw-text-cw-muted")):(w.style.color="",w.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(w.style.backgroundColor=r.closeButtonBackgroundColor,w.classList.remove("hover:tvw-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let Z=r.closeButtonBorderWidth||"0px",Te=r.closeButtonBorderColor||"transparent";w.style.border=`${Z} solid ${Te}`,w.classList.remove("tvw-border-none")}else w.style.border="",w.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(w.style.borderRadius=r.closeButtonBorderRadius,w.classList.remove("tvw-rounded-full")):(w.style.borderRadius="",w.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(w.style.paddingLeft=r.closeButtonPaddingX,w.style.paddingRight=r.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),r.closeButtonPaddingY?(w.style.paddingTop=r.closeButtonPaddingY,w.style.paddingBottom=r.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),R.appendChild(w),T&&K){let Z=null,Te=()=>{if(Z)return;Z=p("div","tvw-clear-chat-tooltip"),Z.textContent=K;let ze=p("div");ze.className="tvw-clear-chat-tooltip-arrow",Z.appendChild(ze);let Je=w.getBoundingClientRect();Z.style.position="fixed",Z.style.left=`${Je.left+Je.width/2}px`,Z.style.top=`${Je.top-8}px`,Z.style.transform="translate(-50%, -100%)",document.body.appendChild(Z)},Ee=()=>{Z&&Z.parentNode&&(Z.parentNode.removeChild(Z),Z=null)};R.addEventListener("mouseenter",Te),R.addEventListener("mouseleave",Ee),w.addEventListener("focus",Te),w.addEventListener("blur",Ee),R._cleanupTooltip=()=>{Ee(),R.removeEventListener("mouseenter",Te),R.removeEventListener("mouseleave",Ee),w.removeEventListener("focus",Te),w.removeEventListener("blur",Ee)}}return l!=="top-right"&&t.appendChild(R),{header:t,iconHolder:c,headerTitle:m,headerSubtitle:b,closeButton:w,closeButtonWrapper:R,clearChatButton:h,clearChatButtonWrapper:x}},Qt=(n,e,s)=>{var i,l,d,u;let t=(i=s==null?void 0:s.launcher)!=null?i:{},r=(l=t.closeButtonPlacement)!=null?l:"inline",o=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"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 qn=n=>Dt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Un=n=>{var f,D,j,h;let{config:e,showClose:s=!0,onClose:t}=n,r=(f=e==null?void 0:e.launcher)!=null?f:{},o=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(D=r.title)!=null?D:"Chat Assistant",o.appendChild(i);let l=(j=r.closeButtonSize)!=null?j:"32px",d=p("div",""),u=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");u.style.height=l,u.style.width=l,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=s?"":"none";let c=(h=r.closeButtonIconName)!=null?h:"x",y=le(c,"20px",r.closeButtonColor||"",2);y?u.appendChild(y):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),o.appendChild(d);let m=p("div");m.style.display="none";let b=p("span");return b.style.display="none",{header:o,iconHolder:m,headerTitle:i,headerSubtitle:b,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},zn=n=>{var w,K,T,O,ee,P,Y,fe;let{config:e,showClose:s=!0,onClose:t,onClearChat:r}=n,o=(w=e==null?void 0:e.launcher)!=null?w:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=p("div","tvw-flex tvw-items-center tvw-gap-3"),d=(K=o.headerIconSize)!=null?K:"56px",u=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");u.style.height=d,u.style.width=d;let c=o.headerIconName;if(c){let J=parseFloat(d)||24,F=le(c,J*.5,"#ffffff",2);F?u.replaceChildren(F):u.textContent=(T=o.agentIconText)!=null?T:"\u{1F4AC}"}else if(o.iconUrl){let J=p("img");J.src=o.iconUrl,J.alt="",J.className="tvw-rounded-xl tvw-object-cover",J.style.height=d,J.style.width=d,u.replaceChildren(J)}else u.textContent=(O=o.agentIconText)!=null?O:"\u{1F4AC}";let y=p("div","tvw-flex tvw-flex-col tvw-flex-1"),m=p("span","tvw-text-lg tvw-font-semibold");m.textContent=(ee=o.title)!=null?ee:"Chat Assistant";let b=p("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(P=o.subtitle)!=null?P:"Here to help you get answers fast",y.append(m,b),l.append(u,y);let f=(Y=o.closeButtonSize)!=null?Y:"32px",D=p("div",""),j=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");j.style.height=f,j.style.width=f,j.type="button",j.setAttribute("aria-label","Close chat"),j.style.display=s?"":"none";let h=(fe=o.closeButtonIconName)!=null?fe:"x",x=le(h,"20px",o.closeButtonColor||"",2);x?j.appendChild(x):j.textContent="\xD7",t&&j.addEventListener("click",t),D.appendChild(j),l.appendChild(D),i.appendChild(l);let R=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return R.textContent="Online and ready to help",i.appendChild(R),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:b,closeButton:j,closeButtonWrapper:D,clearChatButton:null,clearChatButtonWrapper:null}},Mn={default:qn,minimal:Un,expanded:zn},Jn=n=>{var e;return(e=Mn[n])!=null?e:Mn.default},Ln=(n,e,s)=>{var i,l,d;if(e!=null&&e.render){let u=e.render({config:n,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat}),c=p("div");c.style.display="none";let y=p("span"),m=p("span"),b=p("button");b.style.display="none";let f=p("div");return f.style.display="none",{header:u,iconHolder:c,headerTitle:y,headerSubtitle:m,closeButton:b,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",o=Jn(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 nr=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 De,oe,$,qe,Xe,tt,bt,Ct,q,he,mt,ft,Ve,nt,L,Re,it,at,Tt,wt,$e,st,Ue,U,lt;let{config:e}=n,s=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((De=e==null?void 0:e.voiceRecognition)==null?void 0:De.enabled)===!0,o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=p("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 u=p("textarea");u.placeholder=($=(oe=e==null?void 0:e.copy)==null?void 0:oe.inputPlaceholder)!=null?$:"Type your message\u2026",u.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",u.rows=1;let c=(Xe=(qe=e==null?void 0:e.theme)==null?void 0:qe.inputFontFamily)!=null?Xe:"sans-serif",y=(bt=(tt=e==null?void 0:e.theme)==null?void 0:tt.inputFontWeight)!=null?bt:"400";u.style.fontFamily=nr(c),u.style.fontWeight=y,u.style.border="none",u.style.outline="none",u.style.borderWidth="0",u.style.borderStyle="none",u.style.borderColor="transparent",u.addEventListener("focus",()=>{u.style.border="none",u.style.outline="none",u.style.borderWidth="0",u.style.borderStyle="none",u.style.borderColor="transparent",u.style.boxShadow="none"}),u.addEventListener("blur",()=>{u.style.border="none",u.style.outline="none"});let m=(Ct=e==null?void 0:e.sendButton)!=null?Ct:{},b=(q=m.useIcon)!=null?q:!1,f=(he=m.iconText)!=null?he:"\u2191",D=m.iconName,j=(mt=m.tooltipText)!=null?mt:"Send message",h=(ft=m.showTooltip)!=null?ft:!1,x=(Ve=m.size)!=null?Ve:"40px",R=m.backgroundColor,w=m.textColor,K=p("div","tvw-send-button-wrapper"),T=p("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(T.type="submit",b){if(T.style.width=x,T.style.height=x,T.style.minWidth=x,T.style.minHeight=x,T.style.fontSize="18px",T.style.lineHeight="1",T.innerHTML="",D){let Ae=parseFloat(x)||24,Oe=w&&typeof w=="string"&&w.trim()?w.trim():"currentColor",Z=le(D,Ae,Oe,2);Z?(T.appendChild(Z),T.style.color=Oe):(T.textContent=f,w?T.style.color=w:T.classList.add("tvw-text-white"))}else T.textContent=f,w?T.style.color=w:T.classList.add("tvw-text-white");R?T.style.backgroundColor=R:T.classList.add("tvw-bg-cw-primary")}else T.textContent=(L=(nt=e==null?void 0:e.copy)==null?void 0:nt.sendButtonLabel)!=null?L:"Send",w?T.style.color=w:T.classList.add("tvw-text-white");if(m.borderWidth&&(T.style.borderWidth=m.borderWidth,T.style.borderStyle="solid"),m.borderColor&&(T.style.borderColor=m.borderColor),m.paddingX?(T.style.paddingLeft=m.paddingX,T.style.paddingRight=m.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),m.paddingY?(T.style.paddingTop=m.paddingY,T.style.paddingBottom=m.paddingY):(T.style.paddingTop="",T.style.paddingBottom=""),h&&j){let Ae=p("div","tvw-send-button-tooltip");Ae.textContent=j,K.appendChild(Ae)}K.appendChild(T);let O=(Re=e==null?void 0:e.voiceRecognition)!=null?Re:{},ee=O.enabled===!0,P=null,Y=null,fe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(ee&&fe){Y=p("div","tvw-send-button-wrapper"),P=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),P.type="button",P.setAttribute("aria-label","Start voice recognition");let Ae=(it=O.iconName)!=null?it:"mic",Oe=(at=O.iconSize)!=null?at:x,Z=parseFloat(Oe)||24,Te=(Tt=O.backgroundColor)!=null?Tt:R,Ee=(wt=O.iconColor)!=null?wt:w;P.style.width=Oe,P.style.height=Oe,P.style.minWidth=Oe,P.style.minHeight=Oe,P.style.fontSize="18px",P.style.lineHeight="1";let ze=Ee||"currentColor",Je=le(Ae,Z,ze,1.5);Je?(P.appendChild(Je),P.style.color=ze):(P.textContent="\u{1F3A4}",P.style.color=ze),Te?P.style.backgroundColor=Te:P.classList.add("tvw-bg-cw-primary"),Ee?P.style.color=Ee:!Ee&&!w&&P.classList.add("tvw-text-white"),O.borderWidth&&(P.style.borderWidth=O.borderWidth,P.style.borderStyle="solid"),O.borderColor&&(P.style.borderColor=O.borderColor),O.paddingX&&(P.style.paddingLeft=O.paddingX,P.style.paddingRight=O.paddingX),O.paddingY&&(P.style.paddingTop=O.paddingY,P.style.paddingBottom=O.paddingY),Y.appendChild(P);let xt=($e=O.tooltipText)!=null?$e:"Start voice recognition";if(((st=O.showTooltip)!=null?st:!1)&&xt){let yt=p("div","tvw-send-button-tooltip");yt.textContent=xt,Y.appendChild(yt)}}d.addEventListener("click",Ae=>{Ae.target!==T&&Ae.target!==K&&Ae.target!==P&&Ae.target!==Y&&u.focus()}),d.append(u),Y&&d.append(Y),d.append(K);let J=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),F=(Ue=e==null?void 0:e.statusIndicator)!=null?Ue:{},ne=(U=F.visible)!=null?U:!0;return J.style.display=ne?"":"none",J.textContent=(lt=F.idleText)!=null?lt:"Online",s.append(t,d,J),{footer:s,suggestions:t,composerForm:d,textarea:u,sendButton:T,sendButtonWrapper:K,micButton:P,micButtonWrapper:Y,statusText:J}};var Ao=n=>{var d,u,c,y,m,b,f;if(!((u=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?u:!0)){let D=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),j=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),h=(y=(c=n==null?void 0:n.launcher)==null?void 0:c.width)!=null?y:"100%";return D.style.width=h,j.style.width="100%",D.appendChild(j),{wrapper:D,panel:j}}let s=(m=n==null?void 0:n.launcher)!=null?m:{},t=s.position&&vt[s.position]?vt[s.position]:vt["bottom-right"],r=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),o=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(f=(b=n==null?void 0:n.launcher)==null?void 0:b.width)!=null?f: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}},To=(n,e=!0)=>{var y,m,b,f,D;let s=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(y=n==null?void 0:n.layout)==null?void 0:y.header,r=t?Ln(n,t,{showClose:e}):Dt({config:n,showClose:e}),o=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");o.id="vanilla-agent-scroll-container";let i=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(m=n==null?void 0:n.copy)==null?void 0:m.welcomeTitle)!=null?b:"Hello \u{1F44B}";let d=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");d.textContent=(D=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",i.append(l,d);let u=p("div","tvw-flex tvw-flex-col tvw-gap-3");o.append(i,u);let c=en({config:n});return Qt(s,r,n),s.append(o,c.footer),{container:s,body:o,messagesWrapper:u,suggestions:c.suggestions,textarea:c.textarea,sendButton:c.sendButton,sendButtonWrapper:c.sendButtonWrapper,micButton:c.micButton,micButtonWrapper:c.micButtonWrapper,composerForm:c.composerForm,statusText:c.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:c.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},sr=(n,e)=>{let s=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=p("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},Eo=(n,e)=>{let s=p("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},or=(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},Yn=(n,e,s)=>{var f,D,j,h,x,R;let t=(f=e.showCopy)!=null?f:!0,r=(D=e.showUpvote)!=null?D:!0,o=(j=e.showDownvote)!=null?j:!0,i=(h=e.visibility)!=null?h:"hover",l=(x=e.align)!=null?x:"right",d=(R=e.layout)!=null?R:"pill-inside",u={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],c={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],y=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${c} ${i==="hover"?"tvw-message-actions-hover":""}`),m=null,b=(w,K,T,O)=>{let ee=document.createElement("button");ee.className="tvw-message-action-btn",ee.setAttribute("aria-label",K),ee.setAttribute("title",K),O&&ee.setAttribute("data-action",O);let P=le(w,14,"currentColor",2);return P&&ee.appendChild(P),ee.addEventListener("click",Y=>{Y.preventDefault(),Y.stopPropagation(),T()}),ee};if(t){let w=b("copy","Copy message",()=>{let K=n.content||"";navigator.clipboard.writeText(K).then(()=>{w.classList.add("tvw-message-action-success");let T=le("check",14,"currentColor",2);T&&(w.innerHTML="",w.appendChild(T)),setTimeout(()=>{w.classList.remove("tvw-message-action-success");let O=le("copy",14,"currentColor",2);O&&(w.innerHTML="",w.appendChild(O))},2e3)}).catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",T)}),s!=null&&s.onCopy&&s.onCopy(n),e.onCopy&&e.onCopy(n)},"copy");y.appendChild(w)}if(r){let w=b("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,w.classList.remove("tvw-message-action-active");else{let T=y.querySelector('[data-action="downvote"]');T&&T.classList.remove("tvw-message-action-active"),m="upvote",w.classList.add("tvw-message-action-active");let O={type:"upvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(O),e.onFeedback&&e.onFeedback(O)}},"upvote");y.appendChild(w)}if(o){let w=b("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,w.classList.remove("tvw-message-action-active");else{let T=y.querySelector('[data-action="upvote"]');T&&T.classList.remove("tvw-message-action-active"),m="downvote",w.classList.add("tvw-message-action-active");let O={type:"downvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(O),e.onFeedback&&e.onFeedback(O)}},"downvote");y.appendChild(w)}return y},tn=(n,e,s,t,r)=>{var R,w,K,T,O;let o=s!=null?s:{},i=(R=o.layout)!=null?R:"bubble",l=o.avatar,d=o.timestamp,u=(w=l==null?void 0:l.show)!=null?w:!1,c=(K=d==null?void 0:d.show)!=null?K:!1,y=(T=l==null?void 0:l.position)!=null?T:"left",m=(O=d==null?void 0:d.position)!=null?O:"below",b=or(n.role,i),f=p("div",b.join(" ")),D=document.createElement("div");if(D.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),c&&m==="inline"&&n.createdAt){let ee=Eo(n,d);ee.classList.add("tvw-ml-2","tvw-inline"),D.appendChild(ee)}if(f.appendChild(D),c&&m==="below"&&n.createdAt){let ee=Eo(n,d);ee.classList.add("tvw-mt-1"),f.appendChild(ee)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let ee=un();f.appendChild(ee)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let ee=Yn(n,t,r);f.appendChild(ee)}if(!u||n.role==="system")return f;let h=p("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),x=sr(l,n.role);return y==="right"||y==="left"&&n.role==="user"?h.append(f,x):h.append(x,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),h},Wo=(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 Kn=new Set,Xn=n=>{let e=n.reasoning,s=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return s;let t=Kn.has(n.id),r=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false");let o=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",o.appendChild(i);let l=p("span","tvw-text-xs tvw-text-cw-primary");l.textContent=Co(e),o.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),c=le(t?"chevron-up":"chevron-down",16,"currentColor",2);c?d.appendChild(c):d.textContent=t?"Hide":"Show";let y=p("div","tvw-flex tvw-items-center tvw-ml-auto");y.append(d),r.append(o,y);let m=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let b=e.chunks.join(""),f=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");f.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(f);let D=()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let x=le(t?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"},j=()=>{t=!t,t?Kn.add(n.id):Kn.delete(n.id),D()};return r.addEventListener("pointerdown",h=>{h.preventDefault(),j()}),r.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),j())}),D(),s.append(r,m),s};var Vn=new Set,Gn=(n,e)=>{var j;let s=n.toolCall,t=(j=e==null?void 0:e.toolCall)!=null?j:{},r=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(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=Vn.has(n.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",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=p("div","tvw-flex tvw-flex-col tvw-text-left"),d=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=xo(s),l.appendChild(d);let u=p("div","tvw-flex tvw-items-center"),c=t.toggleTextColor||t.headerTextColor||"currentColor",y=le(o?"chevron-up":"chevron-down",16,c,2);y?u.appendChild(y):u.textContent=o?"Hide":"Show";let m=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(l,m);let b=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=o?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),s.name){let h=p("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,b.appendChild(h)}if(s.args!==void 0){let h=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Arguments";let R=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(R.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(R.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(R.style.color=t.codeBlockTextColor),R.textContent=jn(s.args),h.append(x,R),b.appendChild(h)}if(s.chunks&&s.chunks.length){let h=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Activity";let R=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(R.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(R.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(R.style.color=t.codeBlockTextColor),R.textContent=s.chunks.join(`
16
- `),h.append(x,R),b.appendChild(h)}if(s.status==="complete"&&s.result!==void 0){let h=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Result";let R=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(R.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(R.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(R.style.color=t.codeBlockTextColor),R.textContent=jn(s.result),h.append(x,R),b.appendChild(h)}if(s.status==="complete"&&typeof s.duration=="number"){let h=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(h.style.color=t.contentTextColor),h.textContent=`Duration: ${s.duration}ms`,b.appendChild(h)}let f=()=>{i.setAttribute("aria-expanded",o?"true":"false"),u.innerHTML="";let h=t.toggleTextColor||t.headerTextColor||"currentColor",x=le(o?"chevron-up":"chevron-down",16,h,2);x?u.appendChild(x):u.textContent=o?"Hide":"Show",b.style.display=o?"":"none"},D=()=>{o=!o,o?Vn.add(n.id):Vn.delete(n.id),f()};return i.addEventListener("pointerdown",h=>{h.preventDefault(),D()}),i.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),D())}),f(),r.append(i,b),r};var Mo=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(b=>b.role==="user"))return;let c=document.createDocumentFragment(),y=r?r.isStreaming():!1,m=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let f=p("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");f.type="button",f.textContent=b,f.disabled=y,l!=null&&l.fontFamily&&(f.style.fontFamily=m(l.fontFamily)),l!=null&&l.fontWeight&&(f.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(f.style.paddingLeft=l.paddingX,f.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(f.style.paddingTop=l.paddingY,f.style.paddingBottom=l.paddingY),f.addEventListener("click",()=>{!r||r.isStreaming()||(o.value="",r.sendMessage(b))}),c.appendChild(f),e.push(f)}),n.appendChild(c)}}};var Lo={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"}},Zn=(n,e,s,t)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(o=>{var f,D,j;if(o.dataset.enhanced==="true")return;let i=(f=o.dataset.tvForm)!=null?f:"init";o.dataset.enhanced="true";let l=(D=Lo[i])!=null?D:Lo.init;o.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),u=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=l.title,d.appendChild(u),l.description){let h=p("p","tvw-text-sm tvw-text-cw-muted");h.textContent=l.description,d.appendChild(h)}let c=document.createElement("form");c.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(h=>{var T,O;let x=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");x.htmlFor=`${e.id}-${i}-${h.name}`;let R=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");R.textContent=h.label,x.appendChild(R);let w=(T=h.type)!=null?T:"text",K;w==="textarea"?(K=document.createElement("textarea"),K.rows=3):(K=document.createElement("input"),K.type=w),K.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",K.id=`${e.id}-${i}-${h.name}`,K.name=h.name,K.placeholder=(O=h.placeholder)!=null?O:"",h.required&&(K.required=!0),x.appendChild(K),c.appendChild(x)});let y=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(j=l.submitLabel)!=null?j:"Submit",y.appendChild(m),y.appendChild(b),c.appendChild(y),o.replaceChildren(d,c),c.addEventListener("submit",async h=>{var K,T;h.preventDefault();let x=(K=s.formEndpoint)!=null?K:"/form",R=new FormData(c),w={};R.forEach((O,ee)=>{w[ee]=O}),w.type=i,b.disabled=!0,m.textContent="Submitting\u2026";try{let O=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!O.ok)throw new Error(`Form submission failed (${O.status})`);let ee=await O.json();m.textContent=(T=ee.message)!=null?T:"Thanks! We'll be in touch soon.",ee.success&&ee.nextPrompt&&await t.sendMessage(String(ee.nextPrompt))}catch(O){m.textContent=O instanceof Error?O.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var Qn=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()}},gn=new Qn;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 kn(n){var e,s,t,r,o,i,l,d,u,c,y,m,b,f,D,j,h,x,R;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:{...(u=(d=ke.layout)==null?void 0:d.messages)==null?void 0:u.avatar,...(y=(c=n.layout)==null?void 0:c.messages)==null?void 0:y.avatar},timestamp:{...(b=(m=ke.layout)==null?void 0:m.messages)==null?void 0:b.timestamp,...(D=(f=n.layout)==null?void 0:f.messages)==null?void 0:D.timestamp}},slots:{...(j=ke.layout)==null?void 0:j.slots,...(h=n.layout)==null?void 0:h.slots}},markdown:{...ke.markdown,...n.markdown,options:{...(x=ke.markdown)==null?void 0:x.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...ke.messageActions,...n.messageActions}}:ke}var ko=()=>{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 rr=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},ir=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},hn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=rr(n),s=ir(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}},es=n=>typeof n=="string"?n:n==null?"":String(n),Kt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:es(n.payload.text)},messageAndClick:(n,e)=>{var r;if(n.type!=="message_and_click")return;let s=n.payload,t=es(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:es(s.text)}}},Bo=n=>Array.isArray(n)?n.map(e=>String(e)):[],mn=n=>{let e=new Set(Bo(n.getMetadata().processedActionMessageIds)),s=()=>{e=new Set(Bo(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((u,c)=>u||(c==null?void 0:c({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 u of n.handlers)if(u)try{let c=u(l,{message:o.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!c)continue;if(c.handled){let y=c.persistMessage!==!1;return{text:c.displayText!==void 0?c.displayText:"",persist:y}}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:s}};var ar=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}},lr=n=>n.map(e=>({...e,streaming:!1})),Bn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let s=e();return s?ar(s.getItem(n)):null},save:s=>{let t=e();if(t)try{let r={...s,messages:s.messages?lr(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 ts=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 ts;var sn=require("partial-json");function dr(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function cr(n,e){if(!dr(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 Hn(){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=cr(r,s);o&&(n=o)}catch{}return e=s.length,n},reset:()=>{n=null,e=0}}}function Ho(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Rn(n,e){let{config: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 Ro(){let n=Hn();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function In(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Pn(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 on="vanilla-agent-chat-history",pr=30*1e3,ns=n=>!n||typeof n!="object"?{}:{...n},Io=n=>n.map(e=>({...e,streaming:!1})),Po=(n,e)=>{let s=n!=null&&n.markdown?cn(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 u=e.process({text:r,raw:o!=null?o:r,message:t.message,streaming:t.streaming});u!==null&&(r=u.text,u.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):Cn(r)}},$n=(n,e,s)=>{var ce,Ie,pe,Fe,rt,ht,rs,is,as,ls,ds,cs,ps,us;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=kn(e),r=gn.getForInstance(t.plugins);t.components&&nn.registerAll(t.components);let o=ko(),i=(ce=t.storageAdapter)!=null?ce:Bn(),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 g=a;g.metadata&&(l=ns(g.metadata)),(Ie=g.messages)!=null&&Ie.length&&(t={...t,initialMessages:g.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let u=()=>l,c=a=>{var W;l=(W=a({...l}))!=null?W:{},Wt()},y=t.actionParsers&&t.actionParsers.length?t.actionParsers:[hn],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick],b=mn({parsers:y,handlers:m,getMetadata:u,updateMetadata:c,emit:o.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let f=(Fe=(pe=t.launcher)==null?void 0:pe.enabled)!=null?Fe:!0,D=(ht=(rt=t.launcher)==null?void 0:rt.autoExpand)!=null?ht:!1,j=D,h=f,x=f?D:!0,R=Po(t,b),w=(is=(rs=t.features)==null?void 0:rs.showReasoning)!=null?is:!0,K=(ls=(as=t.features)==null?void 0:as.showToolCalls)!=null?ls:!0,T={onCopy:a=>{o.emit("message:copy",a)},onFeedback:a=>{o.emit("message:feedback",a)}},O=(ds=t.statusIndicator)!=null?ds:{},ee=a=>{var g,W,N,I;return a==="idle"?(g=O.idleText)!=null?g:Ke.idle:a==="connecting"?(W=O.connectingText)!=null?W:Ke.connecting:a==="connected"?(N=O.connectedText)!=null?N:Ke.connected:a==="error"?(I=O.errorText)!=null?I:Ke.error:Ke[a]},{wrapper:P,panel:Y}=Ao(t),fe=To(t,f),{container:J,body:F,messagesWrapper:ne,suggestions:De,textarea:oe,sendButton:$,sendButtonWrapper:qe,composerForm:Xe,statusText:tt,introTitle:bt,introSubtitle:Ct,closeButton:q,iconHolder:he,headerTitle:mt,headerSubtitle:ft,header:Ve,footer:nt}=fe,L=fe.micButton,Re=fe.micButtonWrapper,it=r.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let g=Dt({config:t,showClose:f});return Qt(J,g,t),g.header},onClose:()=>ot(!1,"user")});if(a){let g=J.querySelector(".tvw-border-b-cw-divider");g&&(g.replaceWith(a),Ve=a)}}let at=r.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>en({config:t}).footer,onSubmit:g=>{U&&!U.isStreaming()&&U.sendMessage(g)},disabled:!1});a&&(nt.replaceWith(a),nt=a)}(()=>{var N,I;let a=(I=(N=t.layout)==null?void 0:N.slots)!=null?I:{},g=re=>{switch(re){case"body-top":return J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return ne;case"footer-top":return De;case"composer":return Xe;case"footer-bottom":return tt;default:return null}},W=(re,H)=>{var C;switch(re){case"header-left":case"header-center":case"header-right":if(re==="header-left")Ve.insertBefore(H,Ve.firstChild);else if(re==="header-right")Ve.appendChild(H);else{let _=Ve.querySelector(".tvw-flex-col");_?(C=_.parentNode)==null||C.insertBefore(H,_.nextSibling):Ve.appendChild(H)}break;case"body-top":let G=F.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(H):F.insertBefore(H,F.firstChild);break;case"body-bottom":F.appendChild(H);break;case"footer-top":De.replaceWith(H);break;case"footer-bottom":tt.replaceWith(H);break;default:break}};for(let[re,H]of Object.entries(a))if(H)try{let C=H({config:t,defaultContent:()=>g(re)});C&&W(re,C)}catch(C){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${re}":`,C)}})(),Y.appendChild(J),n.appendChild(P);let wt=()=>{var ie,Pe,dt,ae,ct,Rt,It,Lt,Ut,Pt,zt,pt,$t,Ot,vn,ln;let a=(Pe=(ie=t.launcher)==null?void 0:ie.sidebarMode)!=null?Pe:!1,g=a||((ae=(dt=t.launcher)==null?void 0:dt.fullHeight)!=null?ae:!1),W=(ct=t.theme)!=null?ct:{},N=(It=(Rt=t.launcher)==null?void 0:Rt.position)!=null?It:"bottom-left",I=N==="bottom-left"||N==="top-left",re=a?"none":"1px solid var(--tvw-cw-border)",H=a?I?"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)",C=a?"0":"16px",G=(Lt=W.panelBorder)!=null?Lt:re,_=(Ut=W.panelShadow)!=null?Ut:H,k=(Pt=W.panelBorderRadius)!=null?Pt:C;n.style.cssText="",P.style.cssText="",Y.style.cssText="",J.style.cssText="",F.style.cssText="",nt.style.cssText="";let z=(pt=(zt=t==null?void 0:t.launcher)==null?void 0:zt.width)!=null?pt:t==null?void 0:t.launcherWidth,He=z!=null?z:"min(400px, calc(100vw - 24px))";a||(Y.style.width=He,Y.style.maxWidth=He),Y.style.boxShadow=_,Y.style.borderRadius=k,J.style.border=G,J.style.borderRadius=k;let ue=(($t=t.launcher)==null?void 0:$t.enabled)===!1;if(g&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1 1 0%",P.style.minHeight="0",P.style.maxHeight="100%",P.style.height="100%",ue&&(P.style.overflow="hidden"),Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.height="100%",Y.style.overflow="hidden",J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.overflow="hidden",F.style.flex="1 1 0%",F.style.minHeight="0",F.style.overflowY="auto",nt.style.flexShrink="0"),P.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&&!ue&&((Ot=vt[N])!=null?Ot:vt["bottom-right"]).split(" ").forEach(Vt=>P.classList.add(Vt)),a){let Jt=(ln=(vn=t.launcher)==null?void 0:vn.sidebarWidth)!=null?ln:"420px";P.style.cssText=`
15
+ `,s.addEventListener("click",e);let t=o=>{var h,b,W,v,D,x,S,X,B,_,Z,j;let a=(h=o.launcher)!=null?h:{},l=s.querySelector("[data-role='launcher-title']");l&&(l.textContent=(b=a.title)!=null?b:"Chat Assistant");let p=s.querySelector("[data-role='launcher-subtitle']");p&&(p.textContent=(W=a.subtitle)!=null?W:"Get answers fast");let c=s.querySelector(".tvw-flex-col");c&&(a.textHidden?c.style.display="none":c.style.display="");let f=s.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let K=(v=a.agentIconSize)!=null?v:"40px";if(f.style.height=K,f.style.width=K,f.innerHTML="",a.agentIconName){let Q=parseFloat(K)||24,ne=ce(a.agentIconName,Q*.6,"#ffffff",2);ne?(f.appendChild(ne),f.style.display=""):(f.textContent=(D=a.agentIconText)!=null?D:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",f.style.display="")}let w=s.querySelector("[data-role='launcher-image']");if(w){let K=(S=a.agentIconSize)!=null?S:"40px";w.style.height=K,w.style.width=K,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let d=s.querySelector("[data-role='launcher-call-to-action-icon']");if(d){let K=(X=a.callToActionIconSize)!=null?X:"32px";d.style.height=K,d.style.width=K,a.callToActionIconBackgroundColor?(d.style.backgroundColor=a.callToActionIconBackgroundColor,d.classList.remove("tvw-bg-cw-primary")):(d.style.backgroundColor="",d.classList.add("tvw-bg-cw-primary"));let Q=0;if(a.callToActionIconPadding?(d.style.boxSizing="border-box",d.style.padding=a.callToActionIconPadding,Q=(parseFloat(a.callToActionIconPadding)||0)*2):(d.style.boxSizing="",d.style.padding=""),a.callToActionIconHidden)d.style.display="none";else if(d.style.display="",d.innerHTML="",a.callToActionIconName){let ne=parseFloat(K)||24,re=Math.max(ne-Q,8),q=ce(a.callToActionIconName,re,"currentColor",2);q?d.appendChild(q):d.textContent=(B=a.callToActionIconText)!=null?B:"\u2197"}else d.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}let C=a.position&&vt[a.position]?vt[a.position]:vt["bottom-right"],g="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";s.className=`${g} ${C}`;let U="1px solid #e5e7eb",$="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";s.style.border=(Z=a.border)!=null?Z:U,s.style.boxShadow=(j=a.shadow)!=null?j:$},r=()=>{s.removeEventListener("click",e),s.remove()};return n&&t(n),{element:s,update:t,destroy:r}};var Ot=n=>{var _,Z,j,K,Q,ne,re,q,qe,Ve,nt,bt,Ct,J,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,$e,ot,Ue,I,dt,Se,Oe;let{config:e,showClose:s=!0}=n,t=m("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(_=e==null?void 0:e.launcher)!=null?_:{},o=(Z=r.headerIconSize)!=null?Z:"48px",a=(j=r.closeButtonSize)!=null?j:"32px",l=(K=r.closeButtonPlacement)!=null?K:"inline",p=(Q=r.headerIconHidden)!=null?Q:!1,c=r.headerIconName,f=m("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=o,f.style.width=o,!p)if(c){let te=parseFloat(o)||24,Ae=ce(c,te*.6,"#ffffff",2);Ae?f.replaceChildren(Ae):f.textContent=(re=(ne=e==null?void 0:e.launcher)==null?void 0:ne.agentIconText)!=null?re:"\u{1F4AC}"}else if((q=e==null?void 0:e.launcher)!=null&&q.iconUrl){let te=m("img");te.src=e.launcher.iconUrl,te.alt="",te.className="tvw-rounded-xl tvw-object-cover",te.style.height=o,te.style.width=o,f.replaceChildren(te)}else f.textContent=(Ve=(qe=e==null?void 0:e.launcher)==null?void 0:qe.agentIconText)!=null?Ve:"\u{1F4AC}";let w=m("div","tvw-flex tvw-flex-col"),d=m("span","tvw-text-base tvw-font-semibold");d.textContent=(bt=(nt=e==null?void 0:e.launcher)==null?void 0:nt.title)!=null?bt:"Chat Assistant";let C=m("span","tvw-text-xs tvw-text-cw-muted");C.textContent=(J=(Ct=e==null?void 0:e.launcher)==null?void 0:Ct.subtitle)!=null?J:"Here to help you get answers fast",w.append(d,C),p?t.append(w):t.append(f,w);let g=(fe=r.clearChat)!=null?fe:{},U=(mt=g.enabled)!=null?mt:!0,$=(ft=g.placement)!=null?ft:"inline",h=null,b=null;if(U){let te=(Ge=g.size)!=null?Ge:"32px",Ae=(st=g.iconName)!=null?st:"refresh-cw",Te=(H=g.iconColor)!=null?H:"",ze=(He=g.backgroundColor)!=null?He:"",Je=(at=g.borderWidth)!=null?at:"",xt=(lt=g.borderColor)!=null?lt:"",Bt=(Tt=g.borderRadius)!=null?Tt:"",yt=(wt=g.paddingX)!=null?wt:"",Et=($e=g.paddingY)!=null?$e:"",St=(ot=g.tooltipText)!=null?ot:"Clear chat",ye=(Ue=g.showTooltip)!=null?Ue:!0;b=m("div",$==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),$==="top-right"&&(b.style.right="48px"),h=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),h.style.height=te,h.style.width=te,h.type="button",h.setAttribute("aria-label",St);let Ht=ce(Ae,"20px",Te||"",2);if(Ht&&h.appendChild(Ht),Te&&(h.style.color=Te,h.classList.remove("tvw-text-cw-muted")),ze&&(h.style.backgroundColor=ze,h.classList.remove("hover:tvw-bg-gray-100")),Je||xt){let Le=Je||"0px",Ye=xt||"transparent";h.style.border=`${Le} solid ${Ye}`,h.classList.remove("tvw-border-none")}if(Bt&&(h.style.borderRadius=Bt,h.classList.remove("tvw-rounded-full")),yt?(h.style.paddingLeft=yt,h.style.paddingRight=yt):(h.style.paddingLeft="",h.style.paddingRight=""),Et?(h.style.paddingTop=Et,h.style.paddingBottom=Et):(h.style.paddingTop="",h.style.paddingBottom=""),b.appendChild(h),ye&&St&&h&&b){let Le=null,Ye=()=>{if(Le||!h)return;Le=m("div","tvw-clear-chat-tooltip"),Le.textContent=St;let Dt=m("div");Dt.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(Dt);let Mt=h.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Mt.left+Mt.width/2}px`,Le.style.top=`${Mt.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},At=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};b.addEventListener("mouseenter",Ye),b.addEventListener("mouseleave",At),h.addEventListener("focus",Ye),h.addEventListener("blur",At),b._cleanupTooltip=()=>{At(),b&&(b.removeEventListener("mouseenter",Ye),b.removeEventListener("mouseleave",At)),h&&(h.removeEventListener("focus",Ye),h.removeEventListener("blur",At))}}$==="inline"&&t.appendChild(b)}let W=m("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":U&&$==="inline"?"":"tvw-ml-auto"),v=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=a,v.style.width=a,v.type="button";let D=(I=r.closeButtonTooltipText)!=null?I:"Close chat",x=(dt=r.closeButtonShowTooltip)!=null?dt:!0;v.setAttribute("aria-label",D),v.style.display=s?"":"none";let S=(Se=r.closeButtonIconName)!=null?Se:"x",X=(Oe=r.closeButtonIconText)!=null?Oe:"\xD7",B=ce(S,"20px",r.closeButtonColor||"",2);if(B?v.appendChild(B):v.textContent=X,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let te=r.closeButtonBorderWidth||"0px",Ae=r.closeButtonBorderColor||"transparent";v.style.border=`${te} solid ${Ae}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),W.appendChild(v),x&&D){let te=null,Ae=()=>{if(te)return;te=m("div","tvw-clear-chat-tooltip"),te.textContent=D;let ze=m("div");ze.className="tvw-clear-chat-tooltip-arrow",te.appendChild(ze);let Je=v.getBoundingClientRect();te.style.position="fixed",te.style.left=`${Je.left+Je.width/2}px`,te.style.top=`${Je.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Te=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};W.addEventListener("mouseenter",Ae),W.addEventListener("mouseleave",Te),v.addEventListener("focus",Ae),v.addEventListener("blur",Te),W._cleanupTooltip=()=>{Te(),W.removeEventListener("mouseenter",Ae),W.removeEventListener("mouseleave",Te),v.removeEventListener("focus",Ae),v.removeEventListener("blur",Te)}}return l!=="top-right"&&t.appendChild(W),{header:t,iconHolder:f,headerTitle:d,headerSubtitle:C,closeButton:v,closeButtonWrapper:W,clearChatButton:h,clearChatButtonWrapper:b}},Qt=(n,e,s)=>{var a,l,p,c;let t=(a=s==null?void 0:s.launcher)!=null?a:{},r=(l=t.closeButtonPlacement)!=null?l:"inline",o=(c=(p=t.clearChat)==null?void 0:p.placement)!=null?c:"inline";n.appendChild(e.header),r==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&o==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var Kn=n=>Ot({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Xn=n=>{var g,U,$,h;let{config:e,showClose:s=!0,onClose:t}=n,r=(g=e==null?void 0:e.launcher)!=null?g:{},o=m("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),a=m("span","tvw-text-base tvw-font-semibold");a.textContent=(U=r.title)!=null?U:"Chat Assistant",o.appendChild(a);let l=($=r.closeButtonSize)!=null?$:"32px",p=m("div",""),c=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=l,c.style.width=l,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=s?"":"none";let f=(h=r.closeButtonIconName)!=null?h:"x",w=ce(f,"20px",r.closeButtonColor||"",2);w?c.appendChild(w):c.textContent="\xD7",t&&c.addEventListener("click",t),p.appendChild(c),o.appendChild(p);let d=m("div");d.style.display="none";let C=m("span");return C.style.display="none",{header:o,iconHolder:d,headerTitle:a,headerSubtitle:C,closeButton:c,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},Vn=n=>{var v,D,x,S,X,B,_,Z;let{config:e,showClose:s=!0,onClose:t,onClearChat:r}=n,o=(v=e==null?void 0:e.launcher)!=null?v:{},a=m("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=m("div","tvw-flex tvw-items-center tvw-gap-3"),p=(D=o.headerIconSize)!=null?D:"56px",c=m("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=p,c.style.width=p;let f=o.headerIconName;if(f){let j=parseFloat(p)||24,K=ce(f,j*.5,"#ffffff",2);K?c.replaceChildren(K):c.textContent=(x=o.agentIconText)!=null?x:"\u{1F4AC}"}else if(o.iconUrl){let j=m("img");j.src=o.iconUrl,j.alt="",j.className="tvw-rounded-xl tvw-object-cover",j.style.height=p,j.style.width=p,c.replaceChildren(j)}else c.textContent=(S=o.agentIconText)!=null?S:"\u{1F4AC}";let w=m("div","tvw-flex tvw-flex-col tvw-flex-1"),d=m("span","tvw-text-lg tvw-font-semibold");d.textContent=(X=o.title)!=null?X:"Chat Assistant";let C=m("span","tvw-text-sm tvw-text-cw-muted");C.textContent=(B=o.subtitle)!=null?B:"Here to help you get answers fast",w.append(d,C),l.append(c,w);let g=(_=o.closeButtonSize)!=null?_:"32px",U=m("div",""),$=m("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");$.style.height=g,$.style.width=g,$.type="button",$.setAttribute("aria-label","Close chat"),$.style.display=s?"":"none";let h=(Z=o.closeButtonIconName)!=null?Z:"x",b=ce(h,"20px",o.closeButtonColor||"",2);b?$.appendChild(b):$.textContent="\xD7",t&&$.addEventListener("click",t),U.appendChild($),l.appendChild(U),a.appendChild(l);let W=m("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return W.textContent="Online and ready to help",a.appendChild(W),{header:a,iconHolder:c,headerTitle:d,headerSubtitle:C,closeButton:$,closeButtonWrapper:U,clearChatButton:null,clearChatButtonWrapper:null}},Bn={default:Kn,minimal:Xn,expanded:Vn},Gn=n=>{var e;return(e=Bn[n])!=null?e:Bn.default},Hn=(n,e,s)=>{var a,l,p;if(e!=null&&e.render){let c=e.render({config:n,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat}),f=m("div");f.style.display="none";let w=m("span"),d=m("span"),C=m("button");C.style.display="none";let g=m("div");return g.style.display="none",{header:c,iconHolder:f,headerTitle:w,headerSubtitle:d,closeButton:C,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let t=(a=e==null?void 0:e.layout)!=null?a:"default",o=Gn(t)({config:n,showClose:(p=(l=e==null?void 0:e.showCloseButton)!=null?l:s==null?void 0:s.showClose)!=null?p:!0,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat});return e&&(e.showIcon===!1&&(o.iconHolder.style.display="none"),e.showTitle===!1&&(o.headerTitle.style.display="none"),e.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(o.closeButton.style.display="none"),e.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var ar=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},en=n=>{var ne,re,q,qe,Ve,nt,bt,Ct,J,fe,mt,ft,Ge,st,H,He,at,lt,Tt,wt,$e,ot,Ue,I,dt;let{config:e}=n,s=m("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=m("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((ne=e==null?void 0:e.voiceRecognition)==null?void 0:ne.enabled)===!0,o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),p=m("form",`tvw-widget-composer tvw-flex tvw-items-end ${r&&o?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);p.style.outline="none";let c=m("textarea");c.placeholder=(q=(re=e==null?void 0:e.copy)==null?void 0:re.inputPlaceholder)!=null?q:"Type your message\u2026",c.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",c.rows=1;let f=(Ve=(qe=e==null?void 0:e.theme)==null?void 0:qe.inputFontFamily)!=null?Ve:"sans-serif",w=(bt=(nt=e==null?void 0:e.theme)==null?void 0:nt.inputFontWeight)!=null?bt:"400";c.style.fontFamily=ar(f),c.style.fontWeight=w,c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.addEventListener("focus",()=>{c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.style.boxShadow="none"}),c.addEventListener("blur",()=>{c.style.border="none",c.style.outline="none"});let d=(Ct=e==null?void 0:e.sendButton)!=null?Ct:{},C=(J=d.useIcon)!=null?J:!1,g=(fe=d.iconText)!=null?fe:"\u2191",U=d.iconName,$=(mt=d.tooltipText)!=null?mt:"Send message",h=(ft=d.showTooltip)!=null?ft:!1,b=(Ge=d.size)!=null?Ge:"40px",W=d.backgroundColor,v=d.textColor,D=m("div","tvw-send-button-wrapper"),x=m("button",C?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(x.type="submit",C){if(x.style.width=b,x.style.height=b,x.style.minWidth=b,x.style.minHeight=b,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",U){let Se=parseFloat(b)||24,Oe=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",te=ce(U,Se,Oe,2);te?(x.appendChild(te),x.style.color=Oe):(x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white"))}else x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white");W?x.style.backgroundColor=W:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(H=(st=e==null?void 0:e.copy)==null?void 0:st.sendButtonLabel)!=null?H:"Send",v?x.style.color=v:x.classList.add("tvw-text-white");if(d.borderWidth&&(x.style.borderWidth=d.borderWidth,x.style.borderStyle="solid"),d.borderColor&&(x.style.borderColor=d.borderColor),d.paddingX?(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),d.paddingY?(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),h&&$){let Se=m("div","tvw-send-button-tooltip");Se.textContent=$,D.appendChild(Se)}D.appendChild(x);let S=(He=e==null?void 0:e.voiceRecognition)!=null?He:{},X=S.enabled===!0,B=null,_=null,Z=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(X&&Z){_=m("div","tvw-send-button-wrapper"),B=m("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),B.type="button",B.setAttribute("aria-label","Start voice recognition");let Se=(at=S.iconName)!=null?at:"mic",Oe=(lt=S.iconSize)!=null?lt:b,te=parseFloat(Oe)||24,Ae=(Tt=S.backgroundColor)!=null?Tt:W,Te=(wt=S.iconColor)!=null?wt:v;B.style.width=Oe,B.style.height=Oe,B.style.minWidth=Oe,B.style.minHeight=Oe,B.style.fontSize="18px",B.style.lineHeight="1";let ze=Te||"currentColor",Je=ce(Se,te,ze,1.5);Je?(B.appendChild(Je),B.style.color=ze):(B.textContent="\u{1F3A4}",B.style.color=ze),Ae?B.style.backgroundColor=Ae:B.classList.add("tvw-bg-cw-primary"),Te?B.style.color=Te:!Te&&!v&&B.classList.add("tvw-text-white"),S.borderWidth&&(B.style.borderWidth=S.borderWidth,B.style.borderStyle="solid"),S.borderColor&&(B.style.borderColor=S.borderColor),S.paddingX&&(B.style.paddingLeft=S.paddingX,B.style.paddingRight=S.paddingX),S.paddingY&&(B.style.paddingTop=S.paddingY,B.style.paddingBottom=S.paddingY),_.appendChild(B);let xt=($e=S.tooltipText)!=null?$e:"Start voice recognition";if(((ot=S.showTooltip)!=null?ot:!1)&&xt){let yt=m("div","tvw-send-button-tooltip");yt.textContent=xt,_.appendChild(yt)}}p.addEventListener("click",Se=>{Se.target!==x&&Se.target!==D&&Se.target!==B&&Se.target!==_&&c.focus()}),p.append(c),_&&p.append(_),p.append(D);let j=m("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),K=(Ue=e==null?void 0:e.statusIndicator)!=null?Ue:{},Q=(I=K.visible)!=null?I:!0;return j.style.display=Q?"":"none",j.textContent=(dt=K.idleText)!=null?dt:"Online",s.append(t,p,j),{footer:s,suggestions:t,composerForm:p,textarea:c,sendButton:x,sendButtonWrapper:D,micButton:B,micButtonWrapper:_,statusText:j}};var Lo=n=>{var p,c,f,w,d,C,g;if(!((c=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)!=null?c:!0)){let U=m("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),$=m("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),h=(w=(f=n==null?void 0:n.launcher)==null?void 0:f.width)!=null?w:"100%";return U.style.width=h,$.style.width="100%",U.appendChild($),{wrapper:U,panel:$}}let s=(d=n==null?void 0:n.launcher)!=null?d:{},t=s.position&&vt[s.position]?vt[s.position]:vt["bottom-right"],r=m("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),o=m("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),a=(g=(C=n==null?void 0:n.launcher)==null?void 0:C.width)!=null?g:n==null?void 0:n.launcherWidth,l=a!=null?a:"min(400px, calc(100vw - 24px))";return o.style.width=l,o.style.maxWidth=l,r.appendChild(o),{wrapper:r,panel:o}},Bo=(n,e=!0)=>{var w,d,C,g,U;let s=m("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=n==null?void 0:n.layout)==null?void 0:w.header,r=t?Hn(n,t,{showClose:e}):Ot({config:n,showClose:e}),o=m("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");o.id="vanilla-agent-scroll-container";let a=m("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=m("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(C=(d=n==null?void 0:n.copy)==null?void 0:d.welcomeTitle)!=null?C:"Hello \u{1F44B}";let p=m("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");p.textContent=(U=(g=n==null?void 0:n.copy)==null?void 0:g.welcomeSubtitle)!=null?U:"Ask anything about your account or products.",a.append(l,p);let c=m("div","tvw-flex tvw-flex-col tvw-gap-3");o.append(a,c);let f=en({config:n});return Qt(s,r,n),s.append(o,f.footer),{container:s,body:o,messagesWrapper:c,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:f.footer}};var gn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let s=document.createElement("div");s.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",s.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(e),n.appendChild(s),n.appendChild(t),n.appendChild(r),n},lr=(n,e)=>{let s=m("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=m("img");r.src=t,r.alt=e==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",s.appendChild(r)}else s.textContent=t,s.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else s.textContent=e==="user"?"U":"A",s.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return s},Ho=(n,e)=>{let s=m("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?s.textContent=e.format(t):s.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s},dr=(n,e="bubble")=>{let s=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):s.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":s.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:s.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return s},Zn=(n,e,s)=>{var g,U,$,h,b,W;let t=(g=e.showCopy)!=null?g:!0,r=(U=e.showUpvote)!=null?U:!0,o=($=e.showDownvote)!=null?$:!0,a=(h=e.visibility)!=null?h:"hover",l=(b=e.align)!=null?b:"right",p=(W=e.layout)!=null?W:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[p],w=m("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${f} ${a==="hover"?"tvw-message-actions-hover":""}`),d=null,C=(v,D,x,S)=>{let X=document.createElement("button");X.className="tvw-message-action-btn",X.setAttribute("aria-label",D),X.setAttribute("title",D),S&&X.setAttribute("data-action",S);let B=ce(v,14,"currentColor",2);return B&&X.appendChild(B),X.addEventListener("click",_=>{_.preventDefault(),_.stopPropagation(),x()}),X};if(t){let v=C("copy","Copy message",()=>{let D=n.content||"";navigator.clipboard.writeText(D).then(()=>{v.classList.add("tvw-message-action-success");let x=ce("check",14,"currentColor",2);x&&(v.innerHTML="",v.appendChild(x)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let S=ce("copy",14,"currentColor",2);S&&(v.innerHTML="",v.appendChild(S))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),s!=null&&s.onCopy&&s.onCopy(n),e.onCopy&&e.onCopy(n)},"copy");w.appendChild(v)}if(r){let v=C("thumbs-up","Upvote",()=>{if(d==="upvote")d=null,v.classList.remove("tvw-message-action-active");else{let x=w.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),d="upvote",v.classList.add("tvw-message-action-active");let S={type:"upvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),e.onFeedback&&e.onFeedback(S)}},"upvote");w.appendChild(v)}if(o){let v=C("thumbs-down","Downvote",()=>{if(d==="downvote")d=null,v.classList.remove("tvw-message-action-active");else{let x=w.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),d="downvote",v.classList.add("tvw-message-action-active");let S={type:"downvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),e.onFeedback&&e.onFeedback(S)}},"downvote");w.appendChild(v)}return w},tn=(n,e,s,t,r)=>{var W,v,D,x,S;let o=s!=null?s:{},a=(W=o.layout)!=null?W:"bubble",l=o.avatar,p=o.timestamp,c=(v=l==null?void 0:l.show)!=null?v:!1,f=(D=p==null?void 0:p.show)!=null?D:!1,w=(x=l==null?void 0:l.position)!=null?x:"left",d=(S=p==null?void 0:p.position)!=null?S:"below",C=dr(n.role,a),g=m("div",C.join(" ")),U=document.createElement("div");if(U.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),f&&d==="inline"&&n.createdAt){let X=Ho(n,p);X.classList.add("tvw-ml-2","tvw-inline"),U.appendChild(X)}if(g.appendChild(U),f&&d==="below"&&n.createdAt){let X=Ho(n,p);X.classList.add("tvw-mt-1"),g.appendChild(X)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let X=gn();g.appendChild(X)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let X=Zn(n,t,r);g.appendChild(X)}if(!c||n.role==="system")return g;let h=m("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),b=lr(l,n.role);return w==="right"||w==="left"&&n.role==="user"?h.append(g,b):h.append(b,g),g.classList.remove("tvw-max-w-[85%]"),g.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),h},Po=(n,e,s,t,r)=>{let o=s!=null?s:{};return n.role==="user"&&o.renderUserMessage?o.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&o.renderAssistantMessage?o.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):tn(n,e,s,t,r)};var Qn=new Set,es=n=>{let e=n.reasoning,s=m("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return s;let t=Qn.has(n.id),r=m("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false");let o=m("div","tvw-flex tvw-flex-col tvw-text-left"),a=m("span","tvw-text-xs tvw-text-cw-primary");a.textContent="Thinking...",o.appendChild(a);let l=m("span","tvw-text-xs tvw-text-cw-primary");l.textContent=To(e),o.appendChild(l),e.status==="complete"?a.style.display="none":a.style.display="";let p=m("div","tvw-flex tvw-items-center"),f=ce(t?"chevron-up":"chevron-down",16,"currentColor",2);f?p.appendChild(f):p.textContent=t?"Hide":"Show";let w=m("div","tvw-flex tvw-items-center tvw-ml-auto");w.append(p),r.append(o,w);let d=m("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");d.style.display=t?"":"none";let C=e.chunks.join(""),g=m("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");g.textContent=C||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),d.appendChild(g);let U=()=>{r.setAttribute("aria-expanded",t?"true":"false"),p.innerHTML="";let b=ce(t?"chevron-up":"chevron-down",16,"currentColor",2);b?p.appendChild(b):p.textContent=t?"Hide":"Show",d.style.display=t?"":"none"},$=()=>{t=!t,t?Qn.add(n.id):Qn.delete(n.id),U()};return r.addEventListener("pointerdown",h=>{h.preventDefault(),$()}),r.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),$())}),U(),s.append(r,d),s};var ts=new Set,ns=(n,e)=>{var $;let s=n.toolCall,t=($=e==null?void 0:e.toolCall)!=null?$:{},r=m("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!s)return r;let o=ts.has(n.id),a=m("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),t.headerBackgroundColor&&(a.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(a.style.paddingLeft=t.headerPaddingX,a.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(a.style.paddingTop=t.headerPaddingY,a.style.paddingBottom=t.headerPaddingY);let l=m("div","tvw-flex tvw-flex-col tvw-text-left"),p=m("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(p.style.color=t.headerTextColor),p.textContent=Eo(s),l.appendChild(p);let c=m("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",w=ce(o?"chevron-up":"chevron-down",16,f,2);w?c.appendChild(w):c.textContent=o?"Hide":"Show";let d=m("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");d.append(c),a.append(l,d);let C=m("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(C.style.display=o?"":"none",t.contentBackgroundColor&&(C.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(C.style.color=t.contentTextColor),t.contentPaddingX&&(C.style.paddingLeft=t.contentPaddingX,C.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(C.style.paddingTop=t.contentPaddingY,C.style.paddingBottom=t.contentPaddingY),s.name){let h=m("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?h.style.color=t.contentTextColor:t.headerTextColor&&(h.style.color=t.headerTextColor),h.textContent=s.name,C.appendChild(h)}if(s.args!==void 0){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Arguments";let W=m("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Jn(s.args),h.append(b,W),C.appendChild(h)}if(s.chunks&&s.chunks.length){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Activity";let W=m("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=s.chunks.join(`
16
+ `),h.append(b,W),C.appendChild(h)}if(s.status==="complete"&&s.result!==void 0){let h=m("div","tvw-space-y-1"),b=m("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(b.style.color=t.labelTextColor),b.textContent="Result";let W=m("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Jn(s.result),h.append(b,W),C.appendChild(h)}if(s.status==="complete"&&typeof s.duration=="number"){let h=m("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(h.style.color=t.contentTextColor),h.textContent=`Duration: ${s.duration}ms`,C.appendChild(h)}let g=()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let h=t.toggleTextColor||t.headerTextColor||"currentColor",b=ce(o?"chevron-up":"chevron-down",16,h,2);b?c.appendChild(b):c.textContent=o?"Hide":"Show",C.style.display=o?"":"none"},U=()=>{o=!o,o?ts.add(n.id):ts.delete(n.id),g()};return a.addEventListener("pointerdown",h=>{h.preventDefault(),U()}),a.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),U())}),g(),r.append(a,C),r};var Ro=n=>{let e=[];return{buttons:e,render:(t,r,o,a,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(a!=null?a:r?r.getMessages():[]).some(C=>C.role==="user"))return;let f=document.createDocumentFragment(),w=r?r.isStreaming():!1,d=C=>{switch(C){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(C=>{let g=m("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");g.type="button",g.textContent=C,g.disabled=w,l!=null&&l.fontFamily&&(g.style.fontFamily=d(l.fontFamily)),l!=null&&l.fontWeight&&(g.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(g.style.paddingLeft=l.paddingX,g.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(g.style.paddingTop=l.paddingY,g.style.paddingBottom=l.paddingY),g.addEventListener("click",()=>{!r||r.isStreaming()||(o.value="",r.sendMessage(C))}),f.appendChild(g),e.push(g)}),n.appendChild(f)}}};var Io={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},ss=(n,e,s,t)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(o=>{var g,U,$;if(o.dataset.enhanced==="true")return;let a=(g=o.dataset.tvForm)!=null?g:"init";o.dataset.enhanced="true";let l=(U=Io[a])!=null?U:Io.init;o.classList.add("tvw-form-card","tvw-space-y-4");let p=m("div","tvw-space-y-1"),c=m("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=m("p","tvw-text-sm tvw-text-cw-muted");h.textContent=l.description,p.appendChild(h)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(h=>{var x,S;let b=m("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");b.htmlFor=`${e.id}-${a}-${h.name}`;let W=m("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");W.textContent=h.label,b.appendChild(W);let v=(x=h.type)!=null?x:"text",D;v==="textarea"?(D=document.createElement("textarea"),D.rows=3):(D=document.createElement("input"),D.type=v),D.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",D.id=`${e.id}-${a}-${h.name}`,D.name=h.name,D.placeholder=(S=h.placeholder)!=null?S:"",h.required&&(D.required=!0),b.appendChild(D),f.appendChild(b)});let w=m("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),d=m("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),C=m("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");C.type="submit",C.textContent=($=l.submitLabel)!=null?$:"Submit",w.appendChild(d),w.appendChild(C),f.appendChild(w),o.replaceChildren(p,f),f.addEventListener("submit",async h=>{var D,x;h.preventDefault();let b=(D=s.formEndpoint)!=null?D:"/form",W=new FormData(f),v={};W.forEach((S,X)=>{v[X]=S}),v.type=a,C.disabled=!0,d.textContent="Submitting\u2026";try{let S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let X=await S.json();d.textContent=(x=X.message)!=null?x:"Thanks! We'll be in touch soon.",X.success&&X.nextPrompt&&await t.sendMessage(String(X.nextPrompt))}catch(S){d.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{C.disabled=!1}})})};var os=class{constructor(){this.plugins=new Map}register(e){var s;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(s=e.onRegister)==null||s.call(e)}unregister(e){var t;let s=this.plugins.get(e);s&&((t=s.onUnregister)==null||t.call(s),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,s)=>{var t,r;return((t=s.priority)!=null?t:0)-((r=e.priority)!=null?r:0)})}getForInstance(e){let s=this.getAll();if(!e||e.length===0)return s;let t=new Set(e.map(o=>o.id));return[...s.filter(o=>!t.has(o.id)),...e].sort((o,a)=>{var l,p;return((l=a.priority)!=null?l:0)-((p=o.priority)!=null?p:0)})}clear(){this.plugins.forEach(e=>{var s;return(s=e.onUnregister)==null?void 0:s.call(e)}),this.plugins.clear()}},hn=new os;var ke={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Pn(n){var e,s,t,r,o,a,l,p,c,f,w,d,C,g,U,$,h,b,W;return n?{...ke,...n,theme:{...ke.theme,...n.theme},launcher:{...ke.launcher,...n.launcher,clearChat:{...(e=ke.launcher)==null?void 0:e.clearChat,...(s=n.launcher)==null?void 0:s.clearChat}},copy:{...ke.copy,...n.copy},sendButton:{...ke.sendButton,...n.sendButton},statusIndicator:{...ke.statusIndicator,...n.statusIndicator},voiceRecognition:{...ke.voiceRecognition,...n.voiceRecognition},features:{...ke.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:ke.suggestionChips,suggestionChipsConfig:{...ke.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...ke.layout,...n.layout,header:{...(r=ke.layout)==null?void 0:r.header,...(o=n.layout)==null?void 0:o.header},messages:{...(a=ke.layout)==null?void 0:a.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(c=(p=ke.layout)==null?void 0:p.messages)==null?void 0:c.avatar,...(w=(f=n.layout)==null?void 0:f.messages)==null?void 0:w.avatar},timestamp:{...(C=(d=ke.layout)==null?void 0:d.messages)==null?void 0:C.timestamp,...(U=(g=n.layout)==null?void 0:g.messages)==null?void 0:U.timestamp}},slots:{...($=ke.layout)==null?void 0:$.slots,...(h=n.layout)==null?void 0:h.slots}},markdown:{...ke.markdown,...n.markdown,options:{...(b=ke.markdown)==null?void 0:b.options,...(W=n.markdown)==null?void 0:W.options}},messageActions:{...ke.messageActions,...n.messageActions}}:ke}var $o=()=>{let n=new Map,e=(r,o)=>(n.has(r)||n.set(r,new Set),n.get(r).add(o),()=>s(r,o)),s=(r,o)=>{var a;(a=n.get(r))==null||a.delete(o)};return{on:e,off:s,emit:(r,o)=>{var a;(a=n.get(r))==null||a.forEach(l=>{try{l(o)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var cr=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},ur=n=>{let e=n.trim(),s=e.indexOf("{");if(s===-1)return null;let t=0;for(let r=s;r<e.length;r+=1){let o=e[r];if(o==="{"&&(t+=1),o==="}"&&(t-=1,t===0))return e.slice(s,r+1)}return null},mn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=cr(n),s=ur(e);if(!s)return null;let t=JSON.parse(s);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...o}=t;return{type:String(r),payload:o,raw:t}}catch{return null}},rs=n=>typeof n=="string"?n:n==null?"":String(n),Kt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:rs(n.payload.text)},messageAndClick:(n,e)=>{var r;if(n.type!=="message_and_click")return;let s=n.payload,t=rs(s.element);if(t&&((r=e.document)!=null&&r.querySelector)){let o=e.document.querySelector(t);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:rs(s.text)}}},Fo=n=>Array.isArray(n)?n.map(e=>String(e)):[],fn=n=>{let e=new Set(Fo(n.getMetadata().processedActionMessageIds)),s=()=>{e=new Set(Fo(n.getMetadata().processedActionMessageIds))},t=()=>{let o=Array.from(e);n.updateMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||e.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?n.parsers.reduce((c,f)=>c||(f==null?void 0:f({text:a,message:o.message}))||null,null):null;if(!l)return null;e.add(o.message.id),t();let p={action:l,message:o.message};n.emit("action:detected",p);for(let c of n.handlers)if(c)try{let f=c(l,{message:o.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!f)continue;if(f.handled){let w=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:w}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:s}};var pr=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},gr=n=>n.map(e=>({...e,streaming:!1})),Rn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let s=e();return s?pr(s.getItem(n)):null},save:s=>{let t=e();if(t)try{let r={...s,messages:s.messages?gr(s.messages):void 0};t.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let s=e();if(s)try{s.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var is=class{constructor(){this.components=new Map}register(e,s){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,s)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([s,t])=>{this.register(s,t)})}},nn=new is;var sn=require("partial-json");function hr(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function mr(n,e){if(!hr(n))return null;let s=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:s,raw:e}}function In(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:s=>{let t=s.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(s.length<=e)return n;try{let r=(0,sn.parse)(s,sn.STR|sn.OBJ),o=mr(r,s);o&&(n=o)}catch{}return e=s.length,n},reset:()=>{n=null,e=0}}}function No(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function $n(n,e){let{config:s,message:t,onPropsUpdate:r}=e,o=nn.get(n.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:t,config:s,updateProps:l=>{r&&r(l)}};try{return o(n.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Oo(){let n=In();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Fn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Nn(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var fr=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function On(n){let{onSubmit:e,onDismiss:s,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:c=fr}=n,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let w=null,d=document.createElement("div");d.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let g=document.createElement("h3");g.className="tvw-feedback-title",g.textContent=t,C.appendChild(g);let U=document.createElement("p");U.className="tvw-feedback-subtitle",U.textContent=r,C.appendChild(U),d.appendChild(C);let $=document.createElement("div");$.className="tvw-feedback-rating tvw-feedback-rating-csat",$.setAttribute("role","radiogroup"),$.setAttribute("aria-label","Satisfaction rating from 1 to 5");let h=[];for(let x=1;x<=5;x++){let S=document.createElement("button");S.type="button",S.className="tvw-feedback-rating-btn tvw-feedback-star-btn",S.setAttribute("role","radio"),S.setAttribute("aria-checked","false"),S.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${c[x-1]}`),S.title=c[x-1],S.dataset.rating=String(x),S.innerHTML=`
17
+ <svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
18
+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
19
+ </svg>
20
+ `,S.addEventListener("click",()=>{w=x,h.forEach((X,B)=>{let _=B<x;X.classList.toggle("selected",_),X.setAttribute("aria-checked",B===x-1?"true":"false")})}),h.push(S),$.appendChild(S)}d.appendChild($);let b=null;if(p){let x=document.createElement("div");x.className="tvw-feedback-comment-container",b=document.createElement("textarea"),b.className="tvw-feedback-comment",b.placeholder=o,b.rows=3,b.setAttribute("aria-label","Additional comments"),x.appendChild(b),d.appendChild(x)}let W=document.createElement("div");W.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=l,v.addEventListener("click",()=>{s==null||s(),f.remove()});let D=document.createElement("button");return D.type="button",D.className="tvw-feedback-btn tvw-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(w===null){$.classList.add("tvw-feedback-shake"),setTimeout(()=>$.classList.remove("tvw-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let x=(b==null?void 0:b.value.trim())||void 0;await e(w,x),f.remove()}catch(x){D.disabled=!1,D.textContent=a,console.error("[CSAT Feedback] Failed to submit:",x)}}),W.appendChild(v),W.appendChild(D),d.appendChild(W),f.appendChild(d),f}function Dn(n){let{onSubmit:e,onDismiss:s,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:f="Very likely"}=n,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-nps",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Net Promoter Score feedback");let d=null,C=document.createElement("div");C.className="tvw-feedback-content";let g=document.createElement("div");g.className="tvw-feedback-header";let U=document.createElement("h3");U.className="tvw-feedback-title",U.textContent=t,g.appendChild(U);let $=document.createElement("p");$.className="tvw-feedback-subtitle",$.textContent=r,g.appendChild($),C.appendChild(g);let h=document.createElement("div");h.className="tvw-feedback-rating tvw-feedback-rating-nps",h.setAttribute("role","radiogroup"),h.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="tvw-feedback-labels";let W=document.createElement("span");W.className="tvw-feedback-label-low",W.textContent=c;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,b.appendChild(W),b.appendChild(v);let D=document.createElement("div");D.className="tvw-feedback-numbers";let x=[];for(let Z=0;Z<=10;Z++){let j=document.createElement("button");j.type="button",j.className="tvw-feedback-rating-btn tvw-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${Z} out of 10`),j.textContent=String(Z),j.dataset.rating=String(Z),Z<=6?j.classList.add("tvw-feedback-detractor"):Z<=8?j.classList.add("tvw-feedback-passive"):j.classList.add("tvw-feedback-promoter"),j.addEventListener("click",()=>{d=Z,x.forEach((K,Q)=>{K.classList.toggle("selected",Q===Z),K.setAttribute("aria-checked",Q===Z?"true":"false")})}),x.push(j),D.appendChild(j)}h.appendChild(b),h.appendChild(D),C.appendChild(h);let S=null;if(p){let Z=document.createElement("div");Z.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),Z.appendChild(S),C.appendChild(Z)}let X=document.createElement("div");X.className="tvw-feedback-actions";let B=document.createElement("button");B.type="button",B.className="tvw-feedback-btn tvw-feedback-btn-skip",B.textContent=l,B.addEventListener("click",()=>{s==null||s(),w.remove()});let _=document.createElement("button");return _.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-submit",_.textContent=a,_.addEventListener("click",async()=>{if(d===null){D.classList.add("tvw-feedback-shake"),setTimeout(()=>D.classList.remove("tvw-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let Z=(S==null?void 0:S.value.trim())||void 0;await e(d,Z),w.remove()}catch(Z){_.disabled=!1,_.textContent=a,console.error("[NPS Feedback] Failed to submit:",Z)}}),X.appendChild(B),X.appendChild(_),C.appendChild(X),w.appendChild(C),w}var on="vanilla-agent-chat-history",wr=30*1e3,as=n=>!n||typeof n!="object"?{}:{...n},Do=n=>n.map(e=>({...e,streaming:!1})),_o=(n,e)=>{let s=n!=null&&n.markdown?un(n.markdown):null;return t=>{var a,l,p;let r=(a=t.text)!=null?a:"",o=(l=t.message.rawContent)!=null?l:null;if(e){let c=e.process({text:r,raw:o!=null?o:r,message:t.message,streaming:t.streaming});c!==null&&(r=c.text,c.persist||(t.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...t,text:r,raw:(p=o!=null?o:t.text)!=null?p:""}):s?s(r):xn(r)}},_n=(n,e,s)=>{var de,pe,Re,ge,De,it,ht,cs,us,ps,gs,hs,ms,fs;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Pn(e),r=hn.getForInstance(t.plugins);t.components&&nn.registerAll(t.components);let o=$o(),a=(de=t.storageAdapter)!=null?de:Rn(),l={},p=null;if(a!=null&&a.load)try{let i=a.load();if(i&&typeof i.then=="function")p=i;else if(i){let u=i;u.metadata&&(l=as(u.metadata)),(pe=u.messages)!=null&&pe.length&&(t={...t,initialMessages:u.messages})}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",i)}let c=()=>l,f=i=>{var E;l=(E=i({...l}))!=null?E:{},Mt()},w=t.actionParsers&&t.actionParsers.length?t.actionParsers:[mn],d=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick],C=fn({parsers:w,handlers:d,getMetadata:c,updateMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let g=(ge=(Re=t.launcher)==null?void 0:Re.enabled)!=null?ge:!0,U=(it=(De=t.launcher)==null?void 0:De.autoExpand)!=null?it:!1,$=U,h=g,b=g?U:!0,W=_o(t,C),v=(cs=(ht=t.features)==null?void 0:ht.showReasoning)!=null?cs:!0,D=(ps=(us=t.features)==null?void 0:us.showToolCalls)!=null?ps:!0,x={onCopy:i=>{var u,E;o.emit("message:copy",i),I!=null&&I.isClientTokenMode()&&I.submitMessageFeedback(i.id,"copy").catch(O=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",O)}),(E=(u=t.messageActions)==null?void 0:u.onCopy)==null||E.call(u,i)},onFeedback:i=>{var u,E;o.emit("message:feedback",i),I!=null&&I.isClientTokenMode()&&I.submitMessageFeedback(i.messageId,i.type).catch(O=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",O)}),(E=(u=t.messageActions)==null?void 0:u.onFeedback)==null||E.call(u,i)}},S=(gs=t.statusIndicator)!=null?gs:{},X=i=>{var u,E,O,k;return i==="idle"?(u=S.idleText)!=null?u:Xe.idle:i==="connecting"?(E=S.connectingText)!=null?E:Xe.connecting:i==="connected"?(O=S.connectedText)!=null?O:Xe.connected:i==="error"?(k=S.errorText)!=null?k:Xe.error:Xe[i]},{wrapper:B,panel:_}=Lo(t),Z=Bo(t,g),{container:j,body:K,messagesWrapper:Q,suggestions:ne,textarea:re,sendButton:q,sendButtonWrapper:qe,composerForm:Ve,statusText:nt,introTitle:bt,introSubtitle:Ct,closeButton:J,iconHolder:fe,headerTitle:mt,headerSubtitle:ft,header:Ge,footer:st}=Z,H=Z.micButton,He=Z.micButtonWrapper,at=r.find(i=>i.renderHeader);if(at!=null&&at.renderHeader){let i=at.renderHeader({config:t,defaultRenderer:()=>{let u=Ot({config:t,showClose:g});return Qt(j,u,t),u.header},onClose:()=>Ke(!1,"user")});if(i){let u=j.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(i),Ge=i)}}let lt=r.find(i=>i.renderComposer);if(lt!=null&&lt.renderComposer){let i=lt.renderComposer({config:t,defaultRenderer:()=>en({config:t}).footer,onSubmit:u=>{I&&!I.isStreaming()&&I.sendMessage(u)},disabled:!1});i&&(st.replaceWith(i),st=i)}(()=>{var O,k;let i=(k=(O=t.layout)==null?void 0:O.slots)!=null?k:{},u=ee=>{switch(ee){case"body-top":return j.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Q;case"footer-top":return ne;case"composer":return Ve;case"footer-bottom":return nt;default:return null}},E=(ee,N)=>{var T;switch(ee){case"header-left":case"header-center":case"header-right":if(ee==="header-left")Ge.insertBefore(N,Ge.firstChild);else if(ee==="header-right")Ge.appendChild(N);else{let z=Ge.querySelector(".tvw-flex-col");z?(T=z.parentNode)==null||T.insertBefore(N,z.nextSibling):Ge.appendChild(N)}break;case"body-top":let G=K.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(N):K.insertBefore(N,K.firstChild);break;case"body-bottom":K.appendChild(N);break;case"footer-top":ne.replaceWith(N);break;case"footer-bottom":nt.replaceWith(N);break;default:break}};for(let[ee,N]of Object.entries(i))if(N)try{let T=N({config:t,defaultContent:()=>u(ee)});T&&E(ee,T)}catch(T){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ee}":`,T)}})(),_.appendChild(j),n.appendChild(B);let wt=()=>{var ae,Ie,ct,le,ut,Pt,Rt,kt,Ut,It,zt,pt,$t,Ft,bn,dn;let i=(Ie=(ae=t.launcher)==null?void 0:ae.sidebarMode)!=null?Ie:!1,u=i||((le=(ct=t.launcher)==null?void 0:ct.fullHeight)!=null?le:!1),E=(ut=t.theme)!=null?ut:{},O=(Rt=(Pt=t.launcher)==null?void 0:Pt.position)!=null?Rt:"bottom-left",k=O==="bottom-left"||O==="top-left",ee=i?"none":"1px solid var(--tvw-cw-border)",N=i?k?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",T=i?"0":"16px",G=(kt=E.panelBorder)!=null?kt:ee,z=(Ut=E.panelShadow)!=null?Ut:N,R=(It=E.panelBorderRadius)!=null?It:T;n.style.cssText="",B.style.cssText="",_.style.cssText="",j.style.cssText="",K.style.cssText="",st.style.cssText="";let Y=(pt=(zt=t==null?void 0:t.launcher)==null?void 0:zt.width)!=null?pt:t==null?void 0:t.launcherWidth,Be=Y!=null?Y:"min(400px, calc(100vw - 24px))";i||(_.style.width=Be,_.style.maxWidth=Be),_.style.boxShadow=z,_.style.borderRadius=R,j.style.border=G,j.style.borderRadius=R;let he=(($t=t.launcher)==null?void 0:$t.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",B.style.display="flex",B.style.flexDirection="column",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.maxHeight="100%",B.style.height="100%",he&&(B.style.overflow="hidden"),_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.height="100%",_.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",st.style.flexShrink="0"),B.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!i&&!he&&((Ft=vt[O])!=null?Ft:vt["bottom-right"]).split(" ").forEach(Vt=>B.classList.add(Vt)),i){let Jt=(dn=(bn=t.launcher)==null?void 0:bn.sidebarWidth)!=null?dn:"420px";B.style.cssText=`
17
21
  position: fixed !important;
18
22
  top: 0 !important;
19
23
  bottom: 0 !important;
@@ -24,8 +28,8 @@
24
28
  padding: 0 !important;
25
29
  display: flex !important;
26
30
  flex-direction: column !important;
27
- ${I?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
28
- `,Y.style.cssText=`
31
+ ${k?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
+ `,_.style.cssText=`
29
33
  position: relative !important;
30
34
  display: flex !important;
31
35
  flex-direction: column !important;
@@ -36,9 +40,9 @@
36
40
  min-height: 0 !important;
37
41
  margin: 0 !important;
38
42
  padding: 0 !important;
39
- box-shadow: ${_} !important;
40
- border-radius: ${k} !important;
41
- `,Y.style.setProperty("width","100%","important"),Y.style.setProperty("max-width","100%","important"),J.style.cssText=`
43
+ box-shadow: ${z} !important;
44
+ border-radius: ${R} !important;
45
+ `,_.style.setProperty("width","100%","important"),_.style.setProperty("max-width","100%","important"),j.style.cssText=`
42
46
  display: flex !important;
43
47
  flex-direction: column !important;
44
48
  flex: 1 1 0% !important;
@@ -47,17 +51,17 @@
47
51
  min-height: 0 !important;
48
52
  max-height: 100% !important;
49
53
  overflow: hidden !important;
50
- border-radius: ${k} !important;
54
+ border-radius: ${R} !important;
51
55
  border: ${G} !important;
52
- `,nt.style.cssText=`
56
+ `,st.style.cssText=`
53
57
  flex-shrink: 0 !important;
54
58
  border-top: none !important;
55
59
  padding: 8px 16px 12px 16px !important;
56
- `}if(!ue){let Jt="max-height: -moz-available !important; max-height: stretch !important;",Vt=a?"":"padding-top: 1.25em !important;";P.style.cssText+=Jt+Vt}};wt(),_n(n,t);let $e=[],st=Mo(De),Ue=null,U,lt=!1,Ae=!0,Oe=0,Z=0,Te=null,Ee=!1,ze=0,Je=!1,xt=125,Bt=2e3,yt=5,Et=50,St=new Map,we={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Ht=(ps=(cs=t.voiceRecognition)==null?void 0:cs.autoResume)!=null?ps:!1,Be=a=>{o.emit("voice:state",{active:we.active,source:a,timestamp:Date.now()})},Ye=()=>{c(a=>({...a,voiceState:{active:we.active,timestamp:Date.now(),manuallyDeactivated:we.manuallyDeactivated}}))},At=()=>{var N,I;if(((N=t.voiceRecognition)==null?void 0:N.enabled)===!1)return;let a=ns(l.voiceState),g=!!a.active,W=Number((I=a.timestamp)!=null?I:0);we.manuallyDeactivated=!!a.manuallyDeactivated,g&&Date.now()-W<pr&&setTimeout(()=>{we.active||(we.manuallyDeactivated=!1,Se("restore"))},1e3)},Nt=()=>U?Io(U.getMessages()).filter(a=>!a.__skipPersist):[];function Wt(a){if(!(i!=null&&i.save))return;let W={messages:a?Io(a):U?Nt():[],metadata:l};try{let N=i.save(W);N instanceof Promise&&N.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)})}catch(N){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",N)}}let jt=(a=!1)=>{if(!Ae)return;let g=Date.now();Ee&&g<ze&&!a||(Ee&&g>=ze&&(Ee=!1),!(!a&&!lt)&&(g-Z<xt||(Z=g,Te&&cancelAnimationFrame(Te),Te=requestAnimationFrame(()=>{Ee||!Ae||(Je=!0,F.scrollTop=F.scrollHeight,Oe=F.scrollTop,requestAnimationFrame(()=>{Je=!1}),Te=null)}))))},Mt=null,fn=()=>P.querySelector("#vanilla-agent-scroll-container")||F,wn=(a,g=500)=>{let W=a.scrollTop,N=a.clientHeight,I=a.scrollHeight,re=I-W;if(W+N>=I-2||Math.abs(re)<5)return;Mt!==null&&(cancelAnimationFrame(Mt),Mt=null);let C=performance.now(),G=k=>1-Math.pow(1-k,3),_=k=>{let z=a.scrollHeight;z!==I&&(I=z,re=I-W);let He=k-C,ue=Math.min(He/g,1),ie=G(ue),Pe=W+re*ie;a.scrollTop=Pe,ue<1?Mt=requestAnimationFrame(_):(a.scrollTop=a.scrollHeight,Mt=null)};Mt=requestAnimationFrame(_)},yn=a=>{let g=new Map;a.forEach(W=>{let N=St.get(W.id);g.set(W.id,{streaming:W.streaming,role:W.role}),!N&&W.role==="assistant"&&o.emit("assistant:message",W),W.role==="assistant"&&(N!=null&&N.streaming)&&W.streaming===!1&&o.emit("assistant:complete",W)}),St.clear(),g.forEach((W,N)=>{St.set(N,W)})},_t=(a,g,W)=>{a.innerHTML="";let N=document.createDocumentFragment();g.forEach(C=>{var He,ue;let G=null,_=r.find(ie=>!!(C.variant==="reasoning"&&ie.renderReasoning||C.variant==="tool"&&ie.renderToolCall||!C.variant&&ie.renderMessage)),k=(He=t.layout)==null?void 0:He.messages;if(_)if(C.variant==="reasoning"&&C.reasoning&&_.renderReasoning){if(!w)return;G=_.renderReasoning({message:C,defaultRenderer:()=>Xn(C),config:t})}else if(C.variant==="tool"&&C.toolCall&&_.renderToolCall){if(!K)return;G=_.renderToolCall({message:C,defaultRenderer:()=>Gn(C,t),config:t})}else _.renderMessage&&(G=_.renderMessage({message:C,defaultRenderer:()=>{let ie=tn(C,W,k,t.messageActions,T);return C.role!=="user"&&Zn(ie,C,t,U),ie},config:t}));if(!G&&C.role==="assistant"&&!C.variant&&t.enableComponentStreaming!==!1&&In(C)){let Pe=Pn(C);if(Pe){let dt=Rn(Pe,{config:t,message:C,transform:W});if(dt){let ae=document.createElement("div");if(ae.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(" "),ae.setAttribute("data-message-id",C.id),C.content&&C.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=W({text:C.content,message:C,streaming:!!C.streaming,raw:C.rawContent}),ae.appendChild(ct)}ae.appendChild(dt),G=ae}}}if(!G)if(C.variant==="reasoning"&&C.reasoning){if(!w)return;G=Xn(C)}else if(C.variant==="tool"&&C.toolCall){if(!K)return;G=Gn(C,t)}else{let ie=(ue=t.layout)==null?void 0:ue.messages;ie!=null&&ie.renderUserMessage&&C.role==="user"?G=ie.renderUserMessage({message:C,config:t,streaming:!!C.streaming}):ie!=null&&ie.renderAssistantMessage&&C.role==="assistant"?G=ie.renderAssistantMessage({message:C,config:t,streaming:!!C.streaming}):G=tn(C,W,ie,t.messageActions,T),C.role!=="user"&&G&&Zn(G,C,t,U)}let z=document.createElement("div");z.className="tvw-flex",C.role==="user"&&z.classList.add("tvw-justify-end"),z.appendChild(G),N.appendChild(z)});let I=g.some(C=>C.role==="assistant"&&C.streaming),re=g[g.length-1],H=(re==null?void 0:re.role)==="assistant"&&!re.streaming;if(lt&&g.some(C=>C.role==="user")&&!I&&!H){let C=un(),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(C);let _=document.createElement("div");_.className="tvw-flex",_.appendChild(G),N.appendChild(_)}a.appendChild(N),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let C=fn();wn(C)})})},qt=()=>{f&&(x?(P.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Y.classList.remove("tvw-scale-95","tvw-opacity-0"),Y.classList.add("tvw-scale-100","tvw-opacity-100"),B?B.element.style.display="none":V&&(V.style.display="none")):(P.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Y.classList.remove("tvw-scale-100","tvw-opacity-100"),Y.classList.add("tvw-scale-95","tvw-opacity-0"),B?B.element.style.display="":V&&(V.style.display="")))},ot=(a,g="user")=>{if(!f||x===a)return;let W=x;x=a,qt(),x&&(ye(),jt(!0));let N={open:x,source:g,timestamp:Date.now()};x&&!W?o.emit("widget:opened",N):!x&&W&&o.emit("widget:closed",N),o.emit("widget:state",{open:x,launcherEnabled:f,voiceActive:we.active,streaming:U.isStreaming()})},Xt=a=>{$.disabled=a,L&&(L.disabled=a),st.buttons.forEach(g=>{g.disabled=a})},rn=()=>{var I,re,H,C,G,_,k,z,He,ue,ie,Pe,dt,ae;bt.textContent=(re=(I=t.copy)==null?void 0:I.welcomeTitle)!=null?re:"Hello \u{1F44B}",Ct.textContent=(C=(H=t.copy)==null?void 0:H.welcomeSubtitle)!=null?C:"Ask anything about your account or products.",oe.placeholder=(_=(G=t.copy)==null?void 0:G.inputPlaceholder)!=null?_:"How can I help...",((z=(k=t.sendButton)==null?void 0:k.useIcon)!=null?z:!1)||($.textContent=(ue=(He=t.copy)==null?void 0:He.sendButtonLabel)!=null?ue:"Send");let g=(Pe=(ie=t.theme)==null?void 0:ie.inputFontFamily)!=null?Pe:"sans-serif",W=(ae=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?ae:"400",N=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};oe.style.fontFamily=N(g),oe.style.fontWeight=W};U=new Zt(t,{onMessagesChanged(a){_t(ne,a,R),U&&(a.some(N=>N.role==="user")?st.render([],U,oe,a):st.render(t.suggestionChips,U,oe,a,t.suggestionChipsConfig)),jt(!lt),yn(a);let g=[...a].reverse().find(W=>W.role==="user");we.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wt(a)},onStatusChanged(a){var N;let g=(N=t.statusIndicator)!=null?N:{},W=I=>{var re,H,C,G;return I==="idle"?(re=g.idleText)!=null?re:Ke.idle:I==="connecting"?(H=g.connectingText)!=null?H:Ke.connecting:I==="connected"?(C=g.connectedText)!=null?C:Ke.connected:I==="error"?(G=g.errorText)!=null?G:Ke.error:Ke[I]};tt.textContent=W(a)},onStreamingChanged(a){lt=a,Xt(a),U&&_t(ne,U.getMessages(),R),a||jt(!0)}}),d&&d.then(a=>{var g;a&&(a.metadata&&(l=ns(a.metadata),b.syncFromMetadata()),(g=a.messages)!=null&&g.length&&U.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let an=a=>{a.preventDefault();let g=oe.value.trim();g&&(oe.value="",U.sendMessage(g))},S=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),$.click())},X=null,te=!1,be=null,xe=null,Ne=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Se=(a="user")=>{var re,H,C,G;if(te||U.isStreaming())return;let g=Ne();if(!g)return;X=new g;let N=(H=((re=t.voiceRecognition)!=null?re:{}).pauseDuration)!=null?H:2e3;X.continuous=!0,X.interimResults=!0,X.lang="en-US";let I=oe.value;X.onresult=_=>{let k="",z="";for(let ue=0;ue<_.results.length;ue++){let ie=_.results[ue],Pe=ie[0].transcript;ie.isFinal?k+=Pe+" ":z=Pe}let He=I+k+z;oe.value=He,be&&clearTimeout(be),(k||z)&&(be=window.setTimeout(()=>{let ue=oe.value.trim();ue&&X&&te&&(A(),oe.value="",U.sendMessage(ue,{viaVoice:!0}))},N))},X.onerror=_=>{_.error!=="no-speech"&&A()},X.onend=()=>{if(te){let _=oe.value.trim();_&&_!==I.trim()&&(oe.value="",U.sendMessage(_,{viaVoice:!0})),A()}};try{if(X.start(),te=!0,we.active=!0,a!=="system"&&(we.manuallyDeactivated=!1),Be(a),Ye(),L){xe={backgroundColor:L.style.backgroundColor,color:L.style.color,borderColor:L.style.borderColor};let _=(C=t.voiceRecognition)!=null?C:{},k=(G=_.recordingBackgroundColor)!=null?G:"#ef4444",z=_.recordingIconColor,He=_.recordingBorderColor;if(L.classList.add("tvw-voice-recording"),L.style.backgroundColor=k,z){L.style.color=z;let ue=L.querySelector("svg");ue&&ue.setAttribute("stroke",z)}He&&(L.style.borderColor=He),L.setAttribute("aria-label","Stop voice recognition")}}catch{A("system")}},A=(a="user")=>{if(te){if(te=!1,be&&(clearTimeout(be),be=null),X){try{X.stop()}catch{}X=null}if(we.active=!1,Be(a),Ye(),L){if(L.classList.remove("tvw-voice-recording"),xe){L.style.backgroundColor=xe.backgroundColor,L.style.color=xe.color,L.style.borderColor=xe.borderColor;let g=L.querySelector("svg");g&&g.setAttribute("stroke",xe.color||"currentColor"),xe=null}L.setAttribute("aria-label","Start voice recognition")}}},gt=(a,g)=>{var Pe,dt,ae,ct,Rt,It,Lt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let N=p("div","tvw-send-button-wrapper"),I=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");I.type="button",I.setAttribute("aria-label","Start voice recognition");let re=(Pe=a==null?void 0:a.iconName)!=null?Pe:"mic",H=(dt=g==null?void 0:g.size)!=null?dt:"40px",C=(ae=a==null?void 0:a.iconSize)!=null?ae:H,G=parseFloat(C)||24,_=(ct=a==null?void 0:a.backgroundColor)!=null?ct:g==null?void 0:g.backgroundColor,k=(Rt=a==null?void 0:a.iconColor)!=null?Rt:g==null?void 0:g.textColor;I.style.width=C,I.style.height=C,I.style.minWidth=C,I.style.minHeight=C,I.style.fontSize="18px",I.style.lineHeight="1";let z=k||"currentColor",He=le(re,G,z,1.5);He?(I.appendChild(He),I.style.color=z):(I.textContent="\u{1F3A4}",I.style.color=z),_?I.style.backgroundColor=_:I.classList.add("tvw-bg-cw-primary"),k?I.style.color=k:!k&&!(g!=null&&g.textColor)&&I.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(I.style.borderWidth=a.borderWidth,I.style.borderStyle="solid"),a!=null&&a.borderColor&&(I.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(I.style.paddingLeft=a.paddingX,I.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(I.style.paddingTop=a.paddingY,I.style.paddingBottom=a.paddingY),N.appendChild(I);let ue=(It=a==null?void 0:a.tooltipText)!=null?It:"Start voice recognition";if(((Lt=a==null?void 0:a.showTooltip)!=null?Lt:!1)&&ue){let Ut=p("div","tvw-send-button-tooltip");Ut.textContent=ue,N.appendChild(Ut)}return{micButton:I,micButtonWrapper:N}},Q=()=>{if(te){let a=oe.value.trim();we.manuallyDeactivated=!0,Ye(),A("user"),a&&(oe.value="",U.sendMessage(a))}else we.manuallyDeactivated=!1,Ye(),Se("user")};L&&(L.addEventListener("click",Q),$e.push(()=>{A("system"),L&&L.removeEventListener("click",Q)}));let E=o.on("assistant:complete",()=>{Ht&&(we.active||we.manuallyDeactivated||Ht==="assistant"&&!we.lastUserMessageWasVoice||setTimeout(()=>{!we.active&&!we.manuallyDeactivated&&Se("auto")},600))});$e.push(E);let v=()=>{ot(!x,"user")},B=null,V=null;if(f){let a=r.find(g=>g.renderLauncher);if(a!=null&&a.renderLauncher){let g=a.renderLauncher({config:t,defaultRenderer:()=>pn(t,v).element,onToggle:v});g&&(V=g)}V||(B=pn(t,v))}B?n.appendChild(B.element):V&&n.appendChild(V),qt(),st.render(t.suggestionChips,U,oe,void 0,t.suggestionChipsConfig),rn(),Xt(U.isStreaming()),jt(!0),At();let ye=()=>{var W,N,I,re,H,C,G,_;let a=(N=(W=t.launcher)==null?void 0:W.sidebarMode)!=null?N:!1,g=a||((re=(I=t.launcher)==null?void 0:I.fullHeight)!=null?re:!1);if(!f){Y.style.height="",Y.style.width="";return}if(!a){let k=(C=(H=t==null?void 0:t.launcher)==null?void 0:H.width)!=null?C:t==null?void 0:t.launcherWidth,z=k!=null?k:"min(400px, calc(100vw - 24px))";Y.style.width=z,Y.style.maxWidth=z}if(!g){let k=window.innerHeight,z=64,He=(_=(G=t.launcher)==null?void 0:G.heightOffset)!=null?_:0,ue=Math.max(200,k-z),ie=Math.min(640,ue),Pe=Math.max(200,ie-He);Y.style.height=`${Pe}px`}};ye(),window.addEventListener("resize",ye),$e.push(()=>window.removeEventListener("resize",ye)),Oe=F.scrollTop;let Ge=()=>{let a=F.scrollTop,g=F.scrollHeight,W=F.clientHeight,N=g-a-W,I=Math.abs(a-Oe);if(Oe=a,!Je&&!(I<=yt)){if(!Ae&&N<Et){Ee=!1,Ae=!0;return}Ae&&N>Et&&(Ee=!0,ze=Date.now()+Bt,Ae=!1)}};F.addEventListener("scroll",Ge,{passive:!0}),$e.push(()=>F.removeEventListener("scroll",Ge)),$e.push(()=>{Te&&cancelAnimationFrame(Te)});let Me=()=>{q&&(Ue&&(q.removeEventListener("click",Ue),Ue=null),f?(q.style.display="",Ue=()=>{x=!1,qt()},q.addEventListener("click",Ue)):q.style.display="none")};Me(),(()=>{let{clearChatButton:a}=fe;a&&a.addEventListener("click",()=>{U.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(W){console.error("[AgentWidget] Failed to clear default localStorage:",W)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(W){console.error("[AgentWidget] Failed to clear custom localStorage:",W)}let g=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let W=i.clear();W instanceof Promise&&W.catch(N=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",N)})}catch(W){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",W)}l={},b.syncFromMetadata()})})(),Xe.addEventListener("submit",an),oe.addEventListener("keydown",S),$e.push(()=>{Xe.removeEventListener("submit",an),oe.removeEventListener("keydown",S)}),$e.push(()=>{U.cancel()}),B?$e.push(()=>{B==null||B.destroy()}):V&&$e.push(()=>{V==null||V.remove()});let ve={update(a){var ln,Jt,Vt,gs,hs,ms,fs,ws,ys,vs,bs,Cs,xs,Ss,As,Ts,Es,Ws,Ms,Ls,ks,Bs,Hs,Rs,Is,Ps,$s,Os,Fs,Ds,Ns,js,_s,qs,Us,zs,Js,Ys,Ks,Xs,Vs,Gs,Zs,Qs,eo,to,no,so,oo,ro,io,ao,lo,co,po,uo,go;let g=t.toolCall;t={...t,...a},wt(),_n(n,t);let W=gn.getForInstance(t.plugins);if(r.length=0,r.push(...W),f=(Jt=(ln=t.launcher)==null?void 0:ln.enabled)!=null?Jt:!0,D=(gs=(Vt=t.launcher)==null?void 0:Vt.autoExpand)!=null?gs:!1,w=(ms=(hs=t.features)==null?void 0:hs.showReasoning)!=null?ms:!0,K=(ws=(fs=t.features)==null?void 0:fs.showToolCalls)!=null?ws:!0,((ys=t.launcher)==null?void 0:ys.enabled)===!1&&B&&(B.destroy(),B=null),((vs=t.launcher)==null?void 0:vs.enabled)===!1&&V&&(V.remove(),V=null),((bs=t.launcher)==null?void 0:bs.enabled)!==!1&&!B&&!V){let M=r.find(me=>me.renderLauncher);if(M!=null&&M.renderLauncher){let me=M.renderLauncher({config:t,defaultRenderer:()=>pn(t,v).element,onToggle:v});me&&(V=me,n.appendChild(V))}V||(B=pn(t,v),n.appendChild(B.element))}B&&B.update(t),mt&&((Cs=t.launcher)==null?void 0:Cs.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((xs=t.launcher)==null?void 0:xs.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),f!==h?f?ot(D,"auto"):(x=!0,qt()):D!==j&&ot(D,"auto"),j=D,h=f,ye(),Me(),JSON.stringify(a.toolCall)!==JSON.stringify(g)&&U&&_t(ne,U.getMessages(),R);let H=(Ss=t.launcher)!=null?Ss:{},C=(As=H.headerIconHidden)!=null?As:!1,G=H.headerIconName,_=(Ts=H.headerIconSize)!=null?Ts:"48px";if(he){let M=J.querySelector(".tvw-border-b-cw-divider"),me=M==null?void 0:M.querySelector(".tvw-flex-col");if(C)he.style.display="none",M&&me&&!M.contains(me)&&M.insertBefore(me,M.firstChild);else{if(he.style.display="",he.style.height=_,he.style.width=_,M&&me&&(M.contains(he)?he.nextSibling!==me&&(he.remove(),M.insertBefore(he,me)):M.insertBefore(he,me)),G){let Le=parseFloat(_)||24,Ce=le(G,Le*.6,"#ffffff",2);Ce?he.replaceChildren(Ce):he.textContent=(Es=H.agentIconText)!=null?Es:"\u{1F4AC}"}else if(H.iconUrl){let Le=he.querySelector("img");if(Le)Le.src=H.iconUrl,Le.style.height=_,Le.style.width=_;else{let Ce=document.createElement("img");Ce.src=H.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=_,Ce.style.width=_,he.replaceChildren(Ce)}}else{let Le=he.querySelector("svg"),Ce=he.querySelector("img");(Le||Ce)&&he.replaceChildren(),he.textContent=(Ws=H.agentIconText)!=null?Ws:"\u{1F4AC}"}let se=he.querySelector("img");se&&(se.style.height=_,se.style.width=_)}}if(q){let M=(Ms=H.closeButtonSize)!=null?Ms:"32px",me=(Ls=H.closeButtonPlacement)!=null?Ls:"inline";q.style.height=M,q.style.width=M;let{closeButtonWrapper:se}=fe,Le=me==="top-right",Ce=se==null?void 0:se.classList.contains("tvw-absolute");if(se&&Le!==Ce)if(se.remove(),Le)se.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",J.style.position="relative",J.appendChild(se);else{let ge=(Bs=(ks=H.clearChat)==null?void 0:ks.placement)!=null?Bs:"inline",Qe=(Rs=(Hs=H.clearChat)==null?void 0:Hs.enabled)!=null?Rs:!0;se.className=Qe&&ge==="inline"?"":"tvw-ml-auto";let et=J.querySelector(".tvw-border-b-cw-divider");et&&et.appendChild(se)}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 ge=H.closeButtonBorderWidth||"0px",Qe=H.closeButtonBorderColor||"transparent";q.style.border=`${ge} solid ${Qe}`,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=(Is=H.closeButtonIconName)!=null?Is:"x",je=(Ps=H.closeButtonIconText)!=null?Ps:"\xD7";q.innerHTML="";let ut=le(Ze,"20px",H.closeButtonColor||"",2);ut?q.appendChild(ut):q.textContent=je;let Ft=($s=H.closeButtonTooltipText)!=null?$s:"Close chat",We=(Os=H.closeButtonShowTooltip)!=null?Os:!0;if(q.setAttribute("aria-label",Ft),se&&(se._cleanupTooltip&&(se._cleanupTooltip(),delete se._cleanupTooltip),We&&Ft)){let ge=null,Qe=()=>{if(ge||!q)return;ge=p("div","tvw-clear-chat-tooltip"),ge.textContent=Ft;let Gt=p("div");Gt.className="tvw-clear-chat-tooltip-arrow",ge.appendChild(Gt);let Dn=q.getBoundingClientRect();ge.style.position="fixed",ge.style.left=`${Dn.left+Dn.width/2}px`,ge.style.top=`${Dn.top-8}px`,ge.style.transform="translate(-50%, -100%)",document.body.appendChild(ge)},et=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};se.addEventListener("mouseenter",Qe),se.addEventListener("mouseleave",et),q.addEventListener("focus",Qe),q.addEventListener("blur",et),se._cleanupTooltip=()=>{et(),se&&(se.removeEventListener("mouseenter",Qe),se.removeEventListener("mouseleave",et)),q&&(q.removeEventListener("focus",Qe),q.removeEventListener("blur",et))}}}let{clearChatButton:k,clearChatButtonWrapper:z}=fe;if(k){let M=(Fs=H.clearChat)!=null?Fs:{},me=(Ds=M.enabled)!=null?Ds:!0,se=(Ns=M.placement)!=null?Ns:"inline";if(z){z.style.display=me?"":"none";let Le=se==="top-right",Ce=z.classList.contains("tvw-absolute");if(Le!==Ce&&me){if(z.remove(),Le)z.className="tvw-absolute tvw-top-4 tvw-z-50",z.style.right="48px",J.style.position="relative",J.appendChild(z);else{z.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",z.style.right="";let je=J.querySelector(".tvw-border-b-cw-divider"),ut=fe.closeButtonWrapper;je&&ut&&ut.parentElement===je?je.insertBefore(z,ut):je&&je.appendChild(z)}let Ze=fe.closeButtonWrapper;Ze&&!Ze.classList.contains("tvw-absolute")&&(Le?Ze.classList.add("tvw-ml-auto"):Ze.classList.remove("tvw-ml-auto"))}}if(me){let Le=(js=M.size)!=null?js:"32px";k.style.height=Le,k.style.width=Le;let Ce=(_s=M.iconName)!=null?_s:"refresh-cw",Ze=(qs=M.iconColor)!=null?qs:"";k.innerHTML="";let je=le(Ce,"20px",Ze||"",2);if(je&&k.appendChild(je),Ze?(k.style.color=Ze,k.classList.remove("tvw-text-cw-muted")):(k.style.color="",k.classList.add("tvw-text-cw-muted")),M.backgroundColor?(k.style.backgroundColor=M.backgroundColor,k.classList.remove("hover:tvw-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let We=M.borderWidth||"0px",ge=M.borderColor||"transparent";k.style.border=`${We} solid ${ge}`,k.classList.remove("tvw-border-none")}else k.style.border="",k.classList.add("tvw-border-none");M.borderRadius?(k.style.borderRadius=M.borderRadius,k.classList.remove("tvw-rounded-full")):(k.style.borderRadius="",k.classList.add("tvw-rounded-full")),M.paddingX?(k.style.paddingLeft=M.paddingX,k.style.paddingRight=M.paddingX):(k.style.paddingLeft="",k.style.paddingRight=""),M.paddingY?(k.style.paddingTop=M.paddingY,k.style.paddingBottom=M.paddingY):(k.style.paddingTop="",k.style.paddingBottom="");let ut=(Us=M.tooltipText)!=null?Us:"Clear chat",Ft=(zs=M.showTooltip)!=null?zs:!0;if(k.setAttribute("aria-label",ut),z&&(z._cleanupTooltip&&(z._cleanupTooltip(),delete z._cleanupTooltip),Ft&&ut)){let We=null,ge=()=>{if(We||!k)return;We=p("div","tvw-clear-chat-tooltip"),We.textContent=ut;let et=p("div");et.className="tvw-clear-chat-tooltip-arrow",We.appendChild(et);let Gt=k.getBoundingClientRect();We.style.position="fixed",We.style.left=`${Gt.left+Gt.width/2}px`,We.style.top=`${Gt.top-8}px`,We.style.transform="translate(-50%, -100%)",document.body.appendChild(We)},Qe=()=>{We&&We.parentNode&&(We.parentNode.removeChild(We),We=null)};z.addEventListener("mouseenter",ge),z.addEventListener("mouseleave",Qe),k.addEventListener("focus",ge),k.addEventListener("blur",Qe),z._cleanupTooltip=()=>{Qe(),z&&(z.removeEventListener("mouseenter",ge),z.removeEventListener("mouseleave",Qe)),k&&(k.removeEventListener("focus",ge),k.removeEventListener("blur",Qe))}}}}let He=t.actionParsers&&t.actionParsers.length?t.actionParsers:[hn],ue=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick];b=mn({parsers:He,handlers:ue,getMetadata:u,updateMetadata:c,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),R=Po(t,b),U.updateConfig(t),_t(ne,U.getMessages(),R),st.render(t.suggestionChips,U,oe,void 0,t.suggestionChipsConfig),rn(),Xt(U.isStreaming());let ie=((Js=t.voiceRecognition)==null?void 0:Js.enabled)===!0,Pe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=ie&&Pe;if(Xe.classList.remove("tvw-gap-1","tvw-gap-3"),Xe.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),ie&&Pe)if(!L||!Re){let M=gt(t.voiceRecognition,t.sendButton);M&&(L=M.micButton,Re=M.micButtonWrapper,Xe.insertBefore(Re,qe),L.addEventListener("click",Q),L.disabled=U.isStreaming())}else{let M=(Ys=t.voiceRecognition)!=null?Ys:{},me=(Ks=t.sendButton)!=null?Ks:{},se=(Xs=M.iconName)!=null?Xs:"mic",Le=(Vs=me.size)!=null?Vs:"40px",Ce=(Gs=M.iconSize)!=null?Gs:Le,Ze=parseFloat(Ce)||24;L.style.width=Ce,L.style.height=Ce,L.style.minWidth=Ce,L.style.minHeight=Ce;let je=(Qs=(Zs=M.iconColor)!=null?Zs:me.textColor)!=null?Qs:"currentColor";L.innerHTML="";let ut=le(se,Ze,je,2);ut?L.appendChild(ut):L.textContent="\u{1F3A4}";let Ft=(eo=M.backgroundColor)!=null?eo:me.backgroundColor;Ft?(L.style.backgroundColor=Ft,L.classList.remove("tvw-bg-cw-primary")):(L.style.backgroundColor="",L.classList.add("tvw-bg-cw-primary")),je?(L.style.color=je,L.classList.remove("tvw-text-white")):!je&&!me.textColor&&(L.style.color="",L.classList.add("tvw-text-white")),M.borderWidth?(L.style.borderWidth=M.borderWidth,L.style.borderStyle="solid"):(L.style.borderWidth="",L.style.borderStyle=""),M.borderColor?L.style.borderColor=M.borderColor:L.style.borderColor="",M.paddingX?(L.style.paddingLeft=M.paddingX,L.style.paddingRight=M.paddingX):(L.style.paddingLeft="",L.style.paddingRight=""),M.paddingY?(L.style.paddingTop=M.paddingY,L.style.paddingBottom=M.paddingY):(L.style.paddingTop="",L.style.paddingBottom="");let We=Re==null?void 0:Re.querySelector(".tvw-send-button-tooltip"),ge=(to=M.tooltipText)!=null?to:"Start voice recognition";if(((no=M.showTooltip)!=null?no:!1)&&ge)if(We)We.textContent=ge,We.style.display="";else{let et=document.createElement("div");et.className="tvw-send-button-tooltip",et.textContent=ge,Re==null||Re.insertBefore(et,L)}else We&&(We.style.display="none");Re.style.display="",L.disabled=U.isStreaming()}else L&&Re&&(Re.style.display="none",te&&A());let ae=(so=t.sendButton)!=null?so:{},ct=(oo=ae.useIcon)!=null?oo:!1,Rt=(ro=ae.iconText)!=null?ro:"\u2191",It=ae.iconName,Lt=(io=ae.tooltipText)!=null?io:"Send message",Ut=(ao=ae.showTooltip)!=null?ao:!1,Pt=(lo=ae.size)!=null?lo:"40px",zt=ae.backgroundColor,pt=ae.textColor;if(ct){if($.style.width=Pt,$.style.height=Pt,$.style.minWidth=Pt,$.style.minHeight=Pt,$.style.fontSize="18px",$.style.lineHeight="1",$.innerHTML="",It){let M=parseFloat(Pt)||24,me=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",se=le(It,M,me,2);se?($.appendChild(se),$.style.color=me):($.textContent=Rt,pt?$.style.color=pt:$.classList.add("tvw-text-white"))}else $.textContent=Rt,pt?$.style.color=pt:$.classList.add("tvw-text-white");$.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",zt?($.style.backgroundColor=zt,$.classList.remove("tvw-bg-cw-primary")):$.classList.add("tvw-bg-cw-primary")}else $.textContent=(po=(co=t.copy)==null?void 0:co.sendButtonLabel)!=null?po:"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"),pt?$.style.color=pt:$.classList.add("tvw-text-white");ae.borderWidth?($.style.borderWidth=ae.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),ae.borderColor?$.style.borderColor=ae.borderColor:$.style.borderColor="",ae.paddingX?($.style.paddingLeft=ae.paddingX,$.style.paddingRight=ae.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),ae.paddingY?($.style.paddingTop=ae.paddingY,$.style.paddingBottom=ae.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let $t=qe==null?void 0:qe.querySelector(".tvw-send-button-tooltip");if(Ut&&Lt)if($t)$t.textContent=Lt,$t.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=Lt,qe==null||qe.insertBefore(M,$)}else $t&&($t.style.display="none");let Ot=(uo=t.statusIndicator)!=null?uo:{},vn=(go=Ot.visible)!=null?go:!0;if(tt.style.display=vn?"":"none",U){let M=U.getStatus(),me=se=>{var Le,Ce,Ze,je;return se==="idle"?(Le=Ot.idleText)!=null?Le:Ke.idle:se==="connecting"?(Ce=Ot.connectingText)!=null?Ce:Ke.connecting:se==="connected"?(Ze=Ot.connectedText)!=null?Ze:Ke.connected:se==="error"?(je=Ot.errorText)!=null?je:Ke.error:Ke[se]};tt.textContent=me(M)}},open(){f&&ot(!0,"api")},close(){f&&ot(!1,"api")},toggle(){f&&ot(!x,"api")},clearChat(){U.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",W)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}l={},b.syncFromMetadata()},setMessage(a){return!oe||U.isStreaming()?!1:(!x&&f&&ot(!0,"system"),oe.value=a,oe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(U.isStreaming())return!1;let g=(a==null?void 0:a.trim())||oe.value.trim();return g?(!x&&f&&ot(!0,"system"),oe.value="",U.sendMessage(g),!0):!1},startVoiceRecognition(){return te||U.isStreaming()||!Ne()?!1:(!x&&f&&ot(!0,"system"),we.manuallyDeactivated=!1,Ye(),Se("user"),!0)},stopVoiceRecognition(){return te?(we.manuallyDeactivated=!0,Ye(),A("user"),!0):!1},injectTestMessage(a){!x&&f&&ot(!0,"system"),U.injectTestEvent(a)},getMessages(){return U.getMessages()},getStatus(){return U.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){c(a)},on(a,g){return o.on(a,g)},off(a,g){o.off(a,g)},isOpen(){return f&&x},isVoiceActive(){return we.active},getState(){return{open:f&&x,launcherEnabled:f,voiceActive:we.active,streaming:U.isStreaming()}},destroy(){$e.forEach(a=>a()),P.remove(),B==null||B.destroy(),V==null||V.remove(),Ue&&q.removeEventListener("click",Ue)}};if((((us=s==null?void 0:s.debugTools)!=null?us:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,g={controller:ve,getMessages:ve.getMessages,getStatus:ve.getStatus,getMetadata:ve.getPersistentMetadata,updateMetadata:ve.updatePersistentMetadata,clearHistory:()=>ve.clearChat(),setVoiceActive:W=>W?ve.startVoiceRecognition():ve.stopVoiceRecognition()};window.AgentWidgetBrowser=g,$e.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=a)})}return ve};var ss={},ur=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},gr=()=>{try{if(typeof ss!="undefined"&&ss.url)return new URL("../widget.css",ss.url).href}catch{}return null},$o=n=>{let e=gr(),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)}},os=n=>{var u,c,y,m;let e=ur(n.target),s=document.createElement("div");s.className="vanilla-agent-host";let t=(y=(c=(u=n.config)==null?void 0:u.launcher)==null?void 0:c.enabled)!=null?y:!0;t||(s.style.height="100%"),e.appendChild(s);let r=n.useShadowDom===!0,o,i;if(r){let b=s.attachShadow({mode:"open"});i=b,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"),b.appendChild(o),$o(b)}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),$o(s);let l=$n(o,n.config,{debugTools:n.debugTools});(m=n.onReady)==null||m.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 hr(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function On(n){var e,s;return(s=(e=n.parserType)!=null?e:hr(n.streamParser))!=null?s:"plain"}function Oo(n,e="esm"){let s={...n};return delete s.postprocessMessage,delete s.initialMessages,e==="esm"?mr(s):e==="script-installer"?yr(s):e==="script-advanced"?br(s):e==="react-component"?fr(s):e==="react-advanced"?wr(s):vr(s)}function mr(n){let e=On(n),s=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
57
- `)}function fr(n){let e=On(n),s=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
58
- `)}function wr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
59
- `)}function yr(n){let e=On(n),s=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
60
- `)}function vr(n){let e=On(n),s=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
61
- `)}function br(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" }),"),e.push(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
62
- `)}var Cr=os;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_WIDGET_CONFIG,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,generateCodeSnippet,getHeaderLayout,hasComponentDirective,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,pluginRegistry,renderComponentDirective});
60
+ `}if(!he){let Jt="max-height: -moz-available !important; max-height: stretch !important;",Vt=i?"":"padding-top: 1.25em !important;";B.style.cssText+=Jt+Vt}};wt(),Yn(n,t);let $e=[],ot=Ro(ne),Ue=null,I,dt=!1,Se=!0,Oe=0,te=0,Ae=null,Te=!1,ze=0,Je=!1,xt=125,Bt=2e3,yt=5,Et=50,St=new Map,ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Ht=(ms=(hs=t.voiceRecognition)==null?void 0:hs.autoResume)!=null?ms:!1,Le=i=>{o.emit("voice:state",{active:ye.active,source:i,timestamp:Date.now()})},Ye=()=>{f(i=>({...i,voiceState:{active:ye.active,timestamp:Date.now(),manuallyDeactivated:ye.manuallyDeactivated}}))},At=()=>{var O,k;if(((O=t.voiceRecognition)==null?void 0:O.enabled)===!1)return;let i=as(l.voiceState),u=!!i.active,E=Number((k=i.timestamp)!=null?k:0);ye.manuallyDeactivated=!!i.manuallyDeactivated,u&&Date.now()-E<wr&&setTimeout(()=>{ye.active||(ye.manuallyDeactivated=!1,Ne("restore"))},1e3)},Dt=()=>I?Do(I.getMessages()).filter(i=>!i.__skipPersist):[];function Mt(i){if(!(a!=null&&a.save))return;let E={messages:i?Do(i):I?Dt():[],metadata:l};try{let O=a.save(E);O instanceof Promise&&O.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(O){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",O)}}let _t=(i=!1)=>{if(!Se)return;let u=Date.now();Te&&u<ze&&!i||(Te&&u>=ze&&(Te=!1),!(!i&&!dt)&&(u-te<xt||(te=u,Ae&&cancelAnimationFrame(Ae),Ae=requestAnimationFrame(()=>{Te||!Se||(Je=!0,K.scrollTop=K.scrollHeight,Oe=K.scrollTop,requestAnimationFrame(()=>{Je=!1}),Ae=null)}))))},Wt=null,wn=()=>B.querySelector("#vanilla-agent-scroll-container")||K,yn=(i,u=500)=>{let E=i.scrollTop,O=i.clientHeight,k=i.scrollHeight,ee=k-E;if(E+O>=k-2||Math.abs(ee)<5)return;Wt!==null&&(cancelAnimationFrame(Wt),Wt=null);let T=performance.now(),G=R=>1-Math.pow(1-R,3),z=R=>{let Y=i.scrollHeight;Y!==k&&(k=Y,ee=k-E);let Be=R-T,he=Math.min(Be/u,1),ae=G(he),Ie=E+ee*ae;i.scrollTop=Ie,he<1?Wt=requestAnimationFrame(z):(i.scrollTop=i.scrollHeight,Wt=null)};Wt=requestAnimationFrame(z)},vn=i=>{let u=new Map;i.forEach(E=>{let O=St.get(E.id);u.set(E.id,{streaming:E.streaming,role:E.role}),!O&&E.role==="assistant"&&o.emit("assistant:message",E),E.role==="assistant"&&(O!=null&&O.streaming)&&E.streaming===!1&&o.emit("assistant:complete",E)}),St.clear(),u.forEach((E,O)=>{St.set(O,E)})},jt=(i,u,E)=>{i.innerHTML="";let O=document.createDocumentFragment();u.forEach(T=>{var Be,he;let G=null,z=r.find(ae=>!!(T.variant==="reasoning"&&ae.renderReasoning||T.variant==="tool"&&ae.renderToolCall||!T.variant&&ae.renderMessage)),R=(Be=t.layout)==null?void 0:Be.messages;if(z)if(T.variant==="reasoning"&&T.reasoning&&z.renderReasoning){if(!v)return;G=z.renderReasoning({message:T,defaultRenderer:()=>es(T),config:t})}else if(T.variant==="tool"&&T.toolCall&&z.renderToolCall){if(!D)return;G=z.renderToolCall({message:T,defaultRenderer:()=>ns(T,t),config:t})}else z.renderMessage&&(G=z.renderMessage({message:T,defaultRenderer:()=>{let ae=tn(T,E,R,t.messageActions,x);return T.role!=="user"&&ss(ae,T,t,I),ae},config:t}));if(!G&&T.role==="assistant"&&!T.variant&&t.enableComponentStreaming!==!1&&Fn(T)){let Ie=Nn(T);if(Ie){let ct=$n(Ie,{config:t,message:T,transform:E});if(ct){let le=document.createElement("div");if(le.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),le.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let ut=document.createElement("div");ut.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ut.innerHTML=E({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),le.appendChild(ut)}le.appendChild(ct),G=le}}}if(!G)if(T.variant==="reasoning"&&T.reasoning){if(!v)return;G=es(T)}else if(T.variant==="tool"&&T.toolCall){if(!D)return;G=ns(T,t)}else{let ae=(he=t.layout)==null?void 0:he.messages;ae!=null&&ae.renderUserMessage&&T.role==="user"?G=ae.renderUserMessage({message:T,config:t,streaming:!!T.streaming}):ae!=null&&ae.renderAssistantMessage&&T.role==="assistant"?G=ae.renderAssistantMessage({message:T,config:t,streaming:!!T.streaming}):G=tn(T,E,ae,t.messageActions,x),T.role!=="user"&&G&&ss(G,T,t,I)}let Y=document.createElement("div");Y.className="tvw-flex",T.role==="user"&&Y.classList.add("tvw-justify-end"),Y.appendChild(G),O.appendChild(Y)});let k=u.some(T=>T.role==="assistant"&&T.streaming),ee=u[u.length-1],N=(ee==null?void 0:ee.role)==="assistant"&&!ee.streaming;if(dt&&u.some(T=>T.role==="user")&&!k&&!N){let T=gn(),G=document.createElement("div");G.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),G.appendChild(T);let z=document.createElement("div");z.className="tvw-flex",z.appendChild(G),O.appendChild(z)}i.appendChild(O),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let T=wn();yn(T)})})},qt=()=>{g&&(b?(B.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-95","tvw-opacity-0"),_.classList.add("tvw-scale-100","tvw-opacity-100"),y?y.element.style.display="none":F&&(F.style.display="none")):(B.classList.add("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-100","tvw-opacity-100"),_.classList.add("tvw-scale-95","tvw-opacity-0"),y?y.element.style.display="":F&&(F.style.display="")))},Ke=(i,u="user")=>{if(!g||b===i)return;let E=b;b=i,qt(),b&&(be(),_t(!0));let O={open:b,source:u,timestamp:Date.now()};b&&!E?o.emit("widget:opened",O):!b&&E&&o.emit("widget:closed",O),o.emit("widget:state",{open:b,launcherEnabled:g,voiceActive:ye.active,streaming:I.isStreaming()})},Xt=i=>{q.disabled=i,H&&(H.disabled=i),ot.buttons.forEach(u=>{u.disabled=i})},rn=()=>{var k,ee,N,T,G,z,R,Y,Be,he,ae,Ie,ct,le;bt.textContent=(ee=(k=t.copy)==null?void 0:k.welcomeTitle)!=null?ee:"Hello \u{1F44B}",Ct.textContent=(T=(N=t.copy)==null?void 0:N.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",re.placeholder=(z=(G=t.copy)==null?void 0:G.inputPlaceholder)!=null?z:"How can I help...",((Y=(R=t.sendButton)==null?void 0:R.useIcon)!=null?Y:!1)||(q.textContent=(he=(Be=t.copy)==null?void 0:Be.sendButtonLabel)!=null?he:"Send");let u=(Ie=(ae=t.theme)==null?void 0:ae.inputFontFamily)!=null?Ie:"sans-serif",E=(le=(ct=t.theme)==null?void 0:ct.inputFontWeight)!=null?le:"400",O=ut=>{switch(ut){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};re.style.fontFamily=O(u),re.style.fontWeight=E};I=new Zt(t,{onMessagesChanged(i){jt(Q,i,W),I&&(i.some(O=>O.role==="user")?ot.render([],I,re,i):ot.render(t.suggestionChips,I,re,i,t.suggestionChipsConfig)),_t(!dt),vn(i);let u=[...i].reverse().find(E=>E.role==="user");ye.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Mt(i)},onStatusChanged(i){var O;let u=(O=t.statusIndicator)!=null?O:{},E=k=>{var ee,N,T,G;return k==="idle"?(ee=u.idleText)!=null?ee:Xe.idle:k==="connecting"?(N=u.connectingText)!=null?N:Xe.connecting:k==="connected"?(T=u.connectedText)!=null?T:Xe.connected:k==="error"?(G=u.errorText)!=null?G:Xe.error:Xe[k]};nt.textContent=E(i)},onStreamingChanged(i){dt=i,Xt(i),I&&jt(Q,I.getMessages(),W),i||_t(!0)}}),p&&p.then(i=>{var u;i&&(i.metadata&&(l=as(i.metadata),C.syncFromMetadata()),(u=i.messages)!=null&&u.length&&I.hydrateMessages(i.messages))}).catch(i=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)});let an=i=>{i.preventDefault();let u=re.value.trim();u&&(re.value="",I.sendMessage(u))},ln=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),q.click())},A=null,V=!1,ie=null,ve=null,Fe=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ne=(i="user")=>{var ee,N,T,G;if(V||I.isStreaming())return;let u=Fe();if(!u)return;A=new u;let O=(N=((ee=t.voiceRecognition)!=null?ee:{}).pauseDuration)!=null?N:2e3;A.continuous=!0,A.interimResults=!0,A.lang="en-US";let k=re.value;A.onresult=z=>{let R="",Y="";for(let he=0;he<z.results.length;he++){let ae=z.results[he],Ie=ae[0].transcript;ae.isFinal?R+=Ie+" ":Y=Ie}let Be=k+R+Y;re.value=Be,ie&&clearTimeout(ie),(R||Y)&&(ie=window.setTimeout(()=>{let he=re.value.trim();he&&A&&V&&(ue(),re.value="",I.sendMessage(he,{viaVoice:!0}))},O))},A.onerror=z=>{z.error!=="no-speech"&&ue()},A.onend=()=>{if(V){let z=re.value.trim();z&&z!==k.trim()&&(re.value="",I.sendMessage(z,{viaVoice:!0})),ue()}};try{if(A.start(),V=!0,ye.active=!0,i!=="system"&&(ye.manuallyDeactivated=!1),Le(i),Ye(),H){ve={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor};let z=(T=t.voiceRecognition)!=null?T:{},R=(G=z.recordingBackgroundColor)!=null?G:"#ef4444",Y=z.recordingIconColor,Be=z.recordingBorderColor;if(H.classList.add("tvw-voice-recording"),H.style.backgroundColor=R,Y){H.style.color=Y;let he=H.querySelector("svg");he&&he.setAttribute("stroke",Y)}Be&&(H.style.borderColor=Be),H.setAttribute("aria-label","Stop voice recognition")}}catch{ue("system")}},ue=(i="user")=>{if(V){if(V=!1,ie&&(clearTimeout(ie),ie=null),A){try{A.stop()}catch{}A=null}if(ye.active=!1,Le(i),Ye(),H){if(H.classList.remove("tvw-voice-recording"),ve){H.style.backgroundColor=ve.backgroundColor,H.style.color=ve.color,H.style.borderColor=ve.borderColor;let u=H.querySelector("svg");u&&u.setAttribute("stroke",ve.color||"currentColor"),ve=null}H.setAttribute("aria-label","Start voice recognition")}}},P=(i,u)=>{var Ie,ct,le,ut,Pt,Rt,kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let O=m("div","tvw-send-button-wrapper"),k=m("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");k.type="button",k.setAttribute("aria-label","Start voice recognition");let ee=(Ie=i==null?void 0:i.iconName)!=null?Ie:"mic",N=(ct=u==null?void 0:u.size)!=null?ct:"40px",T=(le=i==null?void 0:i.iconSize)!=null?le:N,G=parseFloat(T)||24,z=(ut=i==null?void 0:i.backgroundColor)!=null?ut:u==null?void 0:u.backgroundColor,R=(Pt=i==null?void 0:i.iconColor)!=null?Pt:u==null?void 0:u.textColor;k.style.width=T,k.style.height=T,k.style.minWidth=T,k.style.minHeight=T,k.style.fontSize="18px",k.style.lineHeight="1";let Y=R||"currentColor",Be=ce(ee,G,Y,1.5);Be?(k.appendChild(Be),k.style.color=Y):(k.textContent="\u{1F3A4}",k.style.color=Y),z?k.style.backgroundColor=z:k.classList.add("tvw-bg-cw-primary"),R?k.style.color=R:!R&&!(u!=null&&u.textColor)&&k.classList.add("tvw-text-white"),i!=null&&i.borderWidth&&(k.style.borderWidth=i.borderWidth,k.style.borderStyle="solid"),i!=null&&i.borderColor&&(k.style.borderColor=i.borderColor),i!=null&&i.paddingX&&(k.style.paddingLeft=i.paddingX,k.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(k.style.paddingTop=i.paddingY,k.style.paddingBottom=i.paddingY),O.appendChild(k);let he=(Rt=i==null?void 0:i.tooltipText)!=null?Rt:"Start voice recognition";if(((kt=i==null?void 0:i.showTooltip)!=null?kt:!1)&&he){let Ut=m("div","tvw-send-button-tooltip");Ut.textContent=he,O.appendChild(Ut)}return{micButton:k,micButtonWrapper:O}},rt=()=>{if(V){let i=re.value.trim();ye.manuallyDeactivated=!0,Ye(),ue("user"),i&&(re.value="",I.sendMessage(i))}else ye.manuallyDeactivated=!1,Ye(),Ne("user")};H&&(H.addEventListener("click",rt),$e.push(()=>{ue("system"),H&&H.removeEventListener("click",rt)}));let se=o.on("assistant:complete",()=>{Ht&&(ye.active||ye.manuallyDeactivated||Ht==="assistant"&&!ye.lastUserMessageWasVoice||setTimeout(()=>{!ye.active&&!ye.manuallyDeactivated&&Ne("auto")},600))});$e.push(se);let M=()=>{Ke(!b,"user")},y=null,F=null;if(g){let i=r.find(u=>u.renderLauncher);if(i!=null&&i.renderLauncher){let u=i.renderLauncher({config:t,defaultRenderer:()=>pn(t,M).element,onToggle:M});u&&(F=u)}F||(y=pn(t,M))}y?n.appendChild(y.element):F&&n.appendChild(F),qt(),ot.render(t.suggestionChips,I,re,void 0,t.suggestionChipsConfig),rn(),Xt(I.isStreaming()),_t(!0),At();let be=()=>{var E,O,k,ee,N,T,G,z;let i=(O=(E=t.launcher)==null?void 0:E.sidebarMode)!=null?O:!1,u=i||((ee=(k=t.launcher)==null?void 0:k.fullHeight)!=null?ee:!1);if(!g){_.style.height="",_.style.width="";return}if(!i){let R=(T=(N=t==null?void 0:t.launcher)==null?void 0:N.width)!=null?T:t==null?void 0:t.launcherWidth,Y=R!=null?R:"min(400px, calc(100vw - 24px))";_.style.width=Y,_.style.maxWidth=Y}if(!u){let R=window.innerHeight,Y=64,Be=(z=(G=t.launcher)==null?void 0:G.heightOffset)!=null?z:0,he=Math.max(200,R-Y),ae=Math.min(640,he),Ie=Math.max(200,ae-Be);_.style.height=`${Ie}px`}};be(),window.addEventListener("resize",be),$e.push(()=>window.removeEventListener("resize",be)),Oe=K.scrollTop;let Ee=()=>{let i=K.scrollTop,u=K.scrollHeight,E=K.clientHeight,O=u-i-E,k=Math.abs(i-Oe);if(Oe=i,!Je&&!(k<=yt)){if(!Se&&O<Et){Te=!1,Se=!0;return}Se&&O>Et&&(Te=!0,ze=Date.now()+Bt,Se=!1)}};K.addEventListener("scroll",Ee,{passive:!0}),$e.push(()=>K.removeEventListener("scroll",Ee)),$e.push(()=>{Ae&&cancelAnimationFrame(Ae)});let Ze=()=>{J&&(Ue&&(J.removeEventListener("click",Ue),Ue=null),g?(J.style.display="",Ue=()=>{b=!1,qt()},J.addEventListener("click",Ue)):J.style.display="none")};Ze(),(()=>{let{clearChatButton:i}=Z;i&&i.addEventListener("click",()=>{I.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let u=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),a!=null&&a.clear)try{let E=a.clear();E instanceof Promise&&E.catch(O=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",O)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},C.syncFromMetadata()})})(),Ve.addEventListener("submit",an),re.addEventListener("keydown",ln),$e.push(()=>{Ve.removeEventListener("submit",an),re.removeEventListener("keydown",ln)}),$e.push(()=>{I.cancel()}),y?$e.push(()=>{y==null||y.destroy()}):F&&$e.push(()=>{F==null||F.remove()});let Ce={update(i){var dn,Jt,Vt,ws,ys,vs,bs,Cs,xs,Ss,As,Ts,Es,Ms,Ws,ks,Ls,Bs,Hs,Ps,Rs,Is,$s,Fs,Ns,Os,Ds,_s,js,qs,Us,zs,Js,Ys,Ks,Xs,Vs,Gs,Zs,Qs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,ho,mo,fo,wo;let u=t.toolCall;t={...t,...i},wt(),Yn(n,t);let E=hn.getForInstance(t.plugins);if(r.length=0,r.push(...E),g=(Jt=(dn=t.launcher)==null?void 0:dn.enabled)!=null?Jt:!0,U=(ws=(Vt=t.launcher)==null?void 0:Vt.autoExpand)!=null?ws:!1,v=(vs=(ys=t.features)==null?void 0:ys.showReasoning)!=null?vs:!0,D=(Cs=(bs=t.features)==null?void 0:bs.showToolCalls)!=null?Cs:!0,((xs=t.launcher)==null?void 0:xs.enabled)===!1&&y&&(y.destroy(),y=null),((Ss=t.launcher)==null?void 0:Ss.enabled)===!1&&F&&(F.remove(),F=null),((As=t.launcher)==null?void 0:As.enabled)!==!1&&!y&&!F){let L=r.find(we=>we.renderLauncher);if(L!=null&&L.renderLauncher){let we=L.renderLauncher({config:t,defaultRenderer:()=>pn(t,M).element,onToggle:M});we&&(F=we,n.appendChild(F))}F||(y=pn(t,M),n.appendChild(y.element))}y&&y.update(t),mt&&((Ts=t.launcher)==null?void 0:Ts.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((Es=t.launcher)==null?void 0:Es.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),g!==h?g?Ke(U,"auto"):(b=!0,qt()):U!==$&&Ke(U,"auto"),$=U,h=g,be(),Ze(),JSON.stringify(i.toolCall)!==JSON.stringify(u)&&I&&jt(Q,I.getMessages(),W);let N=(Ms=t.launcher)!=null?Ms:{},T=(Ws=N.headerIconHidden)!=null?Ws:!1,G=N.headerIconName,z=(ks=N.headerIconSize)!=null?ks:"48px";if(fe){let L=j.querySelector(".tvw-border-b-cw-divider"),we=L==null?void 0:L.querySelector(".tvw-flex-col");if(T)fe.style.display="none",L&&we&&!L.contains(we)&&L.insertBefore(we,L.firstChild);else{if(fe.style.display="",fe.style.height=z,fe.style.width=z,L&&we&&(L.contains(fe)?fe.nextSibling!==we&&(fe.remove(),L.insertBefore(fe,we)):L.insertBefore(fe,we)),G){let We=parseFloat(z)||24,xe=ce(G,We*.6,"#ffffff",2);xe?fe.replaceChildren(xe):fe.textContent=(Ls=N.agentIconText)!=null?Ls:"\u{1F4AC}"}else if(N.iconUrl){let We=fe.querySelector("img");if(We)We.src=N.iconUrl,We.style.height=z,We.style.width=z;else{let xe=document.createElement("img");xe.src=N.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=z,xe.style.width=z,fe.replaceChildren(xe)}}else{let We=fe.querySelector("svg"),xe=fe.querySelector("img");(We||xe)&&fe.replaceChildren(),fe.textContent=(Bs=N.agentIconText)!=null?Bs:"\u{1F4AC}"}let oe=fe.querySelector("img");oe&&(oe.style.height=z,oe.style.width=z)}}if(J){let L=(Hs=N.closeButtonSize)!=null?Hs:"32px",we=(Ps=N.closeButtonPlacement)!=null?Ps:"inline";J.style.height=L,J.style.width=L;let{closeButtonWrapper:oe}=Z,We=we==="top-right",xe=oe==null?void 0:oe.classList.contains("tvw-absolute");if(oe&&We!==xe)if(oe.remove(),We)oe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",j.style.position="relative",j.appendChild(oe);else{let me=(Is=(Rs=N.clearChat)==null?void 0:Rs.placement)!=null?Is:"inline",et=(Fs=($s=N.clearChat)==null?void 0:$s.enabled)!=null?Fs:!0;oe.className=et&&me==="inline"?"":"tvw-ml-auto";let tt=j.querySelector(".tvw-border-b-cw-divider");tt&&tt.appendChild(oe)}if(N.closeButtonColor?(J.style.color=N.closeButtonColor,J.classList.remove("tvw-text-cw-muted")):(J.style.color="",J.classList.add("tvw-text-cw-muted")),N.closeButtonBackgroundColor?(J.style.backgroundColor=N.closeButtonBackgroundColor,J.classList.remove("hover:tvw-bg-gray-100")):(J.style.backgroundColor="",J.classList.add("hover:tvw-bg-gray-100")),N.closeButtonBorderWidth||N.closeButtonBorderColor){let me=N.closeButtonBorderWidth||"0px",et=N.closeButtonBorderColor||"transparent";J.style.border=`${me} solid ${et}`,J.classList.remove("tvw-border-none")}else J.style.border="",J.classList.add("tvw-border-none");N.closeButtonBorderRadius?(J.style.borderRadius=N.closeButtonBorderRadius,J.classList.remove("tvw-rounded-full")):(J.style.borderRadius="",J.classList.add("tvw-rounded-full")),N.closeButtonPaddingX?(J.style.paddingLeft=N.closeButtonPaddingX,J.style.paddingRight=N.closeButtonPaddingX):(J.style.paddingLeft="",J.style.paddingRight=""),N.closeButtonPaddingY?(J.style.paddingTop=N.closeButtonPaddingY,J.style.paddingBottom=N.closeButtonPaddingY):(J.style.paddingTop="",J.style.paddingBottom="");let Qe=(Ns=N.closeButtonIconName)!=null?Ns:"x",je=(Os=N.closeButtonIconText)!=null?Os:"\xD7";J.innerHTML="";let gt=ce(Qe,"20px",N.closeButtonColor||"",2);gt?J.appendChild(gt):J.textContent=je;let Nt=(Ds=N.closeButtonTooltipText)!=null?Ds:"Close chat",Me=(_s=N.closeButtonShowTooltip)!=null?_s:!0;if(J.setAttribute("aria-label",Nt),oe&&(oe._cleanupTooltip&&(oe._cleanupTooltip(),delete oe._cleanupTooltip),Me&&Nt)){let me=null,et=()=>{if(me||!J)return;me=m("div","tvw-clear-chat-tooltip"),me.textContent=Nt;let Gt=m("div");Gt.className="tvw-clear-chat-tooltip-arrow",me.appendChild(Gt);let Un=J.getBoundingClientRect();me.style.position="fixed",me.style.left=`${Un.left+Un.width/2}px`,me.style.top=`${Un.top-8}px`,me.style.transform="translate(-50%, -100%)",document.body.appendChild(me)},tt=()=>{me&&me.parentNode&&(me.parentNode.removeChild(me),me=null)};oe.addEventListener("mouseenter",et),oe.addEventListener("mouseleave",tt),J.addEventListener("focus",et),J.addEventListener("blur",tt),oe._cleanupTooltip=()=>{tt(),oe&&(oe.removeEventListener("mouseenter",et),oe.removeEventListener("mouseleave",tt)),J&&(J.removeEventListener("focus",et),J.removeEventListener("blur",tt))}}}let{clearChatButton:R,clearChatButtonWrapper:Y}=Z;if(R){let L=(js=N.clearChat)!=null?js:{},we=(qs=L.enabled)!=null?qs:!0,oe=(Us=L.placement)!=null?Us:"inline";if(Y){Y.style.display=we?"":"none";let We=oe==="top-right",xe=Y.classList.contains("tvw-absolute");if(We!==xe&&we){if(Y.remove(),We)Y.className="tvw-absolute tvw-top-4 tvw-z-50",Y.style.right="48px",j.style.position="relative",j.appendChild(Y);else{Y.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Y.style.right="";let je=j.querySelector(".tvw-border-b-cw-divider"),gt=Z.closeButtonWrapper;je&&gt&&gt.parentElement===je?je.insertBefore(Y,gt):je&&je.appendChild(Y)}let Qe=Z.closeButtonWrapper;Qe&&!Qe.classList.contains("tvw-absolute")&&(We?Qe.classList.add("tvw-ml-auto"):Qe.classList.remove("tvw-ml-auto"))}}if(we){let We=(zs=L.size)!=null?zs:"32px";R.style.height=We,R.style.width=We;let xe=(Js=L.iconName)!=null?Js:"refresh-cw",Qe=(Ys=L.iconColor)!=null?Ys:"";R.innerHTML="";let je=ce(xe,"20px",Qe||"",2);if(je&&R.appendChild(je),Qe?(R.style.color=Qe,R.classList.remove("tvw-text-cw-muted")):(R.style.color="",R.classList.add("tvw-text-cw-muted")),L.backgroundColor?(R.style.backgroundColor=L.backgroundColor,R.classList.remove("hover:tvw-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let Me=L.borderWidth||"0px",me=L.borderColor||"transparent";R.style.border=`${Me} solid ${me}`,R.classList.remove("tvw-border-none")}else R.style.border="",R.classList.add("tvw-border-none");L.borderRadius?(R.style.borderRadius=L.borderRadius,R.classList.remove("tvw-rounded-full")):(R.style.borderRadius="",R.classList.add("tvw-rounded-full")),L.paddingX?(R.style.paddingLeft=L.paddingX,R.style.paddingRight=L.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),L.paddingY?(R.style.paddingTop=L.paddingY,R.style.paddingBottom=L.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let gt=(Ks=L.tooltipText)!=null?Ks:"Clear chat",Nt=(Xs=L.showTooltip)!=null?Xs:!0;if(R.setAttribute("aria-label",gt),Y&&(Y._cleanupTooltip&&(Y._cleanupTooltip(),delete Y._cleanupTooltip),Nt&&gt)){let Me=null,me=()=>{if(Me||!R)return;Me=m("div","tvw-clear-chat-tooltip"),Me.textContent=gt;let tt=m("div");tt.className="tvw-clear-chat-tooltip-arrow",Me.appendChild(tt);let Gt=R.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${Gt.left+Gt.width/2}px`,Me.style.top=`${Gt.top-8}px`,Me.style.transform="translate(-50%, -100%)",document.body.appendChild(Me)},et=()=>{Me&&Me.parentNode&&(Me.parentNode.removeChild(Me),Me=null)};Y.addEventListener("mouseenter",me),Y.addEventListener("mouseleave",et),R.addEventListener("focus",me),R.addEventListener("blur",et),Y._cleanupTooltip=()=>{et(),Y&&(Y.removeEventListener("mouseenter",me),Y.removeEventListener("mouseleave",et)),R&&(R.removeEventListener("focus",me),R.removeEventListener("blur",et))}}}}let Be=t.actionParsers&&t.actionParsers.length?t.actionParsers:[mn],he=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Kt.message,Kt.messageAndClick];C=fn({parsers:Be,handlers:he,getMetadata:c,updateMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),W=_o(t,C),I.updateConfig(t),jt(Q,I.getMessages(),W),ot.render(t.suggestionChips,I,re,void 0,t.suggestionChipsConfig),rn(),Xt(I.isStreaming());let ae=((Vs=t.voiceRecognition)==null?void 0:Vs.enabled)===!0,Ie=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ct=ae&&Ie;if(Ve.classList.remove("tvw-gap-1","tvw-gap-3"),Ve.classList.add(ct?"tvw-gap-1":"tvw-gap-3"),ae&&Ie)if(!H||!He){let L=P(t.voiceRecognition,t.sendButton);L&&(H=L.micButton,He=L.micButtonWrapper,Ve.insertBefore(He,qe),H.addEventListener("click",rt),H.disabled=I.isStreaming())}else{let L=(Gs=t.voiceRecognition)!=null?Gs:{},we=(Zs=t.sendButton)!=null?Zs:{},oe=(Qs=L.iconName)!=null?Qs:"mic",We=(eo=we.size)!=null?eo:"40px",xe=(to=L.iconSize)!=null?to:We,Qe=parseFloat(xe)||24;H.style.width=xe,H.style.height=xe,H.style.minWidth=xe,H.style.minHeight=xe;let je=(so=(no=L.iconColor)!=null?no:we.textColor)!=null?so:"currentColor";H.innerHTML="";let gt=ce(oe,Qe,je,2);gt?H.appendChild(gt):H.textContent="\u{1F3A4}";let Nt=(oo=L.backgroundColor)!=null?oo:we.backgroundColor;Nt?(H.style.backgroundColor=Nt,H.classList.remove("tvw-bg-cw-primary")):(H.style.backgroundColor="",H.classList.add("tvw-bg-cw-primary")),je?(H.style.color=je,H.classList.remove("tvw-text-white")):!je&&!we.textColor&&(H.style.color="",H.classList.add("tvw-text-white")),L.borderWidth?(H.style.borderWidth=L.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),L.borderColor?H.style.borderColor=L.borderColor:H.style.borderColor="",L.paddingX?(H.style.paddingLeft=L.paddingX,H.style.paddingRight=L.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),L.paddingY?(H.style.paddingTop=L.paddingY,H.style.paddingBottom=L.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Me=He==null?void 0:He.querySelector(".tvw-send-button-tooltip"),me=(ro=L.tooltipText)!=null?ro:"Start voice recognition";if(((io=L.showTooltip)!=null?io:!1)&&me)if(Me)Me.textContent=me,Me.style.display="";else{let tt=document.createElement("div");tt.className="tvw-send-button-tooltip",tt.textContent=me,He==null||He.insertBefore(tt,H)}else Me&&(Me.style.display="none");He.style.display="",H.disabled=I.isStreaming()}else H&&He&&(He.style.display="none",V&&ue());let le=(ao=t.sendButton)!=null?ao:{},ut=(lo=le.useIcon)!=null?lo:!1,Pt=(co=le.iconText)!=null?co:"\u2191",Rt=le.iconName,kt=(uo=le.tooltipText)!=null?uo:"Send message",Ut=(po=le.showTooltip)!=null?po:!1,It=(go=le.size)!=null?go:"40px",zt=le.backgroundColor,pt=le.textColor;if(ut){if(q.style.width=It,q.style.height=It,q.style.minWidth=It,q.style.minHeight=It,q.style.fontSize="18px",q.style.lineHeight="1",q.innerHTML="",Rt){let L=parseFloat(It)||24,we=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",oe=ce(Rt,L,we,2);oe?(q.appendChild(oe),q.style.color=we):(q.textContent=Pt,pt?q.style.color=pt:q.classList.add("tvw-text-white"))}else q.textContent=Pt,pt?q.style.color=pt:q.classList.add("tvw-text-white");q.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",zt?(q.style.backgroundColor=zt,q.classList.remove("tvw-bg-cw-primary")):q.classList.add("tvw-bg-cw-primary")}else q.textContent=(mo=(ho=t.copy)==null?void 0:ho.sendButtonLabel)!=null?mo:"Send",q.style.width="",q.style.height="",q.style.minWidth="",q.style.minHeight="",q.style.fontSize="",q.style.lineHeight="",q.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",zt?(q.style.backgroundColor=zt,q.classList.remove("tvw-bg-cw-accent")):q.classList.add("tvw-bg-cw-accent"),pt?q.style.color=pt:q.classList.add("tvw-text-white");le.borderWidth?(q.style.borderWidth=le.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),le.borderColor?q.style.borderColor=le.borderColor:q.style.borderColor="",le.paddingX?(q.style.paddingLeft=le.paddingX,q.style.paddingRight=le.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),le.paddingY?(q.style.paddingTop=le.paddingY,q.style.paddingBottom=le.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let $t=qe==null?void 0:qe.querySelector(".tvw-send-button-tooltip");if(Ut&&kt)if($t)$t.textContent=kt,$t.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=kt,qe==null||qe.insertBefore(L,q)}else $t&&($t.style.display="none");let Ft=(fo=t.statusIndicator)!=null?fo:{},bn=(wo=Ft.visible)!=null?wo:!0;if(nt.style.display=bn?"":"none",I){let L=I.getStatus(),we=oe=>{var We,xe,Qe,je;return oe==="idle"?(We=Ft.idleText)!=null?We:Xe.idle:oe==="connecting"?(xe=Ft.connectingText)!=null?xe:Xe.connecting:oe==="connected"?(Qe=Ft.connectedText)!=null?Qe:Xe.connected:oe==="error"?(je=Ft.errorText)!=null?je:Xe.error:Xe[oe]};nt.textContent=we(L)}},open(){g&&Ke(!0,"api")},close(){g&&Ke(!1,"api")},toggle(){g&&Ke(!b,"api")},clearChat(){I.clearMessages();try{localStorage.removeItem(on),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${on}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==on)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let i=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(i),a!=null&&a.clear)try{let u=a.clear();u instanceof Promise&&u.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}l={},C.syncFromMetadata()},setMessage(i){return!re||I.isStreaming()?!1:(!b&&g&&Ke(!0,"system"),re.value=i,re.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(I.isStreaming())return!1;let u=(i==null?void 0:i.trim())||re.value.trim();return u?(!b&&g&&Ke(!0,"system"),re.value="",I.sendMessage(u),!0):!1},startVoiceRecognition(){return V||I.isStreaming()||!Fe()?!1:(!b&&g&&Ke(!0,"system"),ye.manuallyDeactivated=!1,Ye(),Ne("user"),!0)},stopVoiceRecognition(){return V?(ye.manuallyDeactivated=!0,Ye(),ue("user"),!0):!1},injectTestMessage(i){!b&&g&&Ke(!0,"system"),I.injectTestEvent(i)},getMessages(){return I.getMessages()},getStatus(){return I.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(i){f(i)},on(i,u){return o.on(i,u)},off(i,u){o.off(i,u)},isOpen(){return g&&b},isVoiceActive(){return ye.active},getState(){return{open:g&&b,launcherEnabled:g,voiceActive:ye.active,streaming:I.isStreaming()}},showCSATFeedback(i){!b&&g&&Ke(!0,"system");let u=Q.querySelector(".tvw-feedback-container");u&&u.remove();let E=On({onSubmit:async(O,k)=>{var ee;I.isClientTokenMode()&&await I.submitCSATFeedback(O,k),(ee=i==null?void 0:i.onSubmit)==null||ee.call(i,O,k)},onDismiss:i==null?void 0:i.onDismiss,...i});Q.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!b&&g&&Ke(!0,"system");let u=Q.querySelector(".tvw-feedback-container");u&&u.remove();let E=Dn({onSubmit:async(O,k)=>{var ee;I.isClientTokenMode()&&await I.submitNPSFeedback(O,k),(ee=i==null?void 0:i.onSubmit)==null||ee.call(i,O,k)},onDismiss:i==null?void 0:i.onDismiss,...i});Q.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,u){return I.submitCSATFeedback(i,u)},async submitNPSFeedback(i,u){return I.submitNPSFeedback(i,u)},destroy(){$e.forEach(i=>i()),B.remove(),y==null||y.destroy(),F==null||F.remove(),Ue&&J.removeEventListener("click",Ue)}};if((((fs=s==null?void 0:s.debugTools)!=null?fs:!1)||!!t.debug)&&typeof window!="undefined"){let i=window.AgentWidgetBrowser,u={controller:Ce,getMessages:Ce.getMessages,getStatus:Ce.getStatus,getMetadata:Ce.getPersistentMetadata,updateMetadata:Ce.updatePersistentMetadata,clearHistory:()=>Ce.clearChat(),setVoiceActive:E=>E?Ce.startVoiceRecognition():Ce.stopVoiceRecognition()};window.AgentWidgetBrowser=u,$e.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=i)})}return Ce};var ls={},yr=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},vr=()=>{try{if(typeof ls!="undefined"&&ls.url)return new URL("../widget.css",ls.url).href}catch{}return null},jo=n=>{let e=vr(),s=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let r=t.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else s();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},ds=n=>{var c,f,w,d;let e=yr(n.target),s=document.createElement("div");s.className="vanilla-agent-host";let t=(w=(f=(c=n.config)==null?void 0:c.launcher)==null?void 0:f.enabled)!=null?w:!0;t||(s.style.height="100%"),e.appendChild(s);let r=n.useShadowDom===!0,o,a;if(r){let C=s.attachShadow({mode:"open"});a=C,o=document.createElement("div"),o.id="vanilla-agent-root",t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),C.appendChild(o),jo(C)}else a=s,o=document.createElement("div"),o.id="vanilla-agent-root",t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),s.appendChild(o),jo(s);let l=_n(o,n.config,{debugTools:n.debugTools});(d=n.onReady)==null||d.call(n);let p={...l,host:s,destroy(){l.destroy(),s.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=p),p};function br(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function jn(n){var e,s;return(s=(e=n.parserType)!=null?e:br(n.streamParser))!=null?s:"plain"}function qo(n,e="esm"){let s={...n};return delete s.postprocessMessage,delete s.initialMessages,e==="esm"?Cr(s):e==="script-installer"?Ar(s):e==="script-advanced"?Er(s):e==="react-component"?xr(s):e==="react-advanced"?Sr(s):Tr(s)}function Cr(n){let e=jn(n),s=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
61
+ `)}function xr(n){let e=jn(n),s=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
62
+ `)}function Sr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
63
+ `)}function Ar(n){let e=jn(n),s=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
64
+ `)}function Tr(n){let e=jn(n),s=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),s&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
65
+ `)}function Er(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([s,t])=>{e.push(` ${s}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"?e.push(` ${s}: ${t},`):typeof t=="number"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,t])=>{typeof t=="string"?e.push(` ${s}: "${t}",`):typeof t=="boolean"&&e.push(` ${s}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([s,t])=>{e.push(` ${s}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{e.push(` "${s}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" }),"),e.push(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
66
+ `)}var Mr=ds;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_WIDGET_CONFIG,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getHeaderLayout,hasComponentDirective,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,pluginRegistry,renderComponentDirective});
63
67
  //# sourceMappingURL=index.cjs.map