vanilla-agent 1.7.0 → 1.7.2

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,9 +1,9 @@
1
- "use strict";var $o=Object.create;var tn=Object.defineProperty;var _o=Object.getOwnPropertyDescriptor;var jo=Object.getOwnPropertyNames;var Uo=Object.getPrototypeOf,Vo=Object.prototype.hasOwnProperty;var Ko=(t,n)=>{for(var r in n)tn(t,r,{get:n[r],enumerable:!0})},Mo=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of jo(n))!Vo.call(t,o)&&o!==r&&tn(t,o,{get:()=>n[o],enumerable:!(e=_o(n,o))||e.enumerable});return t};var Xo=(t,n,r)=>(r=t!=null?$o(Uo(t)):{},Mo(n||!t||!t.__esModule?tn(r,"default",{value:t,enumerable:!0}):r,t)),Yo=t=>Mo(tn({},"__esModule",{value:!0}),t);var pr={};Ko(pr,{AgentWidgetClient:()=>Vt,AgentWidgetSession:()=>Jt,DEFAULT_WIDGET_CONFIG:()=>ot,createActionManager:()=>en,createAgentExperience:()=>cn,createJsonStreamParser:()=>an,createLocalStorageAdapter:()=>zo,createPlainTextParser:()=>rn,createRegexJsonParser:()=>sn,createXmlParser:()=>ln,default:()=>gr,defaultActionHandlers:()=>Kt,defaultJsonActionParser:()=>Qt,directivePostprocessor:()=>Wo,escapeHtml:()=>nn,initAgentWidget:()=>Wn,markdownPostprocessor:()=>pn,mergeWithDefaults:()=>dn,pluginRegistry:()=>Zt});module.exports=Yo(pr);var gn=require("marked");gn.marked.setOptions({breaks:!0});var pn=t=>gn.marked.parse(t),nn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Jo=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Eo=t=>`%%FORM_PLACEHOLDER_${t}%%`,Go=(t,n)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let i=JSON.parse(o.trim());if(i&&typeof i=="object"&&i.component==="form"&&i.type){let a=Eo(n.length);return n.push({token:a,type:String(i.type)}),a}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let i=Eo(n.length);return n.push({token:i,type:o}),i}),r},Wo=t=>{let n=[],r=Go(t,n),e=pn(r);return n.forEach(({token:o,type:i})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${Jo(i)}"></div>`;e=e.replace(a,v)}),e};var Yt=require("partial-json"),mn=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Zo=t=>{var a,w;let n=(a=t.completedAt)!=null?a:Date.now(),r=(w=t.startedAt)!=null?w:n,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Lo=t=>t.status==="complete"?Zo(t):t.status==="pending"?"Waiting":"",Qo=t=>{var o,i,a;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(i=t.startedAt)!=null?i:t.completedAt)!=null?a:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var ko=t=>t.status==="complete"?Qo(t):"Using tool...",er=()=>{let t=null,n=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,i=e.match(o);if(i&&i[1])try{return i[1].replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,w=e.match(a);if(w&&w[1])try{return w[1].replace(/\\n/g,`
3
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return w[1]}return null};return{getExtractedText:()=>t,processChunk:async e=>{if(e.length<=n)return t!==null?{text:t,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let i=r(e);return i!==null&&(t=i),n=e.length,t!==null?{text:t,raw:e}:null},close:async()=>{}}},on=t=>{try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},rn=()=>{let t={processChunk:n=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},sn=()=>{var n;let t=er();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(n=t.close)==null?void 0:n.bind(t)}},an=()=>{let t=null,n=0;return{getExtractedText:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t!==null?{text:t,raw:r}:null;try{let o=(0,Yt.parse)(r,Yt.STR|Yt.OBJ);o&&typeof o=="object"&&typeof o.text=="string"&&(t=o.text)}catch{}return n=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},ln=()=>{let t=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let e=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(t=e[1],{text:t,raw:n}):null},getExtractedText:()=>t}};var tr="https://api.travrse.ai/v1/dispatch";function nr(t){switch(t){case"json":return an;case"regex-json":return sn;case"xml":return ln;case"plain":default:return rn}}var Vt=class{constructor(n={}){this.config=n;var r,e,o;this.apiUrl=(r=n.apiUrl)!=null?r:tr,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(e=n.streamParser)!=null?e:nr(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware}async dispatch(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch body",o);let i=await fetch(this.apiUrl,{method:"POST",headers:this.headers,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(n){let e={messages:n.slice().sort((o,i)=>{let a=new Date(o.createdAt).getTime(),w=new Date(i.createdAt).getTime();return a-w}).map(o=>({role:o.role,content:o.content,createdAt:o.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async i=>{try{let a=await i({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async streamResponse(n,r){var Dt,Z,M,rt,xt,qt,st,se,E,ve,b,X,ze,ut,Qe,F,Ct,Oe,gt,Fe,Ve,D,ye,Et,J,it,Xt,mt,St,be,Wt,Lt,at,zt,Ot,kt,ft,lt,$t,_t,jt,wt,ht,$e,Tt,Bt,Rt,Ht,De,_e,dt,et,It,vt,Xe;let e=n.getReader(),o=new TextDecoder,i="",a=Date.now(),w=0,v=()=>a+w++,P=p=>{let _=p.reasoning?{...p.reasoning,chunks:[...p.reasoning.chunks]}:void 0,G=p.toolCall?{...p.toolCall,chunks:p.toolCall.chunks?[...p.toolCall.chunks]:void 0}:void 0,pe=p.tools?p.tools.map(O=>({...O,chunks:O.chunks?[...O.chunks]:void 0})):void 0;return{...p,reasoning:_,toolCall:G,tools:pe}},u=p=>{r({type:"message",message:P(p)})},I=null,k=new Map,q=new Map,L={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},R=p=>{if(p==null)return null;try{return String(p)}catch{return null}},y=p=>{var _,G,pe,O,xe;return R((xe=(O=(pe=(G=(_=p.stepId)!=null?_:p.step_id)!=null?G:p.step)!=null?pe:p.parentId)!=null?O:p.flowStepId)!=null?xe:p.flow_step_id)},B=p=>{var _,G,pe,O,xe,ce,h;return R((h=(ce=(xe=(O=(pe=(G=(_=p.callId)!=null?_:p.call_id)!=null?G:p.requestId)!=null?pe:p.request_id)!=null?O:p.toolCallId)!=null?xe:p.tool_call_id)!=null?ce:p.stepId)!=null?h:p.step_id)},g=()=>I||(I={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:v()},u(I),I),ke=(p,_)=>{L.lastId=_,p&&L.byStep.set(p,_)},re=(p,_)=>{var xe;let G=(xe=p.reasoningId)!=null?xe:p.id,pe=y(p);if(G){let ce=String(G);return ke(pe,ce),ce}if(pe){let ce=L.byStep.get(pe);if(ce)return L.lastId=ce,ce}if(L.lastId&&!_)return L.lastId;if(!_)return null;let O=`reason-${v()}`;return ke(pe,O),O},Ne=p=>{let _=k.get(p);if(_)return _;let G={id:`reason-${p}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:v(),reasoning:{id:p,status:"streaming",chunks:[]}};return k.set(p,G),u(G),G},Be=(p,_)=>{Q.lastId=_,p&&Q.byCall.set(p,_)},we=(p,_)=>{var xe;let G=(xe=p.toolId)!=null?xe:p.id,pe=B(p);if(G){let ce=String(G);return Be(pe,ce),ce}if(pe){let ce=Q.byCall.get(pe);if(ce)return Q.lastId=ce,ce}if(Q.lastId&&!_)return Q.lastId;if(!_)return null;let O=`tool-${v()}`;return Be(pe,O),O},ee=p=>{let _=q.get(p);if(_)return _;let G={id:`tool-${p}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:v(),toolCall:{id:p,status:"pending"}};return q.set(p,G),u(G),G},Ae=p=>{if(typeof p=="number"&&Number.isFinite(p))return p;if(typeof p=="string"){let _=Number(p);if(!Number.isNaN(_)&&Number.isFinite(_))return _;let G=Date.parse(p);if(!Number.isNaN(G))return G}return Date.now()},he=p=>{if(typeof p=="string")return p;if(p==null)return"";try{return JSON.stringify(p)}catch{return String(p)}},Y=new Map,ne=new Map;for(;;){let{done:p,value:_}=await e.read();if(p)break;i+=o.decode(_,{stream:!0});let G=i.split(`
1
+ "use strict";var $o=Object.create;var tn=Object.defineProperty;var jo=Object.getOwnPropertyDescriptor;var Uo=Object.getOwnPropertyNames;var Vo=Object.getPrototypeOf,Ko=Object.prototype.hasOwnProperty;var Xo=(t,n)=>{for(var r in n)tn(t,r,{get:n[r],enumerable:!0})},Mo=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Uo(n))!Ko.call(t,o)&&o!==r&&tn(t,o,{get:()=>n[o],enumerable:!(e=jo(n,o))||e.enumerable});return t};var Yo=(t,n,r)=>(r=t!=null?$o(Vo(t)):{},Mo(n||!t||!t.__esModule?tn(r,"default",{value:t,enumerable:!0}):r,t)),Jo=t=>Mo(tn({},"__esModule",{value:!0}),t);var mr={};Xo(mr,{AgentWidgetClient:()=>Kt,AgentWidgetSession:()=>Jt,DEFAULT_WIDGET_CONFIG:()=>ot,createActionManager:()=>en,createAgentExperience:()=>cn,createFlexibleJsonStreamParser:()=>Bo,createJsonStreamParser:()=>an,createLocalStorageAdapter:()=>Oo,createPlainTextParser:()=>rn,createRegexJsonParser:()=>sn,createXmlParser:()=>ln,default:()=>pr,defaultActionHandlers:()=>Xt,defaultJsonActionParser:()=>Qt,directivePostprocessor:()=>Wo,escapeHtml:()=>nn,initAgentWidget:()=>Wn,markdownPostprocessor:()=>pn,mergeWithDefaults:()=>dn,pluginRegistry:()=>Zt});module.exports=Jo(mr);var gn=require("marked");gn.marked.setOptions({breaks:!0});var pn=t=>gn.marked.parse(t),nn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Go=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Eo=t=>`%%FORM_PLACEHOLDER_${t}%%`,Zo=(t,n)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Eo(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=Eo(n.length);return n.push({token:s,type:o}),s}),r},Wo=t=>{let n=[],r=Zo(t,n),e=pn(r);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${Go(s)}"></div>`;e=e.replace(a,v)}),e};var Et=require("partial-json"),mn=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Qo=t=>{var a,m;let n=(a=t.completedAt)!=null?a:Date.now(),r=(m=t.startedAt)!=null?m:n,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Lo=t=>t.status==="complete"?Qo(t):t.status==="pending"?"Waiting":"",er=t=>{var o,s,a;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var ko=t=>t.status==="complete"?er(t):"Using tool...",tr=()=>{let t=null,n=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,m=e.match(a);if(m&&m[1])try{return m[1].replace(/\\n/g,`
3
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return m[1]}return null};return{getExtractedText:()=>t,processChunk:async e=>{if(e.length<=n)return t!==null?{text:t,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(t=s),n=e.length,t!==null?{text:t,raw:e}:null},close:async()=>{}}},on=t=>{try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},rn=()=>{let t={processChunk:n=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},sn=()=>{var n;let t=tr();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(n=t.close)==null?void 0:n.bind(t)}},an=()=>{let t=null,n=0;return{getExtractedText:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t!==null?{text:t,raw:r}:null;try{let o=(0,Et.parse)(r,Et.STR|Et.OBJ);o&&typeof o=="object"&&typeof o.text=="string"&&(t=o.text)}catch{}return n=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Bo=t=>{let n=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;if(s.action)switch(s.action){case"nav_then_click":return s.on_load_text||s.text||null;case"message":case"message_and_click":case"checkout":return s.text||null;default:return s.text||s.display_text||s.message||null}return s.text||s.display_text||s.message||s.content||null});return{getExtractedText:()=>n,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let m=(0,Et.parse)(s,Et.STR|Et.OBJ),v=o(m);v!==null&&(n=v)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},ln=()=>{let t=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let e=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(t=e[1],{text:t,raw:n}):null},getExtractedText:()=>t}};var nr="https://api.travrse.ai/v1/dispatch";function or(t){switch(t){case"json":return an;case"regex-json":return sn;case"xml":return ln;case"plain":default:return rn}}var Kt=class{constructor(n={}){this.config=n;var r,e,o;this.apiUrl=(r=n.apiUrl)!=null?r:nr,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(e=n.streamParser)!=null?e:or(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware}async dispatch(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch body",o);let s=await fetch(this.apiUrl,{method:"POST",headers:this.headers,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(n){let e={messages:n.slice().sort((o,s)=>{let a=new Date(o.createdAt).getTime(),m=new Date(s.createdAt).getTime();return a-m}).map(o=>({role:o.role,content:o.content,createdAt:o.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async streamResponse(n,r){var qt,Z,M,rt,bt,zt,st,se,E,ve,x,X,ze,ut,Qe,F,Ct,Oe,gt,Fe,Ve,D,ye,Wt,J,it,Yt,mt,St,xe,Lt,kt,at,Ot,_t,Bt,ft,lt,$t,jt,Ut,wt,ht,_e,Tt,Rt,Ht,It,De,$e,dt,et,Pt,vt,Xe;let e=n.getReader(),o=new TextDecoder,s="",a=Date.now(),m=0,v=()=>a+m++,P=p=>{let $=p.reasoning?{...p.reasoning,chunks:[...p.reasoning.chunks]}:void 0,G=p.toolCall?{...p.toolCall,chunks:p.toolCall.chunks?[...p.toolCall.chunks]:void 0}:void 0,pe=p.tools?p.tools.map(O=>({...O,chunks:O.chunks?[...O.chunks]:void 0})):void 0;return{...p,reasoning:$,toolCall:G,tools:pe}},u=p=>{r({type:"message",message:P(p)})},I=null,k=new Map,q=new Map,L={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},R=p=>{if(p==null)return null;try{return String(p)}catch{return null}},y=p=>{var $,G,pe,O,be;return R((be=(O=(pe=(G=($=p.stepId)!=null?$:p.step_id)!=null?G:p.step)!=null?pe:p.parentId)!=null?O:p.flowStepId)!=null?be:p.flow_step_id)},B=p=>{var $,G,pe,O,be,ce,h;return R((h=(ce=(be=(O=(pe=(G=($=p.callId)!=null?$:p.call_id)!=null?G:p.requestId)!=null?pe:p.request_id)!=null?O:p.toolCallId)!=null?be:p.tool_call_id)!=null?ce:p.stepId)!=null?h:p.step_id)},g=()=>I||(I={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:v()},u(I),I),ke=(p,$)=>{L.lastId=$,p&&L.byStep.set(p,$)},re=(p,$)=>{var be;let G=(be=p.reasoningId)!=null?be:p.id,pe=y(p);if(G){let ce=String(G);return ke(pe,ce),ce}if(pe){let ce=L.byStep.get(pe);if(ce)return L.lastId=ce,ce}if(L.lastId&&!$)return L.lastId;if(!$)return null;let O=`reason-${v()}`;return ke(pe,O),O},Ne=p=>{let $=k.get(p);if($)return $;let G={id:`reason-${p}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:v(),reasoning:{id:p,status:"streaming",chunks:[]}};return k.set(p,G),u(G),G},Be=(p,$)=>{Q.lastId=$,p&&Q.byCall.set(p,$)},we=(p,$)=>{var be;let G=(be=p.toolId)!=null?be:p.id,pe=B(p);if(G){let ce=String(G);return Be(pe,ce),ce}if(pe){let ce=Q.byCall.get(pe);if(ce)return Q.lastId=ce,ce}if(Q.lastId&&!$)return Q.lastId;if(!$)return null;let O=`tool-${v()}`;return Be(pe,O),O},ee=p=>{let $=q.get(p);if($)return $;let G={id:`tool-${p}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:v(),toolCall:{id:p,status:"pending"}};return q.set(p,G),u(G),G},Ae=p=>{if(typeof p=="number"&&Number.isFinite(p))return p;if(typeof p=="string"){let $=Number(p);if(!Number.isNaN($)&&Number.isFinite($))return $;let G=Date.parse(p);if(!Number.isNaN(G))return G}return Date.now()},he=p=>{if(typeof p=="string")return p;if(p==null)return"";try{return JSON.stringify(p)}catch{return String(p)}},Y=new Map,ne=new Map;for(;;){let{done:p,value:$}=await e.read();if(p)break;s+=o.decode($,{stream:!0});let G=s.split(`
4
4
 
5
- `);i=(Dt=G.pop())!=null?Dt:"";for(let pe of G){let O=pe.split(`
6
- `),xe="message",ce="";for(let N of O)N.startsWith("event:")?xe=N.replace("event:","").trim():N.startsWith("data:")&&(ce+=N.replace("data:","").trim());if(!ce)continue;let h;try{h=JSON.parse(ce)}catch(N){r({type:"error",error:N instanceof Error?N:new Error("Failed to parse chat stream payload")});continue}let Ye=xe!=="message"?xe:(Z=h.type)!=null?Z:"message";if(Ye==="reason_start"){let N=(M=re(h,!0))!=null?M:`reason-${v()}`,m=Ne(N);m.reasoning=(rt=m.reasoning)!=null?rt:{id:N,status:"streaming",chunks:[]},m.reasoning.startedAt=(qt=m.reasoning.startedAt)!=null?qt:Ae((xt=h.startedAt)!=null?xt:h.timestamp),m.reasoning.completedAt=void 0,m.reasoning.durationMs=void 0,m.streaming=!0,m.reasoning.status="streaming",u(m)}else if(Ye==="reason_chunk"){let N=(se=(st=re(h,!1))!=null?st:re(h,!0))!=null?se:`reason-${v()}`,m=Ne(N);m.reasoning=(E=m.reasoning)!=null?E:{id:N,status:"streaming",chunks:[]},m.reasoning.startedAt=(b=m.reasoning.startedAt)!=null?b:Ae((ve=h.startedAt)!=null?ve:h.timestamp);let d=(ut=(ze=(X=h.reasoningText)!=null?X:h.text)!=null?ze:h.delta)!=null?ut:"";if(d&&h.hidden!==!0&&m.reasoning.chunks.push(String(d)),m.reasoning.status=h.done?"complete":"streaming",h.done){m.reasoning.completedAt=Ae((Qe=h.completedAt)!=null?Qe:h.timestamp);let H=(F=m.reasoning.startedAt)!=null?F:Date.now();m.reasoning.durationMs=Math.max(0,((Ct=m.reasoning.completedAt)!=null?Ct:Date.now())-H)}m.streaming=m.reasoning.status!=="complete",u(m)}else if(Ye==="reason_complete"){let N=(gt=(Oe=re(h,!1))!=null?Oe:re(h,!0))!=null?gt:`reason-${v()}`,m=k.get(N);if(m!=null&&m.reasoning){m.reasoning.status="complete",m.reasoning.completedAt=Ae((Fe=h.completedAt)!=null?Fe:h.timestamp);let H=(Ve=m.reasoning.startedAt)!=null?Ve:Date.now();m.reasoning.durationMs=Math.max(0,((D=m.reasoning.completedAt)!=null?D:Date.now())-H),m.streaming=!1,u(m)}let d=y(h);d&&L.byStep.delete(d)}else if(Ye==="tool_start"){let N=(ye=we(h,!0))!=null?ye:`tool-${v()}`,m=ee(N),d=(Et=m.toolCall)!=null?Et:{id:N,status:"pending"};d.name=(J=h.toolName)!=null?J:d.name,d.status="running",h.args!==void 0&&(d.args=h.args),d.startedAt=(Xt=d.startedAt)!=null?Xt:Ae((it=h.startedAt)!=null?it:h.timestamp),d.completedAt=void 0,d.durationMs=void 0,m.toolCall=d,m.streaming=!0,u(m)}else if(Ye==="tool_chunk"){let N=(St=(mt=we(h,!1))!=null?mt:we(h,!0))!=null?St:`tool-${v()}`,m=ee(N),d=(be=m.toolCall)!=null?be:{id:N,status:"running"};d.startedAt=(Lt=d.startedAt)!=null?Lt:Ae((Wt=h.startedAt)!=null?Wt:h.timestamp);let H=(Ot=(zt=(at=h.text)!=null?at:h.delta)!=null?zt:h.message)!=null?Ot:"";H&&(d.chunks=(kt=d.chunks)!=null?kt:[],d.chunks.push(String(H))),d.status="running",m.toolCall=d,m.streaming=!0,u(m)}else if(Ye==="tool_complete"){let N=(lt=(ft=we(h,!1))!=null?ft:we(h,!0))!=null?lt:`tool-${v()}`,m=ee(N),d=($t=m.toolCall)!=null?$t:{id:N,status:"running"};if(d.status="complete",h.result!==void 0&&(d.result=h.result),typeof h.duration=="number"&&(d.duration=h.duration),d.completedAt=Ae((_t=h.completedAt)!=null?_t:h.timestamp),typeof h.duration=="number")d.durationMs=h.duration;else{let ae=(jt=d.startedAt)!=null?jt:Date.now();d.durationMs=Math.max(0,((wt=d.completedAt)!=null?wt:Date.now())-ae)}m.toolCall=d,m.streaming=!1,u(m);let H=B(h);H&&Q.byCall.delete(H)}else if(Ye==="step_chunk"){let N=h.stepType,m=h.executionType;if(N==="tool"||m==="context")continue;let d=g(),H=(Tt=($e=(ht=h.text)!=null?ht:h.delta)!=null?$e:h.content)!=null?Tt:"";if(H){let le=((Bt=ne.get(d.id))!=null?Bt:"")+H;d.rawContent=le,Y.has(d.id)||Y.set(d.id,this.createStreamParser());let ue=Y.get(d.id),Re=le.trim().startsWith("{")||le.trim().startsWith("[");if(Re&&ne.set(d.id,le),ue.__isPlainTextParser===!0){d.content+=H,ne.delete(d.id),Y.delete(d.id),d.rawContent=void 0,u(d);continue}let de=ue.processChunk(le);if(de instanceof Promise)de.then(j=>{var me;let ie=typeof j=="string"?j:(me=j==null?void 0:j.text)!=null?me:null;if(ie!==null&&ie.trim()!==""){let Ce=I;Ce&&Ce.id===d.id&&(Ce.content=ie,u(Ce))}else if(!Re&&!le.trim().startsWith("<")){let Ce=I;Ce&&Ce.id===d.id&&(Ce.content+=H,ne.delete(Ce.id),Y.delete(Ce.id),Ce.rawContent=void 0,u(Ce))}}).catch(()=>{d.content+=H,ne.delete(d.id),Y.delete(d.id),d.rawContent=void 0,u(d)});else{let j=typeof de=="string"?de:(Rt=de==null?void 0:de.text)!=null?Rt:null;j!==null&&j.trim()!==""?(d.content=j,u(d)):!Re&&!le.trim().startsWith("<")&&(d.content+=H,ne.delete(d.id),Y.delete(d.id),d.rawContent=void 0,u(d))}}if(h.isComplete){let ae=(De=(Ht=h.result)==null?void 0:Ht.response)!=null?De:d.content;if(ae){let le=ne.get(d.id),ue=le!=null?le:he(ae);d.rawContent=ue;let Re=Y.get(d.id),Me=null;if(Re&&(Me=Re.getExtractedText(),Me===null&&(Me=on(ue)),Me===null)){let j=Re.processChunk(ue);j instanceof Promise?j.then(ie=>{var Ce;let me=typeof ie=="string"?ie:(Ce=ie==null?void 0:ie.text)!=null?Ce:null;if(me!==null){let He=I;He&&He.id===d.id&&(He.content=me,He.streaming=!1,u(He))}}):Me=typeof j=="string"?j:(_e=j==null?void 0:j.text)!=null?_e:null}Me!==null&&Me.trim()!==""?d.content=Me:ne.has(d.id)||(d.content=he(ae));let de=Y.get(d.id);if(de){let j=(dt=de.close)==null?void 0:dt.call(de);j instanceof Promise&&j.catch(()=>{}),Y.delete(d.id)}ne.delete(d.id),d.streaming=!1,u(d)}}}else if(Ye==="step_complete"){let N=h.stepType,m=h.executionType;if(N==="tool"||m==="context")continue;let d=(et=h.result)==null?void 0:et.response,H=g();if(d!=null){let ae=Y.get(H.id),le=!1;if(ae){let ue=ae.getExtractedText(),Re=ne.get(H.id),Me=Re!=null?Re:he(d);if(H.rawContent=Me,ue!==null&&ue.trim()!=="")H.content=ue,le=!0;else{let de=on(Me);if(de!==null)H.content=de,le=!0;else{let j=ae.processChunk(Me);if(j instanceof Promise)j.then(ie=>{var Ce;let me=typeof ie=="string"?ie:(Ce=ie==null?void 0:ie.text)!=null?Ce:null;if(me!==null&&me.trim()!==""){let He=I;He&&He.id===H.id&&(He.content=me,He.streaming=!1,u(He))}else{let He=ae.getExtractedText();if(He===null||He.trim()===""){let s=I;s&&s.id===H.id&&(ne.has(H.id)||(s.content=he(d)),s.streaming=!1,u(s))}}});else{let ie=typeof j=="string"?j:(It=j==null?void 0:j.text)!=null?It:null;if(ie!==null&&ie.trim()!=="")H.content=ie,le=!0;else{let me=ae.getExtractedText();me!==null&&me.trim()!==""&&(H.content=me,le=!0)}}}}}if(!H.rawContent){let ue=ne.get(H.id);H.rawContent=ue!=null?ue:he(d)}if(!le&&!ne.has(H.id)&&(H.content=he(d)),ae){let ue=(vt=ae.close)==null?void 0:vt.call(ae);ue instanceof Promise&&ue.catch(()=>{})}Y.delete(H.id),ne.delete(H.id),H.streaming=!1,u(H)}else Y.delete(H.id),ne.delete(H.id),H.streaming=!1,u(H)}else if(Ye==="flow_complete"){let N=(Xe=h.result)==null?void 0:Xe.response;if(N!=null){let m=g(),d=ne.get(m.id),H=d!=null?d:he(N);m.rawContent=H;let ae=he(N),le=Y.get(m.id);if(le){let ue=on(H);if(ue!==null)ae=ue;else{let Re=le.processChunk(H);Re instanceof Promise&&Re.then(de=>{var ie;let j=typeof de=="string"?de:(ie=de==null?void 0:de.text)!=null?ie:null;if(j!==null){let me=I;me&&me.id===m.id&&(me.content=j,me.streaming=!1,u(me))}});let Me=le.getExtractedText();Me!==null&&(ae=Me)}}Y.delete(m.id),ne.delete(m.id),ae!==m.content&&(m.content=ae,u(m)),m.streaming=!1,u(m)}else if(I!==null){let m=I;Y.delete(m.id),ne.delete(m.id),m.streaming=!1,u(m)}r({type:"status",status:"idle"})}else Ye==="error"&&h.error&&r({type:"error",error:h.error instanceof Error?h.error:new Error(String(h.error))})}}}};var Jt=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=n=>{var r,e;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(r=this.callbacks).onError)==null||e.call(r,n.error))};var e;this.messages=[...(e=n.initialMessages)!=null?e:[]].map(o=>{var i;return{...o,sequence:(i=o.sequence)!=null?i:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Vt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(n){this.config={...this.config,...n},this.client=new Vt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}async sendMessage(n,r){var w,v,P,u,I;let e=n.trim();if(!e)return;(w=this.abortController)==null||w.abort();let o={id:`user-${Date.now()}`,role:"user",content:e,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1};this.appendMessage(o),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let a=[...this.messages];try{await this.client.dispatch({messages:a,signal:i.signal},this.handleEvent)}catch(k){let q={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(q),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,k instanceof Error?(P=(v=this.callbacks).onError)==null||P.call(v,k):(I=(u=this.callbacks).onError)==null||I.call(u,new Error(String(k)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,i)=>i===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,e)=>{var v,P;let o=new Date(r.createdAt).getTime(),i=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(i)&&o!==i)return o-i;let a=(v=r.sequence)!=null?v:0,w=(P=e.sequence)!=null?P:0;return a!==w?a-w:r.id.localeCompare(e.id)})}};var fn=(t,n)=>{var e;let r=(e=n==null?void 0:n.theme)!=null?e:{};Object.entries(r).forEach(([o,i])=>{if(i==null||i==="")return;let a=o.replace(/[A-Z]/g,w=>`-${w.toLowerCase()}`);t.style.setProperty(`--cw-${a}`,String(i))})};var or=Xo(require("lucide"),1),Le=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),i=or[o];return i?rr(i,n,r,e):(console.warn(`Lucide icon "${t}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${t}":`,o),null}};function rr(t,n,r,e){if(!t||!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(i=>{if(Array.isArray(i)&&i.length>=2){let a=i[0],w=i[1];if(w){let v=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(w).forEach(([P,u])=>{P!=="stroke"&&v.setAttribute(P,String(u))}),o.appendChild(v)}}}),o}var c=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Ue={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ft={"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 wn=(t,n)=>{let r=c("button");r.type="button",r.innerHTML=`
5
+ `);s=(qt=G.pop())!=null?qt:"";for(let pe of G){let O=pe.split(`
6
+ `),be="message",ce="";for(let N of O)N.startsWith("event:")?be=N.replace("event:","").trim():N.startsWith("data:")&&(ce+=N.replace("data:","").trim());if(!ce)continue;let h;try{h=JSON.parse(ce)}catch(N){r({type:"error",error:N instanceof Error?N:new Error("Failed to parse chat stream payload")});continue}let Ye=be!=="message"?be:(Z=h.type)!=null?Z:"message";if(Ye==="reason_start"){let N=(M=re(h,!0))!=null?M:`reason-${v()}`,f=Ne(N);f.reasoning=(rt=f.reasoning)!=null?rt:{id:N,status:"streaming",chunks:[]},f.reasoning.startedAt=(zt=f.reasoning.startedAt)!=null?zt:Ae((bt=h.startedAt)!=null?bt:h.timestamp),f.reasoning.completedAt=void 0,f.reasoning.durationMs=void 0,f.streaming=!0,f.reasoning.status="streaming",u(f)}else if(Ye==="reason_chunk"){let N=(se=(st=re(h,!1))!=null?st:re(h,!0))!=null?se:`reason-${v()}`,f=Ne(N);f.reasoning=(E=f.reasoning)!=null?E:{id:N,status:"streaming",chunks:[]},f.reasoning.startedAt=(x=f.reasoning.startedAt)!=null?x:Ae((ve=h.startedAt)!=null?ve:h.timestamp);let d=(ut=(ze=(X=h.reasoningText)!=null?X:h.text)!=null?ze:h.delta)!=null?ut:"";if(d&&h.hidden!==!0&&f.reasoning.chunks.push(String(d)),f.reasoning.status=h.done?"complete":"streaming",h.done){f.reasoning.completedAt=Ae((Qe=h.completedAt)!=null?Qe:h.timestamp);let H=(F=f.reasoning.startedAt)!=null?F:Date.now();f.reasoning.durationMs=Math.max(0,((Ct=f.reasoning.completedAt)!=null?Ct:Date.now())-H)}f.streaming=f.reasoning.status!=="complete",u(f)}else if(Ye==="reason_complete"){let N=(gt=(Oe=re(h,!1))!=null?Oe:re(h,!0))!=null?gt:`reason-${v()}`,f=k.get(N);if(f!=null&&f.reasoning){f.reasoning.status="complete",f.reasoning.completedAt=Ae((Fe=h.completedAt)!=null?Fe:h.timestamp);let H=(Ve=f.reasoning.startedAt)!=null?Ve:Date.now();f.reasoning.durationMs=Math.max(0,((D=f.reasoning.completedAt)!=null?D:Date.now())-H),f.streaming=!1,u(f)}let d=y(h);d&&L.byStep.delete(d)}else if(Ye==="tool_start"){let N=(ye=we(h,!0))!=null?ye:`tool-${v()}`,f=ee(N),d=(Wt=f.toolCall)!=null?Wt:{id:N,status:"pending"};d.name=(J=h.toolName)!=null?J:d.name,d.status="running",h.args!==void 0&&(d.args=h.args),d.startedAt=(Yt=d.startedAt)!=null?Yt:Ae((it=h.startedAt)!=null?it:h.timestamp),d.completedAt=void 0,d.durationMs=void 0,f.toolCall=d,f.streaming=!0,u(f)}else if(Ye==="tool_chunk"){let N=(St=(mt=we(h,!1))!=null?mt:we(h,!0))!=null?St:`tool-${v()}`,f=ee(N),d=(xe=f.toolCall)!=null?xe:{id:N,status:"running"};d.startedAt=(kt=d.startedAt)!=null?kt:Ae((Lt=h.startedAt)!=null?Lt:h.timestamp);let H=(_t=(Ot=(at=h.text)!=null?at:h.delta)!=null?Ot:h.message)!=null?_t:"";H&&(d.chunks=(Bt=d.chunks)!=null?Bt:[],d.chunks.push(String(H))),d.status="running",f.toolCall=d,f.streaming=!0,u(f)}else if(Ye==="tool_complete"){let N=(lt=(ft=we(h,!1))!=null?ft:we(h,!0))!=null?lt:`tool-${v()}`,f=ee(N),d=($t=f.toolCall)!=null?$t:{id:N,status:"running"};if(d.status="complete",h.result!==void 0&&(d.result=h.result),typeof h.duration=="number"&&(d.duration=h.duration),d.completedAt=Ae((jt=h.completedAt)!=null?jt:h.timestamp),typeof h.duration=="number")d.durationMs=h.duration;else{let ae=(Ut=d.startedAt)!=null?Ut:Date.now();d.durationMs=Math.max(0,((wt=d.completedAt)!=null?wt:Date.now())-ae)}f.toolCall=d,f.streaming=!1,u(f);let H=B(h);H&&Q.byCall.delete(H)}else if(Ye==="step_chunk"){let N=h.stepType,f=h.executionType;if(N==="tool"||f==="context")continue;let d=g(),H=(Tt=(_e=(ht=h.text)!=null?ht:h.delta)!=null?_e:h.content)!=null?Tt:"";if(H){let le=((Rt=ne.get(d.id))!=null?Rt:"")+H;d.rawContent=le,Y.has(d.id)||Y.set(d.id,this.createStreamParser());let ue=Y.get(d.id),Re=le.trim().startsWith("{")||le.trim().startsWith("[");if(Re&&ne.set(d.id,le),ue.__isPlainTextParser===!0){d.content+=H,ne.delete(d.id),Y.delete(d.id),d.rawContent=void 0,u(d);continue}let de=ue.processChunk(le);if(de instanceof Promise)de.then(j=>{var me;let ie=typeof j=="string"?j:(me=j==null?void 0:j.text)!=null?me:null;if(ie!==null&&ie.trim()!==""){let Ce=I;Ce&&Ce.id===d.id&&(Ce.content=ie,u(Ce))}else if(!Re&&!le.trim().startsWith("<")){let Ce=I;Ce&&Ce.id===d.id&&(Ce.content+=H,ne.delete(Ce.id),Y.delete(Ce.id),Ce.rawContent=void 0,u(Ce))}}).catch(()=>{d.content+=H,ne.delete(d.id),Y.delete(d.id),d.rawContent=void 0,u(d)});else{let j=typeof de=="string"?de:(Ht=de==null?void 0:de.text)!=null?Ht:null;j!==null&&j.trim()!==""?(d.content=j,u(d)):!Re&&!le.trim().startsWith("<")&&(d.content+=H,ne.delete(d.id),Y.delete(d.id),d.rawContent=void 0,u(d))}}if(h.isComplete){let ae=(De=(It=h.result)==null?void 0:It.response)!=null?De:d.content;if(ae){let le=ne.get(d.id),ue=le!=null?le:he(ae);d.rawContent=ue;let Re=Y.get(d.id),Me=null;if(Re&&(Me=Re.getExtractedText(),Me===null&&(Me=on(ue)),Me===null)){let j=Re.processChunk(ue);j instanceof Promise?j.then(ie=>{var Ce;let me=typeof ie=="string"?ie:(Ce=ie==null?void 0:ie.text)!=null?Ce:null;if(me!==null){let He=I;He&&He.id===d.id&&(He.content=me,He.streaming=!1,u(He))}}):Me=typeof j=="string"?j:($e=j==null?void 0:j.text)!=null?$e:null}Me!==null&&Me.trim()!==""?d.content=Me:ne.has(d.id)||(d.content=he(ae));let de=Y.get(d.id);if(de){let j=(dt=de.close)==null?void 0:dt.call(de);j instanceof Promise&&j.catch(()=>{}),Y.delete(d.id)}ne.delete(d.id),d.streaming=!1,u(d)}}}else if(Ye==="step_complete"){let N=h.stepType,f=h.executionType;if(N==="tool"||f==="context")continue;let d=(et=h.result)==null?void 0:et.response,H=g();if(d!=null){let ae=Y.get(H.id),le=!1;if(ae){let ue=ae.getExtractedText(),Re=ne.get(H.id),Me=Re!=null?Re:he(d);if(H.rawContent=Me,ue!==null&&ue.trim()!=="")H.content=ue,le=!0;else{let de=on(Me);if(de!==null)H.content=de,le=!0;else{let j=ae.processChunk(Me);if(j instanceof Promise)j.then(ie=>{var Ce;let me=typeof ie=="string"?ie:(Ce=ie==null?void 0:ie.text)!=null?Ce:null;if(me!==null&&me.trim()!==""){let He=I;He&&He.id===H.id&&(He.content=me,He.streaming=!1,u(He))}else{let He=ae.getExtractedText();if(He===null||He.trim()===""){let i=I;i&&i.id===H.id&&(ne.has(H.id)||(i.content=he(d)),i.streaming=!1,u(i))}}});else{let ie=typeof j=="string"?j:(Pt=j==null?void 0:j.text)!=null?Pt:null;if(ie!==null&&ie.trim()!=="")H.content=ie,le=!0;else{let me=ae.getExtractedText();me!==null&&me.trim()!==""&&(H.content=me,le=!0)}}}}}if(!H.rawContent){let ue=ne.get(H.id);H.rawContent=ue!=null?ue:he(d)}if(!le&&!ne.has(H.id)&&(H.content=he(d)),ae){let ue=(vt=ae.close)==null?void 0:vt.call(ae);ue instanceof Promise&&ue.catch(()=>{})}Y.delete(H.id),ne.delete(H.id),H.streaming=!1,u(H)}else Y.delete(H.id),ne.delete(H.id),H.streaming=!1,u(H)}else if(Ye==="flow_complete"){let N=(Xe=h.result)==null?void 0:Xe.response;if(N!=null){let f=g(),d=ne.get(f.id),H=d!=null?d:he(N);f.rawContent=H;let ae=he(N),le=Y.get(f.id);if(le){let ue=on(H);if(ue!==null)ae=ue;else{let Re=le.processChunk(H);Re instanceof Promise&&Re.then(de=>{var ie;let j=typeof de=="string"?de:(ie=de==null?void 0:de.text)!=null?ie:null;if(j!==null){let me=I;me&&me.id===f.id&&(me.content=j,me.streaming=!1,u(me))}});let Me=le.getExtractedText();Me!==null&&(ae=Me)}}Y.delete(f.id),ne.delete(f.id),ae!==f.content&&(f.content=ae,u(f)),f.streaming=!1,u(f)}else if(I!==null){let f=I;Y.delete(f.id),ne.delete(f.id),f.streaming=!1,u(f)}r({type:"status",status:"idle"})}else Ye==="error"&&h.error&&r({type:"error",error:h.error instanceof Error?h.error:new Error(String(h.error))})}}}};var Jt=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=n=>{var r,e;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(r=this.callbacks).onError)==null||e.call(r,n.error))};var e;this.messages=[...(e=n.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Kt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(n){this.config={...this.config,...n},this.client=new Kt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}async sendMessage(n,r){var m,v,P,u,I;let e=n.trim();if(!e)return;(m=this.abortController)==null||m.abort();let o={id:`user-${Date.now()}`,role:"user",content:e,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1};this.appendMessage(o),this.setStreaming(!0);let s=new AbortController;this.abortController=s;let a=[...this.messages];try{await this.client.dispatch({messages:a,signal:s.signal},this.handleEvent)}catch(k){let q={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(q),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,k instanceof Error?(P=(v=this.callbacks).onError)==null||P.call(v,k):(I=(u=this.callbacks).onError)==null||I.call(u,new Error(String(k)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,e)=>{var v,P;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(v=r.sequence)!=null?v:0,m=(P=e.sequence)!=null?P:0;return a!==m?a-m:r.id.localeCompare(e.id)})}};var fn=(t,n)=>{var e;let r=(e=n==null?void 0:n.theme)!=null?e:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let a=o.replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`);t.style.setProperty(`--cw-${a}`,String(s))})};var rr=Yo(require("lucide"),1),Le=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),s=rr[o];return s?sr(s,n,r,e):(console.warn(`Lucide icon "${t}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${t}":`,o),null}};function sr(t,n,r,e){if(!t||!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let a=s[0],m=s[1];if(m){let v=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(m).forEach(([P,u])=>{P!=="stroke"&&v.setAttribute(P,String(u))}),o.appendChild(v)}}}),o}var c=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Ue={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Dt={"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 wn=(t,n)=>{let r=c("button");r.type="button",r.innerHTML=`
7
7
  <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>
8
8
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
9
9
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -11,6 +11,6 @@
11
11
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
12
12
  </span>
13
13
  <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>
14
- `,r.addEventListener("click",n);let e=i=>{var Q,R,y,B,g,ke,re,Ne,Be,we;let a=(Q=i.launcher)!=null?Q:{},w=r.querySelector("[data-role='launcher-title']");w&&(w.textContent=(R=a.title)!=null?R:"Chat Assistant");let v=r.querySelector("[data-role='launcher-subtitle']");v&&(v.textContent=(y=a.subtitle)!=null?y:"Get answers fast");let P=r.querySelector(".tvw-flex-col");P&&(a.textHidden?P.style.display="none":P.style.display="");let u=r.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ee=(B=a.agentIconSize)!=null?B:"40px";if(u.style.height=ee,u.style.width=ee,u.innerHTML="",a.agentIconName){let Ae=parseFloat(ee)||24,he=Le(a.agentIconName,Ae*.6,"#ffffff",2);he?(u.appendChild(he),u.style.display=""):(u.textContent=(g=a.agentIconText)!=null?g:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(ke=a.agentIconText)!=null?ke:"\u{1F4AC}",u.style.display="")}let I=r.querySelector("[data-role='launcher-image']");if(I){let ee=(re=a.agentIconSize)!=null?re:"40px";I.style.height=ee,I.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(I.src=a.iconUrl,I.style.display="block"):I.style.display="none"}let k=r.querySelector("[data-role='launcher-call-to-action-icon']");if(k){let ee=(Ne=a.callToActionIconSize)!=null?Ne:"32px";k.style.height=ee,k.style.width=ee,a.callToActionIconBackgroundColor?(k.style.backgroundColor=a.callToActionIconBackgroundColor,k.classList.remove("tvw-bg-cw-primary")):(k.style.backgroundColor="",k.classList.add("tvw-bg-cw-primary"));let Ae=0;if(a.callToActionIconPadding?(k.style.boxSizing="border-box",k.style.padding=a.callToActionIconPadding,Ae=(parseFloat(a.callToActionIconPadding)||0)*2):(k.style.boxSizing="",k.style.padding=""),a.callToActionIconHidden)k.style.display="none";else if(k.style.display="",k.innerHTML="",a.callToActionIconName){let he=parseFloat(ee)||24,Y=Math.max(he-Ae,8),ne=Le(a.callToActionIconName,Y,"currentColor",2);ne?k.appendChild(ne):k.textContent=(Be=a.callToActionIconText)!=null?Be:"\u2197"}else k.textContent=(we=a.callToActionIconText)!=null?we:"\u2197"}let q=a.position&&Ft[a.position]?Ft[a.position]:Ft["bottom-right"],L="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-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${L} ${q}`},o=()=>{r.removeEventListener("click",n),r.remove()};return t&&e(t),{element:r,update:e,destroy:o}};var Bo=t=>{var v,P,u,I,k;if(!((P=(v=t==null?void 0:t.launcher)==null?void 0:v.enabled)!=null?P:!0)){let q=c("div","tvw-relative tvw-w-full tvw-h-full"),L=c("div","tvw-relative tvw-w-full tvw-h-full tvw-min-h-[360px]");return q.appendChild(L),{wrapper:q,panel:L}}let r=(u=t==null?void 0:t.launcher)!=null?u:{},e=r.position&&Ft[r.position]?Ft[r.position]:Ft["bottom-right"],o=c("div",`tvw-fixed ${e} tvw-z-50 tvw-transition`),i=c("div","tvw-relative tvw-min-h-[320px]"),a=(k=(I=t==null?void 0:t.launcher)==null?void 0:I.width)!=null?k:t==null?void 0:t.launcherWidth,w=a!=null?a:"min(400px, calc(100vw - 24px))";return i.style.width=w,i.style.maxWidth=w,o.appendChild(i),{wrapper:o,panel:i}},Ro=(t,n=!0)=>{var Wt,Lt,at,zt,Ot,kt,ft,lt,$t,_t,jt,wt,ht,$e,Tt,Bt,Rt,Ht,De,_e,dt,et,It,vt,Xe,p,_,G,pe,O,xe,ce,h,Ye,N,m,d,H,ae,le,ue,Re,Me,de,j,ie,me,Ce,He,s,l,S,z,T,W,x,U,Se,$,A;let r=c("div","tvw-flex tvw-h-full tvw-w-full tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-shadow-2xl tvw-border tvw-border-cw-border"),e=c("div","tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(Wt=t==null?void 0:t.launcher)!=null?Wt:{},i=(Lt=o.headerIconSize)!=null?Lt:"48px",a=(at=o.closeButtonSize)!=null?at:"32px",w=(zt=o.closeButtonPlacement)!=null?zt:"inline",v=(Ot=o.headerIconHidden)!=null?Ot:!1,P=o.headerIconName,u=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(u.style.height=i,u.style.width=i,!v)if(P){let f=parseFloat(i)||24,V=Le(P,f*.6,"#ffffff",2);V?u.replaceChildren(V):u.textContent=(ft=(kt=t==null?void 0:t.launcher)==null?void 0:kt.agentIconText)!=null?ft:"\u{1F4AC}"}else if((lt=t==null?void 0:t.launcher)!=null&&lt.iconUrl){let f=c("img");f.src=t.launcher.iconUrl,f.alt="",f.className="tvw-rounded-xl tvw-object-cover",f.style.height=i,f.style.width=i,u.replaceChildren(f)}else u.textContent=(_t=($t=t==null?void 0:t.launcher)==null?void 0:$t.agentIconText)!=null?_t:"\u{1F4AC}";let I=c("div","tvw-flex tvw-flex-col"),k=c("span","tvw-text-base tvw-font-semibold");k.textContent=(wt=(jt=t==null?void 0:t.launcher)==null?void 0:jt.title)!=null?wt:"Chat Assistant";let q=c("span","tvw-text-xs tvw-text-cw-muted");q.textContent=($e=(ht=t==null?void 0:t.launcher)==null?void 0:ht.subtitle)!=null?$e:"Here to help you get answers fast",I.append(k,q),v?e.append(I):e.append(u,I);let L=(Tt=o.clearChat)!=null?Tt:{},Q=(Bt=L.enabled)!=null?Bt:!0,R=null,y=null;if(Q){let f=(Rt=L.size)!=null?Rt:"32px",V=(Ht=L.iconName)!=null?Ht:"refresh-cw",K=(De=L.iconColor)!=null?De:"",Ie=(_e=L.backgroundColor)!=null?_e:"",fe=(dt=L.borderWidth)!=null?dt:"",Je=(et=L.borderColor)!=null?et:"",te=(It=L.borderRadius)!=null?It:"",tt=(vt=L.paddingX)!=null?vt:"",yt=(Xe=L.paddingY)!=null?Xe:"",ct=(p=L.tooltipText)!=null?p:"Clear chat",Pt=(_=L.showTooltip)!=null?_:!0;y=c("div","tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),R=c("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"),R.style.height=f,R.style.width=f,R.type="button",R.setAttribute("aria-label",ct);let Ut=Le(V,"20px",K||"",2);if(Ut&&R.appendChild(Ut),K&&(R.style.color=K,R.classList.remove("tvw-text-cw-muted")),Ie&&(R.style.backgroundColor=Ie,R.classList.remove("hover:tvw-bg-gray-100")),fe||Je){let Ee=fe||"0px",pt=Je||"transparent";R.style.border=`${Ee} solid ${pt}`,R.classList.remove("tvw-border-none")}if(te&&(R.style.borderRadius=te,R.classList.remove("tvw-rounded-full")),tt?(R.style.paddingLeft=tt,R.style.paddingRight=tt):(R.style.paddingLeft="",R.style.paddingRight=""),yt?(R.style.paddingTop=yt,R.style.paddingBottom=yt):(R.style.paddingTop="",R.style.paddingBottom=""),y.appendChild(R),Pt&&ct&&R&&y){let Ee=null,pt=()=>{if(Ee||!R)return;Ee=c("div","tvw-clear-chat-tooltip"),Ee.textContent=ct;let Nt=c("div");Nt.className="tvw-clear-chat-tooltip-arrow",Ee.appendChild(Nt);let At=R.getBoundingClientRect();Ee.style.position="fixed",Ee.style.left=`${At.left+At.width/2}px`,Ee.style.top=`${At.top-8}px`,Ee.style.transform="translate(-50%, -100%)",document.body.appendChild(Ee)},je=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};y.addEventListener("mouseenter",pt),y.addEventListener("mouseleave",je),R.addEventListener("focus",pt),R.addEventListener("blur",je),y._cleanupTooltip=()=>{je(),y&&(y.removeEventListener("mouseenter",pt),y.removeEventListener("mouseleave",je)),R&&(R.removeEventListener("focus",pt),R.removeEventListener("blur",je))}}e.appendChild(y)}let B=c("div",w==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":Q?"":"tvw-ml-auto"),g=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");g.style.height=a,g.style.width=a,g.type="button";let ke=(G=o.closeButtonTooltipText)!=null?G:"Close chat",re=(pe=o.closeButtonShowTooltip)!=null?pe:!0;g.setAttribute("aria-label",ke),g.style.display=n?"":"none";let Ne=(O=o.closeButtonIconName)!=null?O:"x",Be=(xe=o.closeButtonIconText)!=null?xe:"\xD7",we=Le(Ne,"20px",o.closeButtonColor||"",2);if(we?g.appendChild(we):g.textContent=Be,o.closeButtonColor?(g.style.color=o.closeButtonColor,g.classList.remove("tvw-text-cw-muted")):(g.style.color="",g.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(g.style.backgroundColor=o.closeButtonBackgroundColor,g.classList.remove("hover:tvw-bg-gray-100")):(g.style.backgroundColor="",g.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let f=o.closeButtonBorderWidth||"0px",V=o.closeButtonBorderColor||"transparent";g.style.border=`${f} solid ${V}`,g.classList.remove("tvw-border-none")}else g.style.border="",g.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(g.style.borderRadius=o.closeButtonBorderRadius,g.classList.remove("tvw-rounded-full")):(g.style.borderRadius="",g.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(g.style.paddingLeft=o.closeButtonPaddingX,g.style.paddingRight=o.closeButtonPaddingX):(g.style.paddingLeft="",g.style.paddingRight=""),o.closeButtonPaddingY?(g.style.paddingTop=o.closeButtonPaddingY,g.style.paddingBottom=o.closeButtonPaddingY):(g.style.paddingTop="",g.style.paddingBottom=""),B.appendChild(g),re&&ke){let f=null,V=()=>{if(f)return;f=c("div","tvw-clear-chat-tooltip"),f.textContent=ke;let Ie=c("div");Ie.className="tvw-clear-chat-tooltip-arrow",f.appendChild(Ie);let fe=g.getBoundingClientRect();f.style.position="fixed",f.style.left=`${fe.left+fe.width/2}px`,f.style.top=`${fe.top-8}px`,f.style.transform="translate(-50%, -100%)",document.body.appendChild(f)},K=()=>{f&&f.parentNode&&(f.parentNode.removeChild(f),f=null)};B.addEventListener("mouseenter",V),B.addEventListener("mouseleave",K),g.addEventListener("focus",V),g.addEventListener("blur",K),B._cleanupTooltip=()=>{K(),B.removeEventListener("mouseenter",V),B.removeEventListener("mouseleave",K),g.removeEventListener("focus",V),g.removeEventListener("blur",K)}}w==="top-right"?(r.style.position="relative",r.appendChild(B)):e.appendChild(B);let ee=c("div","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");ee.id="vanilla-agent-scroll-container";let Ae=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),he=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");he.textContent=(h=(ce=t==null?void 0:t.copy)==null?void 0:ce.welcomeTitle)!=null?h:"Hello \u{1F44B}";let Y=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");Y.textContent=(N=(Ye=t==null?void 0:t.copy)==null?void 0:Ye.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",Ae.append(he,Y);let ne=c("div","tvw-flex tvw-flex-col tvw-gap-3");ee.append(Ae,ne);let Dt=c("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),Z=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),M=((m=t==null?void 0:t.voiceRecognition)==null?void 0:m.enabled)===!0,rt=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),st=c("form",`tvw-flex tvw-items-end ${M&&rt?"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`);st.style.outline="none";let se=c("textarea");se.placeholder=(H=(d=t==null?void 0:t.copy)==null?void 0:d.inputPlaceholder)!=null?H:"Type your message\u2026",se.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",se.rows=1;let E=(le=(ae=t==null?void 0:t.theme)==null?void 0:ae.inputFontFamily)!=null?le:"sans-serif",ve=(Re=(ue=t==null?void 0:t.theme)==null?void 0:ue.inputFontWeight)!=null?Re:"400",b=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=b(E),se.style.fontWeight=ve,se.style.border="none",se.style.outline="none",se.style.borderWidth="0",se.style.borderStyle="none",se.style.borderColor="transparent",se.addEventListener("focus",()=>{se.style.border="none",se.style.outline="none",se.style.borderWidth="0",se.style.borderStyle="none",se.style.borderColor="transparent",se.style.boxShadow="none"}),se.addEventListener("blur",()=>{se.style.border="none",se.style.outline="none"});let X=(Me=t==null?void 0:t.sendButton)!=null?Me:{},ze=(de=X.useIcon)!=null?de:!1,ut=(j=X.iconText)!=null?j:"\u2191",Qe=X.iconName,F=(ie=X.tooltipText)!=null?ie:"Send message",Ct=(me=X.showTooltip)!=null?me:!1,Oe=(Ce=X.size)!=null?Ce:"40px",gt=X.backgroundColor,Fe=X.textColor,Ve=c("div","tvw-send-button-wrapper"),D=c("button",ze?"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(D.type="submit",ze){if(D.style.width=Oe,D.style.height=Oe,D.style.minWidth=Oe,D.style.minHeight=Oe,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",Qe){let f=parseFloat(Oe)||24,V=Fe&&typeof Fe=="string"&&Fe.trim()?Fe.trim():"currentColor",K=Le(Qe,f,V,2);K?(D.appendChild(K),D.style.color=V):(D.textContent=ut,Fe?D.style.color=Fe:D.classList.add("tvw-text-white"))}else D.textContent=ut,Fe?D.style.color=Fe:D.classList.add("tvw-text-white");gt?D.style.backgroundColor=gt:D.classList.add("tvw-bg-cw-primary")}else D.textContent=(s=(He=t==null?void 0:t.copy)==null?void 0:He.sendButtonLabel)!=null?s:"Send",Fe?D.style.color=Fe:D.classList.add("tvw-text-white");if(X.borderWidth&&(D.style.borderWidth=X.borderWidth,D.style.borderStyle="solid"),X.borderColor&&(D.style.borderColor=X.borderColor),X.paddingX?(D.style.paddingLeft=X.paddingX,D.style.paddingRight=X.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),X.paddingY?(D.style.paddingTop=X.paddingY,D.style.paddingBottom=X.paddingY):(D.style.paddingTop="",D.style.paddingBottom=""),Ct&&F){let f=c("div","tvw-send-button-tooltip");f.textContent=F,Ve.appendChild(f)}Ve.appendChild(D);let ye=(l=t==null?void 0:t.voiceRecognition)!=null?l:{},Et=ye.enabled===!0,J=null,it=null,Xt=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Et&&Xt){it=c("div","tvw-send-button-wrapper"),J=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),J.type="button",J.setAttribute("aria-label","Start voice recognition");let f=(S=ye.iconName)!=null?S:"mic",V=(z=ye.iconSize)!=null?z:Oe,K=parseFloat(V)||24,Ie=(T=ye.backgroundColor)!=null?T:gt,fe=(W=ye.iconColor)!=null?W:Fe;J.style.width=V,J.style.height=V,J.style.minWidth=V,J.style.minHeight=V,J.style.fontSize="18px",J.style.lineHeight="1";let Je=fe||"currentColor",te=Le(f,K,Je,1.5);te?(J.appendChild(te),J.style.color=Je):(J.textContent="\u{1F3A4}",J.style.color=Je),Ie?J.style.backgroundColor=Ie:J.classList.add("tvw-bg-cw-primary"),fe?J.style.color=fe:!fe&&!Fe&&J.classList.add("tvw-text-white"),ye.borderWidth&&(J.style.borderWidth=ye.borderWidth,J.style.borderStyle="solid"),ye.borderColor&&(J.style.borderColor=ye.borderColor),ye.paddingX&&(J.style.paddingLeft=ye.paddingX,J.style.paddingRight=ye.paddingX),ye.paddingY&&(J.style.paddingTop=ye.paddingY,J.style.paddingBottom=ye.paddingY),it.appendChild(J);let tt=(x=ye.tooltipText)!=null?x:"Start voice recognition";if(((U=ye.showTooltip)!=null?U:!1)&&tt){let ct=c("div","tvw-send-button-tooltip");ct.textContent=tt,it.appendChild(ct)}}st.addEventListener("click",f=>{f.target!==D&&f.target!==Ve&&f.target!==J&&f.target!==it&&se.focus()}),st.append(se),it&&st.append(it),st.append(Ve);let mt=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),St=(Se=t==null?void 0:t.statusIndicator)!=null?Se:{},be=($=St.visible)!=null?$:!0;return mt.style.display=be?"":"none",mt.textContent=(A=St.idleText)!=null?A:"Online",Dt.append(Z,st,mt),r.append(e,ee,Dt),{container:r,body:ee,messagesWrapper:ne,suggestions:Z,textarea:se,sendButton:D,sendButtonWrapper:Ve,micButton:J,micButtonWrapper:it,composerForm:st,statusText:mt,introTitle:he,introSubtitle:Y,closeButton:g,closeButtonWrapper:B,clearChatButton:R,clearChatButtonWrapper:y,iconHolder:u}};var hn=()=>{let t=document.createElement("div");t.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",t.appendChild(n),t.appendChild(r),t.appendChild(e),t.appendChild(o),t},vn=(t,n)=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"];t.role==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");let e=c("div",r.join(" ")),o=document.createElement("div");if(o.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(o),t.streaming&&t.role==="assistant"&&(!t.content||!t.content.trim())){let i=hn();e.appendChild(i)}return e};var yn=new Set,bn=t=>{let n=t.reasoning,r=c("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(!n)return r;let e=yn.has(t.id),o=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false");let i=c("div","tvw-flex tvw-flex-col tvw-text-left"),a=c("span","tvw-text-xs tvw-text-cw-primary");a.textContent="Thinking...",i.appendChild(a);let w=c("span","tvw-text-xs tvw-text-cw-primary");w.textContent=Lo(n),i.appendChild(w),n.status==="complete"?a.style.display="none":a.style.display="";let v=c("div","tvw-flex tvw-items-center"),u=Le(e?"chevron-up":"chevron-down",16,"currentColor",2);u?v.appendChild(u):v.textContent=e?"Hide":"Show";let I=c("div","tvw-flex tvw-items-center tvw-ml-auto");I.append(v),o.append(i,I);let k=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");k.style.display=e?"":"none";let q=n.chunks.join(""),L=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");L.textContent=q||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),k.appendChild(L);let Q=()=>{o.setAttribute("aria-expanded",e?"true":"false"),v.innerHTML="";let B=Le(e?"chevron-up":"chevron-down",16,"currentColor",2);B?v.appendChild(B):v.textContent=e?"Hide":"Show",k.style.display=e?"":"none"},R=()=>{e=!e,e?yn.add(t.id):yn.delete(t.id),Q()};return o.addEventListener("pointerdown",y=>{y.preventDefault(),R()}),o.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),R())}),Q(),r.append(o,k),r};var xn=new Set,Cn=(t,n)=>{var R;let r=t.toolCall,e=(R=n==null?void 0:n.toolCall)!=null?R:{},o=c("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(e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let i=xn.has(t.id),a=c("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",i?"true":"false"),e.headerBackgroundColor&&(a.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(a.style.paddingLeft=e.headerPaddingX,a.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(a.style.paddingTop=e.headerPaddingY,a.style.paddingBottom=e.headerPaddingY);let w=c("div","tvw-flex tvw-flex-col tvw-text-left"),v=c("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(v.style.color=e.headerTextColor),v.textContent=ko(r),w.appendChild(v);let P=c("div","tvw-flex tvw-items-center"),u=e.toggleTextColor||e.headerTextColor||"currentColor",I=Le(i?"chevron-up":"chevron-down",16,u,2);I?P.appendChild(I):P.textContent=i?"Hide":"Show";let k=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");k.append(P),a.append(w,k);let q=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(q.style.display=i?"":"none",e.contentBackgroundColor&&(q.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(q.style.color=e.contentTextColor),e.contentPaddingX&&(q.style.paddingLeft=e.contentPaddingX,q.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(q.style.paddingTop=e.contentPaddingY,q.style.paddingBottom=e.contentPaddingY),r.name){let y=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?y.style.color=e.contentTextColor:e.headerTextColor&&(y.style.color=e.headerTextColor),y.textContent=r.name,q.appendChild(y)}if(r.args!==void 0){let y=c("div","tvw-space-y-1"),B=c("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(B.style.color=e.labelTextColor),B.textContent="Arguments";let g=c("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");g.style.fontSize="0.75rem",g.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(g.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(g.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(g.style.color=e.codeBlockTextColor),g.textContent=mn(r.args),y.append(B,g),q.appendChild(y)}if(r.chunks&&r.chunks.length){let y=c("div","tvw-space-y-1"),B=c("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(B.style.color=e.labelTextColor),B.textContent="Activity";let g=c("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");g.style.fontSize="0.75rem",g.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(g.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(g.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(g.style.color=e.codeBlockTextColor),g.textContent=r.chunks.join(`
15
- `),y.append(B,g),q.appendChild(y)}if(r.status==="complete"&&r.result!==void 0){let y=c("div","tvw-space-y-1"),B=c("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(B.style.color=e.labelTextColor),B.textContent="Result";let g=c("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");g.style.fontSize="0.75rem",g.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(g.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(g.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(g.style.color=e.codeBlockTextColor),g.textContent=mn(r.result),y.append(B,g),q.appendChild(y)}if(r.status==="complete"&&typeof r.duration=="number"){let y=c("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(y.style.color=e.contentTextColor),y.textContent=`Duration: ${r.duration}ms`,q.appendChild(y)}let L=()=>{a.setAttribute("aria-expanded",i?"true":"false"),P.innerHTML="";let y=e.toggleTextColor||e.headerTextColor||"currentColor",B=Le(i?"chevron-up":"chevron-down",16,y,2);B?P.appendChild(B):P.textContent=i?"Hide":"Show",q.style.display=i?"":"none"},Q=()=>{i=!i,i?xn.add(t.id):xn.delete(t.id),L()};return a.addEventListener("pointerdown",y=>{y.preventDefault(),Q()}),a.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),Q())}),L(),o.append(a,q),o};var Ho=t=>{let n=[];return{buttons:n,render:(e,o,i,a)=>{if(t.innerHTML="",n.length=0,!e||!e.length||(a!=null?a:o?o.getMessages():[]).some(I=>I.role==="user"))return;let P=document.createDocumentFragment(),u=o?o.isStreaming():!1;e.forEach(I=>{let k=c("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");k.type="button",k.textContent=I,k.disabled=u,k.addEventListener("click",()=>{!o||o.isStreaming()||(i.value="",o.sendMessage(I))}),P.appendChild(k),n.push(k)}),t.appendChild(P)}}};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"}},Sn=(t,n,r,e)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(i=>{var L,Q,R;if(i.dataset.enhanced==="true")return;let a=(L=i.dataset.tvForm)!=null?L:"init";i.dataset.enhanced="true";let w=(Q=Io[a])!=null?Q:Io.init;i.classList.add("tvw-form-card","tvw-space-y-4");let v=c("div","tvw-space-y-1"),P=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(P.textContent=w.title,v.appendChild(P),w.description){let y=c("p","tvw-text-sm tvw-text-cw-muted");y.textContent=w.description,v.appendChild(y)}let u=document.createElement("form");u.className="tvw-form-grid tvw-space-y-3",w.fields.forEach(y=>{var Ne,Be;let B=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");B.htmlFor=`${n.id}-${a}-${y.name}`;let g=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");g.textContent=y.label,B.appendChild(g);let ke=(Ne=y.type)!=null?Ne:"text",re;ke==="textarea"?(re=document.createElement("textarea"),re.rows=3):(re=document.createElement("input"),re.type=ke),re.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",re.id=`${n.id}-${a}-${y.name}`,re.name=y.name,re.placeholder=(Be=y.placeholder)!=null?Be:"",y.required&&(re.required=!0),B.appendChild(re),u.appendChild(B)});let I=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),k=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),q=c("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");q.type="submit",q.textContent=(R=w.submitLabel)!=null?R:"Submit",I.appendChild(k),I.appendChild(q),u.appendChild(I),i.replaceChildren(v,u),u.addEventListener("submit",async y=>{var re,Ne;y.preventDefault();let B=(re=r.formEndpoint)!=null?re:"/form",g=new FormData(u),ke={};g.forEach((Be,we)=>{ke[we]=Be}),ke.type=a,q.disabled=!0,k.textContent="Submitting\u2026";try{let Be=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ke)});if(!Be.ok)throw new Error(`Form submission failed (${Be.status})`);let we=await Be.json();k.textContent=(Ne=we.message)!=null?Ne:"Thanks! We'll be in touch soon.",we.success&&we.nextPrompt&&await e.sendMessage(String(we.nextPrompt))}catch(Be){k.textContent=Be instanceof Error?Be.message:"Something went wrong. Please try again."}finally{q.disabled=!1}})})};var Tn=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var e;let r=this.plugins.get(n);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let e=new Set(n.map(i=>i.id));return[...r.filter(i=>!e.has(i.id)),...n].sort((i,a)=>{var w,v;return((w=a.priority)!=null?w:0)-((v=i.priority)!=null?v:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},Zt=new Tn;var ot={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",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,iconName:"refresh-cw",size:"29px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!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?"],debug:!1};function dn(t){var n,r,e;return t?{...ot,...t,theme:{...ot.theme,...t.theme},launcher:{...ot.launcher,...t.launcher,clearChat:{...(n=ot.launcher)==null?void 0:n.clearChat,...(r=t.launcher)==null?void 0:r.clearChat}},copy:{...ot.copy,...t.copy},sendButton:{...ot.sendButton,...t.sendButton},statusIndicator:{...ot.statusIndicator,...t.statusIndicator},voiceRecognition:{...ot.voiceRecognition,...t.voiceRecognition},features:{...ot.features,...t.features},suggestionChips:(e=t.suggestionChips)!=null?e:ot.suggestionChips}:ot}var Po=()=>{let t=new Map,n=(o,i)=>(t.has(o)||t.set(o,new Set),t.get(o).add(i),()=>r(o,i)),r=(o,i)=>{var a;(a=t.get(o))==null||a.delete(i)};return{on:n,off:r,emit:(o,i)=>{var a;(a=t.get(o))==null||a.forEach(w=>{try{w(i)}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",v)}})}}};var sr=t=>{let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:t},ir=t=>{let n=t.trim(),r=n.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<n.length;o+=1){let i=n[o];if(i==="{"&&(e+=1),i==="}"&&(e-=1,e===0))return n.slice(r,o+1)}return null},Qt=({text:t})=>{if(!t||!t.includes("{"))return null;try{let n=sr(t),r=ir(n);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...i}=e;return{type:String(o),payload:i,raw:e}}catch{return null}},An=t=>typeof t=="string"?t:t==null?"":String(t),Kt={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:An(t.payload.text)},messageAndClick:(t,n)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,e=An(r.element);if(e&&((o=n.document)!=null&&o.querySelector)){let i=n.document.querySelector(e);i?setTimeout(()=>{i.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:An(r.text)}}},No=t=>Array.isArray(t)?t.map(n=>String(n)):[],en=t=>{let n=new Set(No(t.getMetadata().processedActionMessageIds)),r=()=>{n=new Set(No(t.getMetadata().processedActionMessageIds))},e=()=>{let i=Array.from(n);t.updateMetadata(a=>({...a,processedActionMessageIds:i}))};return{process:i=>{if(i.streaming||i.message.role!=="assistant"||!i.text||n.has(i.message.id))return null;let a=typeof i.raw=="string"&&i.raw||typeof i.message.rawContent=="string"&&i.message.rawContent||typeof i.text=="string"&&i.text||null;!a&&typeof i.text=="string"&&i.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 w=a?t.parsers.reduce((P,u)=>P||(u==null?void 0:u({text:a,message:i.message}))||null,null):null;if(!w)return null;n.add(i.message.id),e();let v={action:w,message:i.message};t.emit("action:detected",v);for(let P of t.handlers)if(P)try{let u=P(w,{message:i.message,metadata:t.getMetadata(),updateMetadata:t.updateMetadata,document:t.documentRef});if(!u)continue;if(u.displayText!==void 0&&u.handled)return u.displayText;if(u.handled)return""}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return""},syncFromMetadata:r}};var Gt="vanilla-agent-chat-history",ar=30*1e3,Mn=t=>!t||typeof t!="object"?{}:{...t},Fo=t=>t.map(n=>({...n,streaming:!1})),Do=(t,n)=>r=>{var i,a,w;let e=(i=r.text)!=null?i:"",o=(a=r.message.rawContent)!=null?a:null;if(n){let v=n.process({text:e,raw:o!=null?o:e,message:r.message,streaming:r.streaming});v!==null&&(e=v)}return t!=null&&t.postprocessMessage?t.postprocessMessage({...r,text:e,raw:(w=o!=null?o:r.text)!=null?w:""}):nn(e)},cn=(t,n,r)=>{var d,H,ae,le,ue,Re,Me,de,j,ie,me,Ce,He;(!t.id||t.id!=="vanilla-agent-root")&&(t.id="vanilla-agent-root");let e=dn(n);fn(t,e);let o=Zt.getForInstance(e.plugins),i=Po(),a=e.storageAdapter,w={},v=null;if(a!=null&&a.load)try{let s=a.load();if(s&&typeof s.then=="function")v=s;else if(s){let l=s;l.metadata&&(w=Mn(l.metadata)),(d=l.messages)!=null&&d.length&&(e={...e,initialMessages:l.messages})}}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",s)}let P=()=>w,u=s=>{var S;w=(S=s({...w}))!=null?S:{},kt()},I=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Qt],k=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Kt.message,Kt.messageAndClick],q=en({parsers:I,handlers:k,getMetadata:P,updateMetadata:u,emit:i.emit,documentRef:typeof document!="undefined"?document:null});q.syncFromMetadata();let L=(ae=(H=e.launcher)==null?void 0:H.enabled)!=null?ae:!0,Q=(ue=(le=e.launcher)==null?void 0:le.autoExpand)!=null?ue:!1,R=Q,y=L,B=L?Q:!0,g=Do(e,q),ke=(Me=(Re=e.features)==null?void 0:Re.showReasoning)!=null?Me:!0,re=(j=(de=e.features)==null?void 0:de.showToolCalls)!=null?j:!0,Ne=(ie=e.statusIndicator)!=null?ie:{},Be=s=>{var l,S,z,T;return s==="idle"?(l=Ne.idleText)!=null?l:Ue.idle:s==="connecting"?(S=Ne.connectingText)!=null?S:Ue.connecting:s==="connected"?(z=Ne.connectedText)!=null?z:Ue.connected:s==="error"?(T=Ne.errorText)!=null?T:Ue.error:Ue[s]},{wrapper:we,panel:ee}=Bo(e),Ae=Ro(e,L),{container:he,body:Y,messagesWrapper:ne,suggestions:Dt,textarea:Z,sendButton:M,sendButtonWrapper:rt,composerForm:xt,statusText:qt,introTitle:st,introSubtitle:se,closeButton:E,iconHolder:ve}=Ae,b=Ae.micButton,X=Ae.micButtonWrapper;ee.appendChild(he),t.appendChild(we);let ze=[],ut=Ho(Dt),Qe=null,F,Ct=!1,Oe=!0,gt=0,Fe=0,Ve=null,D=!1,ye=0,Et=!1,J=125,it=2e3,Xt=5,mt=50,St=new Map,be={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Wt=(Ce=(me=e.voiceRecognition)==null?void 0:me.autoResume)!=null?Ce:!1,Lt=s=>{i.emit("voice:state",{active:be.active,source:s,timestamp:Date.now()})},at=()=>{u(s=>({...s,voiceState:{active:be.active,timestamp:Date.now(),manuallyDeactivated:be.manuallyDeactivated}}))},zt=()=>{var z,T;if(((z=e.voiceRecognition)==null?void 0:z.enabled)===!1)return;let s=Mn(w.voiceState),l=!!s.active,S=Number((T=s.timestamp)!=null?T:0);be.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-S<ar&&setTimeout(()=>{be.active||(be.manuallyDeactivated=!1,vt("restore"))},1e3)},Ot=()=>F?Fo(F.getMessages()):[];function kt(s){if(!(a!=null&&a.save)||!F)return;let l={messages:s?Fo(s):Ot(),metadata:w};try{let S=a.save(l);S instanceof Promise&&S.catch(z=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",z)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let ft=(s=!1)=>{if(!Oe)return;let l=Date.now();D&&l<ye&&!s||(D&&l>=ye&&(D=!1),!(!s&&!Ct)&&(l-Fe<J||(Fe=l,Ve&&cancelAnimationFrame(Ve),Ve=requestAnimationFrame(()=>{D||!Oe||(Et=!0,Y.scrollTop=Y.scrollHeight,gt=Y.scrollTop,requestAnimationFrame(()=>{Et=!1}),Ve=null)}))))},lt=null,$t=()=>we.querySelector("#vanilla-agent-scroll-container")||Y,_t=(s,l=500)=>{let S=s.scrollTop,z=s.clientHeight,T=s.scrollHeight,W=T-S;if(S+z>=T-2||Math.abs(W)<5)return;lt!==null&&(cancelAnimationFrame(lt),lt=null);let U=performance.now(),Se=A=>1-Math.pow(1-A,3),$=A=>{let f=s.scrollHeight;f!==T&&(T=f,W=T-S);let V=A-U,K=Math.min(V/l,1),Ie=Se(K),fe=S+W*Ie;s.scrollTop=fe,K<1?lt=requestAnimationFrame($):(s.scrollTop=s.scrollHeight,lt=null)};lt=requestAnimationFrame($)},jt=s=>{let l=new Map;s.forEach(S=>{let z=St.get(S.id);l.set(S.id,{streaming:S.streaming,role:S.role}),!z&&S.role==="assistant"&&i.emit("assistant:message",S),S.role==="assistant"&&(z!=null&&z.streaming)&&S.streaming===!1&&i.emit("assistant:complete",S)}),St.clear(),l.forEach((S,z)=>{St.set(z,S)})},wt=(s,l,S)=>{s.innerHTML="";let z=document.createDocumentFragment();l.forEach(W=>{let x=null,U=o.find($=>!!(W.variant==="reasoning"&&$.renderReasoning||W.variant==="tool"&&$.renderToolCall||!W.variant&&$.renderMessage));if(U)if(W.variant==="reasoning"&&W.reasoning&&U.renderReasoning){if(!ke)return;x=U.renderReasoning({message:W,defaultRenderer:()=>bn(W),config:e})}else if(W.variant==="tool"&&W.toolCall&&U.renderToolCall){if(!re)return;x=U.renderToolCall({message:W,defaultRenderer:()=>Cn(W,e),config:e})}else U.renderMessage&&(x=U.renderMessage({message:W,defaultRenderer:()=>{let $=vn(W,S);return W.role!=="user"&&Sn($,W,e,F),$},config:e}));if(!x)if(W.variant==="reasoning"&&W.reasoning){if(!ke)return;x=bn(W)}else if(W.variant==="tool"&&W.toolCall){if(!re)return;x=Cn(W,e)}else x=vn(W,S),W.role!=="user"&&Sn(x,W,e,F);let Se=document.createElement("div");Se.className="tvw-flex",W.role==="user"&&Se.classList.add("tvw-justify-end"),Se.appendChild(x),z.appendChild(Se)});let T=l.some(W=>W.role==="assistant"&&W.streaming);if(Ct&&l.some(W=>W.role==="user")&&!T){let W=hn(),x=document.createElement("div");x.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),x.appendChild(W);let U=document.createElement("div");U.className="tvw-flex",U.appendChild(x),z.appendChild(U)}s.appendChild(z),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let W=$t();_t(W)})})},ht=()=>{L&&(B?(we.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ee.classList.remove("tvw-scale-95","tvw-opacity-0"),ee.classList.add("tvw-scale-100","tvw-opacity-100"),O&&(O.element.style.display="none")):(we.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ee.classList.remove("tvw-scale-100","tvw-opacity-100"),ee.classList.add("tvw-scale-95","tvw-opacity-0"),O&&(O.element.style.display="")))},$e=s=>{L&&B!==s&&(B=s,ht(),B&&(xe(),ft(!0)))},Tt=s=>{Z.disabled=s,M.disabled=s,b&&(b.disabled=s),ut.buttons.forEach(l=>{l.disabled=s})},Bt=()=>{var T,W,x,U,Se,$,A,f,V,K,Ie,fe,Je,te;st.textContent=(W=(T=e.copy)==null?void 0:T.welcomeTitle)!=null?W:"Hello \u{1F44B}",se.textContent=(U=(x=e.copy)==null?void 0:x.welcomeSubtitle)!=null?U:"Ask anything about your account or products.",Z.placeholder=($=(Se=e.copy)==null?void 0:Se.inputPlaceholder)!=null?$:"How can I help...",((f=(A=e.sendButton)==null?void 0:A.useIcon)!=null?f:!1)||(M.textContent=(K=(V=e.copy)==null?void 0:V.sendButtonLabel)!=null?K:"Send");let l=(fe=(Ie=e.theme)==null?void 0:Ie.inputFontFamily)!=null?fe:"sans-serif",S=(te=(Je=e.theme)==null?void 0:Je.inputFontWeight)!=null?te:"400",z=tt=>{switch(tt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};Z.style.fontFamily=z(l),Z.style.fontWeight=S};F=new Jt(e,{onMessagesChanged(s){wt(ne,s,g),F&&(s.some(z=>z.role==="user")?ut.render([],F,Z,s):ut.render(e.suggestionChips,F,Z,s)),ft(!Ct),jt(s);let l=[...s].reverse().find(S=>S.role==="user");be.lastUserMessageWasVoice=!!(l!=null&&l.viaVoice),kt(s)},onStatusChanged(s){var z;let l=(z=e.statusIndicator)!=null?z:{},S=T=>{var W,x,U,Se;return T==="idle"?(W=l.idleText)!=null?W:Ue.idle:T==="connecting"?(x=l.connectingText)!=null?x:Ue.connecting:T==="connected"?(U=l.connectedText)!=null?U:Ue.connected:T==="error"?(Se=l.errorText)!=null?Se:Ue.error:Ue[T]};qt.textContent=S(s)},onStreamingChanged(s){Ct=s,Tt(s),F&&wt(ne,F.getMessages(),g),s||ft(!0)}}),v&&v.then(s=>{var l;s&&(s.metadata&&(w=Mn(s.metadata),q.syncFromMetadata()),(l=s.messages)!=null&&l.length&&F.hydrateMessages(s.messages))}).catch(s=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)});let Rt=s=>{s.preventDefault();let l=Z.value.trim();l&&(Z.value="",F.sendMessage(l))},Ht=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),M.click())},De=null,_e=!1,dt=null,et=null,It=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,vt=(s="user")=>{var W,x,U,Se;if(_e||F.isStreaming())return;let l=It();if(!l)return;De=new l;let z=(x=((W=e.voiceRecognition)!=null?W:{}).pauseDuration)!=null?x:2e3;De.continuous=!0,De.interimResults=!0,De.lang="en-US";let T=Z.value;De.onresult=$=>{let A="",f="";for(let K=0;K<$.results.length;K++){let Ie=$.results[K],fe=Ie[0].transcript;Ie.isFinal?A+=fe+" ":f=fe}let V=T+A+f;Z.value=V,dt&&clearTimeout(dt),(A||f)&&(dt=window.setTimeout(()=>{let K=Z.value.trim();K&&De&&_e&&(Xe(),Z.value="",F.sendMessage(K,{viaVoice:!0}))},z))},De.onerror=$=>{$.error!=="no-speech"&&Xe()},De.onend=()=>{if(_e){let $=Z.value.trim();$&&$!==T.trim()&&(Z.value="",F.sendMessage($,{viaVoice:!0})),Xe()}};try{if(De.start(),_e=!0,be.active=!0,s!=="system"&&(be.manuallyDeactivated=!1),Lt(s),at(),b){et={backgroundColor:b.style.backgroundColor,color:b.style.color,borderColor:b.style.borderColor};let $=(U=e.voiceRecognition)!=null?U:{},A=(Se=$.recordingBackgroundColor)!=null?Se:"#ef4444",f=$.recordingIconColor,V=$.recordingBorderColor;if(b.classList.add("tvw-voice-recording"),b.style.backgroundColor=A,f){b.style.color=f;let K=b.querySelector("svg");K&&K.setAttribute("stroke",f)}V&&(b.style.borderColor=V),b.setAttribute("aria-label","Stop voice recognition")}}catch{Xe("system")}},Xe=(s="user")=>{if(_e){if(_e=!1,dt&&(clearTimeout(dt),dt=null),De){try{De.stop()}catch{}De=null}if(be.active=!1,Lt(s),at(),b){if(b.classList.remove("tvw-voice-recording"),et){b.style.backgroundColor=et.backgroundColor,b.style.color=et.color,b.style.borderColor=et.borderColor;let l=b.querySelector("svg");l&&l.setAttribute("stroke",et.color||"currentColor"),et=null}b.setAttribute("aria-label","Start voice recognition")}}},p=(s,l)=>{var fe,Je,te,tt,yt,ct,Pt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let z=c("div","tvw-send-button-wrapper"),T=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");T.type="button",T.setAttribute("aria-label","Start voice recognition");let W=(fe=s==null?void 0:s.iconName)!=null?fe:"mic",x=(Je=l==null?void 0:l.size)!=null?Je:"40px",U=(te=s==null?void 0:s.iconSize)!=null?te:x,Se=parseFloat(U)||24,$=(tt=s==null?void 0:s.backgroundColor)!=null?tt:l==null?void 0:l.backgroundColor,A=(yt=s==null?void 0:s.iconColor)!=null?yt:l==null?void 0:l.textColor;T.style.width=U,T.style.height=U,T.style.minWidth=U,T.style.minHeight=U,T.style.fontSize="18px",T.style.lineHeight="1";let f=A||"currentColor",V=Le(W,Se,f,1.5);V?(T.appendChild(V),T.style.color=f):(T.textContent="\u{1F3A4}",T.style.color=f),$?T.style.backgroundColor=$:T.classList.add("tvw-bg-cw-primary"),A?T.style.color=A:!A&&!(l!=null&&l.textColor)&&T.classList.add("tvw-text-white"),s!=null&&s.borderWidth&&(T.style.borderWidth=s.borderWidth,T.style.borderStyle="solid"),s!=null&&s.borderColor&&(T.style.borderColor=s.borderColor),s!=null&&s.paddingX&&(T.style.paddingLeft=s.paddingX,T.style.paddingRight=s.paddingX),s!=null&&s.paddingY&&(T.style.paddingTop=s.paddingY,T.style.paddingBottom=s.paddingY),z.appendChild(T);let K=(ct=s==null?void 0:s.tooltipText)!=null?ct:"Start voice recognition";if(((Pt=s==null?void 0:s.showTooltip)!=null?Pt:!1)&&K){let Ut=c("div","tvw-send-button-tooltip");Ut.textContent=K,z.appendChild(Ut)}return{micButton:T,micButtonWrapper:z}},_=()=>{if(_e){let s=Z.value.trim();be.manuallyDeactivated=!0,at(),Xe("user"),s&&(Z.value="",F.sendMessage(s))}else be.manuallyDeactivated=!1,at(),vt("user")};b&&(b.addEventListener("click",_),ze.push(()=>{Xe("system"),b&&b.removeEventListener("click",_)}));let G=i.on("assistant:complete",()=>{Wt&&(be.active||be.manuallyDeactivated||Wt==="assistant"&&!be.lastUserMessageWasVoice||setTimeout(()=>{!be.active&&!be.manuallyDeactivated&&vt("auto")},600))});ze.push(G);let pe=()=>{$e(!B)},O=L?wn(e,pe):null;O&&t.appendChild(O.element),ht(),ut.render(e.suggestionChips,F,Z),Bt(),Tt(F.isStreaming()),ft(!0),zt();let xe=()=>{var x,U;if(!L){ee.style.height="",ee.style.width="";return}let s=(U=(x=e==null?void 0:e.launcher)==null?void 0:x.width)!=null?U:e==null?void 0:e.launcherWidth,l=s!=null?s:"min(400px, calc(100vw - 24px))";ee.style.width=l,ee.style.maxWidth=l;let S=window.innerHeight,T=Math.max(200,S-64),W=Math.min(640,T);ee.style.height=`${W}px`};xe(),window.addEventListener("resize",xe),ze.push(()=>window.removeEventListener("resize",xe)),gt=Y.scrollTop;let ce=()=>{let s=Y.scrollTop,l=Y.scrollHeight,S=Y.clientHeight,z=l-s-S,T=Math.abs(s-gt);if(gt=s,!Et&&!(T<=Xt)){if(!Oe&&z<mt){D=!1,Oe=!0;return}Oe&&z>mt&&(D=!0,ye=Date.now()+it,Oe=!1)}};Y.addEventListener("scroll",ce,{passive:!0}),ze.push(()=>Y.removeEventListener("scroll",ce)),ze.push(()=>{Ve&&cancelAnimationFrame(Ve)});let h=()=>{E&&(Qe&&(E.removeEventListener("click",Qe),Qe=null),L?(E.style.display="",Qe=()=>{B=!1,ht()},E.addEventListener("click",Qe)):E.style.display="none")};h(),(()=>{let{clearChatButton:s}=Ae;s&&s.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(S){console.error("[AgentWidget] Failed to clear default localStorage:",S)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(S){console.error("[AgentWidget] Failed to clear custom localStorage:",S)}let l=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let S=a.clear();S instanceof Promise&&S.catch(z=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",z)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)}w={},q.syncFromMetadata()})})(),xt.addEventListener("submit",Rt),Z.addEventListener("keydown",Ht),ze.push(()=>{xt.removeEventListener("submit",Rt),Z.removeEventListener("keydown",Ht)}),ze.push(()=>{F.cancel()}),O&&ze.push(()=>{O==null||O.destroy()});let N={update(s){var Ln,kn,Bn,Rn,Hn,In,Pn,Nn,Fn,Dn,qn,zn,On,$n,_n,jn,Un,Vn,Kn,Xn,Yn,Jn,Gn,Zn,Qn,eo,to,no,oo,ro,so,io,ao,lo,co,uo,go,po,mo,fo,wo,ho,vo,yo,bo,xo,Co,So,To;let l=e.toolCall;e={...e,...s},fn(t,e);let S=Zt.getForInstance(e.plugins);o.length=0,o.push(...S),L=(kn=(Ln=e.launcher)==null?void 0:Ln.enabled)!=null?kn:!0,Q=(Rn=(Bn=e.launcher)==null?void 0:Bn.autoExpand)!=null?Rn:!1,ke=(In=(Hn=e.features)==null?void 0:Hn.showReasoning)!=null?In:!0,re=(Nn=(Pn=e.features)==null?void 0:Pn.showToolCalls)!=null?Nn:!0,((Fn=e.launcher)==null?void 0:Fn.enabled)===!1&&O&&(O.destroy(),O=null),((Dn=e.launcher)==null?void 0:Dn.enabled)!==!1&&!O&&(O=wn(e,pe),t.appendChild(O.element)),O&&O.update(e),L!==y?L?$e(Q):(B=!0,ht()):Q!==R&&$e(Q),R=Q,y=L,xe(),h(),JSON.stringify(s.toolCall)!==JSON.stringify(l)&&F&&wt(ne,F.getMessages(),g);let x=(qn=e.launcher)!=null?qn:{},U=(zn=x.headerIconHidden)!=null?zn:!1,Se=x.headerIconName,$=(On=x.headerIconSize)!=null?On:"48px";if(ve){let C=he.querySelector(".tvw-border-b-cw-divider"),We=C==null?void 0:C.querySelector(".tvw-flex-col");if(U)ve.style.display="none",C&&We&&!C.contains(We)&&C.insertBefore(We,C.firstChild);else{if(ve.style.display="",ve.style.height=$,ve.style.width=$,C&&We&&(C.contains(ve)?ve.nextSibling!==We&&(ve.remove(),C.insertBefore(ve,We)):C.insertBefore(ve,We)),Se){let qe=parseFloat($)||24,ge=Le(Se,qe*.6,"#ffffff",2);ge?ve.replaceChildren(ge):ve.textContent=($n=x.agentIconText)!=null?$n:"\u{1F4AC}"}else if(x.iconUrl){let qe=ve.querySelector("img");if(qe)qe.src=x.iconUrl,qe.style.height=$,qe.style.width=$;else{let ge=document.createElement("img");ge.src=x.iconUrl,ge.alt="",ge.className="tvw-rounded-xl tvw-object-cover",ge.style.height=$,ge.style.width=$,ve.replaceChildren(ge)}}else{let qe=ve.querySelector("svg"),ge=ve.querySelector("img");(qe||ge)&&ve.replaceChildren(),ve.textContent=(_n=x.agentIconText)!=null?_n:"\u{1F4AC}"}let Pe=ve.querySelector("img");Pe&&(Pe.style.height=$,Pe.style.width=$)}}if(E){let C=(jn=x.closeButtonSize)!=null?jn:"32px",We=(Un=x.closeButtonPlacement)!=null?Un:"inline";E.style.height=C,E.style.width=C;let Pe=We==="top-right",qe=E.classList.contains("tvw-absolute");if(Pe!==qe)if(E.remove(),Pe)E.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50 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",he.style.position="relative",he.appendChild(E);else{E.className="tvw-ml-auto 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";let oe=he.querySelector(".tvw-border-b-cw-divider");oe&&oe.appendChild(E)}if(x.closeButtonColor?(E.style.color=x.closeButtonColor,E.classList.remove("tvw-text-cw-muted")):(E.style.color="",E.classList.add("tvw-text-cw-muted")),x.closeButtonBackgroundColor?(E.style.backgroundColor=x.closeButtonBackgroundColor,E.classList.remove("hover:tvw-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:tvw-bg-gray-100")),x.closeButtonBorderWidth||x.closeButtonBorderColor){let oe=x.closeButtonBorderWidth||"0px",bt=x.closeButtonBorderColor||"transparent";E.style.border=`${oe} solid ${bt}`,E.classList.remove("tvw-border-none")}else E.style.border="",E.classList.add("tvw-border-none");x.closeButtonBorderRadius?(E.style.borderRadius=x.closeButtonBorderRadius,E.classList.remove("tvw-rounded-full")):(E.style.borderRadius="",E.classList.add("tvw-rounded-full")),x.closeButtonPaddingX?(E.style.paddingLeft=x.closeButtonPaddingX,E.style.paddingRight=x.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),x.closeButtonPaddingY?(E.style.paddingTop=x.closeButtonPaddingY,E.style.paddingBottom=x.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom="");let ge=(Vn=x.closeButtonIconName)!=null?Vn:"x",Mt=(Kn=x.closeButtonIconText)!=null?Kn:"\xD7";E.innerHTML="";let Ge=Le(ge,"20px",x.closeButtonColor||"",2);Ge?E.appendChild(Ge):E.textContent=Mt;let{closeButtonWrapper:Ke}=Ae,Te=(Xn=x.closeButtonTooltipText)!=null?Xn:"Close chat",Ze=(Yn=x.closeButtonShowTooltip)!=null?Yn:!0;if(E.setAttribute("aria-label",Te),Ke&&(Ke._cleanupTooltip&&(Ke._cleanupTooltip(),delete Ke._cleanupTooltip),Ze&&Te)){let oe=null,bt=()=>{if(oe||!E)return;oe=c("div","tvw-clear-chat-tooltip"),oe.textContent=Te;let Ao=c("div");Ao.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(Ao);let un=E.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${un.left+un.width/2}px`,oe.style.top=`${un.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},nt=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};Ke.addEventListener("mouseenter",bt),Ke.addEventListener("mouseleave",nt),E.addEventListener("focus",bt),E.addEventListener("blur",nt),Ke._cleanupTooltip=()=>{nt(),Ke&&(Ke.removeEventListener("mouseenter",bt),Ke.removeEventListener("mouseleave",nt)),E&&(E.removeEventListener("focus",bt),E.removeEventListener("blur",nt))}}}let{clearChatButton:A,clearChatButtonWrapper:f}=Ae;if(A){let C=(Jn=x.clearChat)!=null?Jn:{},We=(Gn=C.enabled)!=null?Gn:!0;if(f&&(f.style.display=We?"":"none"),We){let Pe=(Zn=C.size)!=null?Zn:"32px";A.style.height=Pe,A.style.width=Pe;let qe=(Qn=C.iconName)!=null?Qn:"refresh-cw",ge=(eo=C.iconColor)!=null?eo:"";A.innerHTML="";let Mt=Le(qe,"20px",ge||"",2);if(Mt&&A.appendChild(Mt),ge?(A.style.color=ge,A.classList.remove("tvw-text-cw-muted")):(A.style.color="",A.classList.add("tvw-text-cw-muted")),C.backgroundColor?(A.style.backgroundColor=C.backgroundColor,A.classList.remove("hover:tvw-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:tvw-bg-gray-100")),C.borderWidth||C.borderColor){let Te=C.borderWidth||"0px",Ze=C.borderColor||"transparent";A.style.border=`${Te} solid ${Ze}`,A.classList.remove("tvw-border-none")}else A.style.border="",A.classList.add("tvw-border-none");C.borderRadius?(A.style.borderRadius=C.borderRadius,A.classList.remove("tvw-rounded-full")):(A.style.borderRadius="",A.classList.add("tvw-rounded-full")),C.paddingX?(A.style.paddingLeft=C.paddingX,A.style.paddingRight=C.paddingX):(A.style.paddingLeft="",A.style.paddingRight=""),C.paddingY?(A.style.paddingTop=C.paddingY,A.style.paddingBottom=C.paddingY):(A.style.paddingTop="",A.style.paddingBottom="");let Ge=(to=C.tooltipText)!=null?to:"Clear chat",Ke=(no=C.showTooltip)!=null?no:!0;if(A.setAttribute("aria-label",Ge),f&&(f._cleanupTooltip&&(f._cleanupTooltip(),delete f._cleanupTooltip),Ke&&Ge)){let Te=null,Ze=()=>{if(Te||!A)return;Te=c("div","tvw-clear-chat-tooltip"),Te.textContent=Ge;let bt=c("div");bt.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(bt);let nt=A.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${nt.left+nt.width/2}px`,Te.style.top=`${nt.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},oe=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};f.addEventListener("mouseenter",Ze),f.addEventListener("mouseleave",oe),A.addEventListener("focus",Ze),A.addEventListener("blur",oe),f._cleanupTooltip=()=>{oe(),f&&(f.removeEventListener("mouseenter",Ze),f.removeEventListener("mouseleave",oe)),A&&(A.removeEventListener("focus",Ze),A.removeEventListener("blur",oe))}}}}let V=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Qt],K=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Kt.message,Kt.messageAndClick];q=en({parsers:V,handlers:K,getMetadata:P,updateMetadata:u,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),g=Do(e,q),F.updateConfig(e),wt(ne,F.getMessages(),g),ut.render(e.suggestionChips,F,Z),Bt(),Tt(F.isStreaming());let Ie=((oo=e.voiceRecognition)==null?void 0:oo.enabled)===!0,fe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Je=Ie&&fe;if(xt.classList.remove("tvw-gap-1","tvw-gap-3"),xt.classList.add(Je?"tvw-gap-1":"tvw-gap-3"),Ie&&fe)if(!b||!X){let C=p(e.voiceRecognition,e.sendButton);C&&(b=C.micButton,X=C.micButtonWrapper,xt.insertBefore(X,rt),b.addEventListener("click",_),b.disabled=F.isStreaming())}else{let C=(ro=e.voiceRecognition)!=null?ro:{},We=(so=e.sendButton)!=null?so:{},Pe=(io=C.iconName)!=null?io:"mic",qe=(ao=We.size)!=null?ao:"40px",ge=(lo=C.iconSize)!=null?lo:qe,Mt=parseFloat(ge)||24;b.style.width=ge,b.style.height=ge,b.style.minWidth=ge,b.style.minHeight=ge;let Ge=(uo=(co=C.iconColor)!=null?co:We.textColor)!=null?uo:"currentColor";b.innerHTML="";let Ke=Le(Pe,Mt,Ge,2);Ke?b.appendChild(Ke):b.textContent="\u{1F3A4}";let Te=(go=C.backgroundColor)!=null?go:We.backgroundColor;Te?(b.style.backgroundColor=Te,b.classList.remove("tvw-bg-cw-primary")):(b.style.backgroundColor="",b.classList.add("tvw-bg-cw-primary")),Ge?(b.style.color=Ge,b.classList.remove("tvw-text-white")):!Ge&&!We.textColor&&(b.style.color="",b.classList.add("tvw-text-white")),C.borderWidth?(b.style.borderWidth=C.borderWidth,b.style.borderStyle="solid"):(b.style.borderWidth="",b.style.borderStyle=""),C.borderColor?b.style.borderColor=C.borderColor:b.style.borderColor="",C.paddingX?(b.style.paddingLeft=C.paddingX,b.style.paddingRight=C.paddingX):(b.style.paddingLeft="",b.style.paddingRight=""),C.paddingY?(b.style.paddingTop=C.paddingY,b.style.paddingBottom=C.paddingY):(b.style.paddingTop="",b.style.paddingBottom="");let Ze=X==null?void 0:X.querySelector(".tvw-send-button-tooltip"),oe=(po=C.tooltipText)!=null?po:"Start voice recognition";if(((mo=C.showTooltip)!=null?mo:!1)&&oe)if(Ze)Ze.textContent=oe,Ze.style.display="";else{let nt=document.createElement("div");nt.className="tvw-send-button-tooltip",nt.textContent=oe,X==null||X.insertBefore(nt,b)}else Ze&&(Ze.style.display="none");X.style.display="",b.disabled=F.isStreaming()}else b&&X&&(X.style.display="none",_e&&Xe());let te=(fo=e.sendButton)!=null?fo:{},tt=(wo=te.useIcon)!=null?wo:!1,yt=(ho=te.iconText)!=null?ho:"\u2191",ct=te.iconName,Pt=(vo=te.tooltipText)!=null?vo:"Send message",Ut=(yo=te.showTooltip)!=null?yo:!1,Ee=(bo=te.size)!=null?bo:"40px",pt=te.backgroundColor,je=te.textColor;if(tt){if(M.style.width=Ee,M.style.height=Ee,M.style.minWidth=Ee,M.style.minHeight=Ee,M.style.fontSize="18px",M.style.lineHeight="1",M.innerHTML="",ct){let C=parseFloat(Ee)||24,We=je&&typeof je=="string"&&je.trim()?je.trim():"currentColor",Pe=Le(ct,C,We,2);Pe?(M.appendChild(Pe),M.style.color=We):(M.textContent=yt,je?M.style.color=je:M.classList.add("tvw-text-white"))}else M.textContent=yt,je?M.style.color=je:M.classList.add("tvw-text-white");M.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",pt?(M.style.backgroundColor=pt,M.classList.remove("tvw-bg-cw-primary")):M.classList.add("tvw-bg-cw-primary")}else M.textContent=(Co=(xo=e.copy)==null?void 0:xo.sendButtonLabel)!=null?Co:"Send",M.style.width="",M.style.height="",M.style.minWidth="",M.style.minHeight="",M.style.fontSize="",M.style.lineHeight="",M.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",pt?(M.style.backgroundColor=pt,M.classList.remove("tvw-bg-cw-accent")):M.classList.add("tvw-bg-cw-accent"),je?M.style.color=je:M.classList.add("tvw-text-white");te.borderWidth?(M.style.borderWidth=te.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),te.borderColor?M.style.borderColor=te.borderColor:M.style.borderColor="",te.paddingX?(M.style.paddingLeft=te.paddingX,M.style.paddingRight=te.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),te.paddingY?(M.style.paddingTop=te.paddingY,M.style.paddingBottom=te.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Nt=rt==null?void 0:rt.querySelector(".tvw-send-button-tooltip");if(Ut&&Pt)if(Nt)Nt.textContent=Pt,Nt.style.display="";else{let C=document.createElement("div");C.className="tvw-send-button-tooltip",C.textContent=Pt,rt==null||rt.insertBefore(C,M)}else Nt&&(Nt.style.display="none");let At=(So=e.statusIndicator)!=null?So:{},Oo=(To=At.visible)!=null?To:!0;if(qt.style.display=Oo?"":"none",F){let C=F.getStatus(),We=Pe=>{var qe,ge,Mt,Ge;return Pe==="idle"?(qe=At.idleText)!=null?qe:Ue.idle:Pe==="connecting"?(ge=At.connectingText)!=null?ge:Ue.connecting:Pe==="connected"?(Mt=At.connectedText)!=null?Mt:Ue.connected:Pe==="error"?(Ge=At.errorText)!=null?Ge:Ue.error:Ue[Pe]};qt.textContent=We(C)}},open(){L&&$e(!0)},close(){L&&$e(!1)},toggle(){L&&$e(!B)},clearChat(){F.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let s=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(s),a!=null&&a.clear)try{let l=a.clear();l instanceof Promise&&l.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",l)}w={},q.syncFromMetadata()},setMessage(s){return!Z||F.isStreaming()?!1:(!B&&L&&$e(!0),Z.value=s,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(F.isStreaming())return!1;let l=(s==null?void 0:s.trim())||Z.value.trim();return l?(!B&&L&&$e(!0),Z.value="",F.sendMessage(l),!0):!1},startVoiceRecognition(){return _e||F.isStreaming()||!It()?!1:(!B&&L&&$e(!0),be.manuallyDeactivated=!1,at(),vt("user"),!0)},stopVoiceRecognition(){return _e?(be.manuallyDeactivated=!0,at(),Xe("user"),!0):!1},injectTestMessage(s){!B&&L&&$e(!0),F.injectTestEvent(s)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...w}},updatePersistentMetadata(s){u(s)},on(s,l){return i.on(s,l)},off(s,l){i.off(s,l)},destroy(){ze.forEach(s=>s()),we.remove(),O==null||O.destroy(),Qe&&E.removeEventListener("click",Qe)}};if((((He=r==null?void 0:r.debugTools)!=null?He:!1)||!!e.debug)&&typeof window!="undefined"){let s=window.AgentWidgetBrowser,l={controller:N,getMessages:N.getMessages,getStatus:N.getStatus,getMetadata:N.getPersistentMetadata,updateMetadata:N.updatePersistentMetadata,clearHistory:()=>N.clearChat(),setVoiceActive:S=>S?N.startVoiceRecognition():N.stopVoiceRecognition()};window.AgentWidgetBrowser=l,ze.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=s)})}return N};var En={},lr=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let n=document.querySelector(t);if(!n)throw new Error(`Chat widget target "${t}" was not found`);return n}return t},dr=()=>{try{if(typeof En!="undefined"&&En.url)return new URL("../widget.css",En.url).href}catch{}return null},qo=t=>{let n=dr(),r=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let o=e.cloneNode(!0);t.insertBefore(o,t.firstChild)};if(t instanceof ShadowRoot)if(n){let e=document.createElement("link");e.rel="stylesheet",e.href=n,e.setAttribute("data-vanilla-agent","true"),t.insertBefore(e,t.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},Wn=t=>{var v;let n=lr(t.target),r=document.createElement("div");r.className="vanilla-agent-host",n.appendChild(r);let e=t.useShadowDom!==!1,o,i;if(e){let P=r.attachShadow({mode:"open"});i=P,o=document.createElement("div"),o.id="vanilla-agent-root",P.appendChild(o),qo(P)}else i=r,o=document.createElement("div"),o.id="vanilla-agent-root",r.appendChild(o),qo(r);let a=cn(o,t.config,{debugTools:t.debugTools});(v=t.onReady)==null||v.call(t);let w={...a,host:r,destroy(){a.destroy(),r.remove(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}};return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=w),w};var cr=t=>{if(!t)return null;try{return JSON.parse(t)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},ur=t=>t.map(n=>({...n,streaming:!1})),zo=(t="vanilla-agent-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?cr(r.getItem(t)):null},save:r=>{let e=n();if(e)try{let o={...r,messages:r.messages?ur(r.messages):void 0};e.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(t)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var gr=Wn;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_WIDGET_CONFIG,createActionManager,createAgentExperience,createJsonStreamParser,createLocalStorageAdapter,createPlainTextParser,createRegexJsonParser,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,initAgentWidget,markdownPostprocessor,mergeWithDefaults,pluginRegistry});
14
+ `,r.addEventListener("click",n);let e=s=>{var Q,R,y,B,g,ke,re,Ne,Be,we;let a=(Q=s.launcher)!=null?Q:{},m=r.querySelector("[data-role='launcher-title']");m&&(m.textContent=(R=a.title)!=null?R:"Chat Assistant");let v=r.querySelector("[data-role='launcher-subtitle']");v&&(v.textContent=(y=a.subtitle)!=null?y:"Get answers fast");let P=r.querySelector(".tvw-flex-col");P&&(a.textHidden?P.style.display="none":P.style.display="");let u=r.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ee=(B=a.agentIconSize)!=null?B:"40px";if(u.style.height=ee,u.style.width=ee,u.innerHTML="",a.agentIconName){let Ae=parseFloat(ee)||24,he=Le(a.agentIconName,Ae*.6,"#ffffff",2);he?(u.appendChild(he),u.style.display=""):(u.textContent=(g=a.agentIconText)!=null?g:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(ke=a.agentIconText)!=null?ke:"\u{1F4AC}",u.style.display="")}let I=r.querySelector("[data-role='launcher-image']");if(I){let ee=(re=a.agentIconSize)!=null?re:"40px";I.style.height=ee,I.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(I.src=a.iconUrl,I.style.display="block"):I.style.display="none"}let k=r.querySelector("[data-role='launcher-call-to-action-icon']");if(k){let ee=(Ne=a.callToActionIconSize)!=null?Ne:"32px";k.style.height=ee,k.style.width=ee,a.callToActionIconBackgroundColor?(k.style.backgroundColor=a.callToActionIconBackgroundColor,k.classList.remove("tvw-bg-cw-primary")):(k.style.backgroundColor="",k.classList.add("tvw-bg-cw-primary"));let Ae=0;if(a.callToActionIconPadding?(k.style.boxSizing="border-box",k.style.padding=a.callToActionIconPadding,Ae=(parseFloat(a.callToActionIconPadding)||0)*2):(k.style.boxSizing="",k.style.padding=""),a.callToActionIconHidden)k.style.display="none";else if(k.style.display="",k.innerHTML="",a.callToActionIconName){let he=parseFloat(ee)||24,Y=Math.max(he-Ae,8),ne=Le(a.callToActionIconName,Y,"currentColor",2);ne?k.appendChild(ne):k.textContent=(Be=a.callToActionIconText)!=null?Be:"\u2197"}else k.textContent=(we=a.callToActionIconText)!=null?we:"\u2197"}let q=a.position&&Dt[a.position]?Dt[a.position]:Dt["bottom-right"],L="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-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${L} ${q}`},o=()=>{r.removeEventListener("click",n),r.remove()};return t&&e(t),{element:r,update:e,destroy:o}};var Ro=t=>{var v,P,u,I,k;if(!((P=(v=t==null?void 0:t.launcher)==null?void 0:v.enabled)!=null?P:!0)){let q=c("div","tvw-relative tvw-w-full tvw-h-full"),L=c("div","tvw-relative tvw-w-full tvw-h-full tvw-min-h-[360px]");return q.appendChild(L),{wrapper:q,panel:L}}let r=(u=t==null?void 0:t.launcher)!=null?u:{},e=r.position&&Dt[r.position]?Dt[r.position]:Dt["bottom-right"],o=c("div",`tvw-fixed ${e} tvw-z-50 tvw-transition`),s=c("div","tvw-relative tvw-min-h-[320px]"),a=(k=(I=t==null?void 0:t.launcher)==null?void 0:I.width)!=null?k:t==null?void 0:t.launcherWidth,m=a!=null?a:"min(400px, calc(100vw - 24px))";return s.style.width=m,s.style.maxWidth=m,o.appendChild(s),{wrapper:o,panel:s}},Ho=(t,n=!0)=>{var Lt,kt,at,Ot,_t,Bt,ft,lt,$t,jt,Ut,wt,ht,_e,Tt,Rt,Ht,It,De,$e,dt,et,Pt,vt,Xe,p,$,G,pe,O,be,ce,h,Ye,N,f,d,H,ae,le,ue,Re,Me,de,j,ie,me,Ce,He,i,l,S,z,T,W,b,U,Se,_,A;let r=c("div","tvw-flex tvw-h-full tvw-w-full tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-shadow-2xl tvw-border tvw-border-cw-border"),e=c("div","tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(Lt=t==null?void 0:t.launcher)!=null?Lt:{},s=(kt=o.headerIconSize)!=null?kt:"48px",a=(at=o.closeButtonSize)!=null?at:"32px",m=(Ot=o.closeButtonPlacement)!=null?Ot:"inline",v=(_t=o.headerIconHidden)!=null?_t:!1,P=o.headerIconName,u=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(u.style.height=s,u.style.width=s,!v)if(P){let w=parseFloat(s)||24,V=Le(P,w*.6,"#ffffff",2);V?u.replaceChildren(V):u.textContent=(ft=(Bt=t==null?void 0:t.launcher)==null?void 0:Bt.agentIconText)!=null?ft:"\u{1F4AC}"}else if((lt=t==null?void 0:t.launcher)!=null&&lt.iconUrl){let w=c("img");w.src=t.launcher.iconUrl,w.alt="",w.className="tvw-rounded-xl tvw-object-cover",w.style.height=s,w.style.width=s,u.replaceChildren(w)}else u.textContent=(jt=($t=t==null?void 0:t.launcher)==null?void 0:$t.agentIconText)!=null?jt:"\u{1F4AC}";let I=c("div","tvw-flex tvw-flex-col"),k=c("span","tvw-text-base tvw-font-semibold");k.textContent=(wt=(Ut=t==null?void 0:t.launcher)==null?void 0:Ut.title)!=null?wt:"Chat Assistant";let q=c("span","tvw-text-xs tvw-text-cw-muted");q.textContent=(_e=(ht=t==null?void 0:t.launcher)==null?void 0:ht.subtitle)!=null?_e:"Here to help you get answers fast",I.append(k,q),v?e.append(I):e.append(u,I);let L=(Tt=o.clearChat)!=null?Tt:{},Q=(Rt=L.enabled)!=null?Rt:!0,R=null,y=null;if(Q){let w=(Ht=L.size)!=null?Ht:"32px",V=(It=L.iconName)!=null?It:"refresh-cw",K=(De=L.iconColor)!=null?De:"",Ie=($e=L.backgroundColor)!=null?$e:"",fe=(dt=L.borderWidth)!=null?dt:"",Je=(et=L.borderColor)!=null?et:"",te=(Pt=L.borderRadius)!=null?Pt:"",tt=(vt=L.paddingX)!=null?vt:"",yt=(Xe=L.paddingY)!=null?Xe:"",ct=(p=L.tooltipText)!=null?p:"Clear chat",Nt=($=L.showTooltip)!=null?$:!0;y=c("div","tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),R=c("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"),R.style.height=w,R.style.width=w,R.type="button",R.setAttribute("aria-label",ct);let Vt=Le(V,"20px",K||"",2);if(Vt&&R.appendChild(Vt),K&&(R.style.color=K,R.classList.remove("tvw-text-cw-muted")),Ie&&(R.style.backgroundColor=Ie,R.classList.remove("hover:tvw-bg-gray-100")),fe||Je){let Ee=fe||"0px",pt=Je||"transparent";R.style.border=`${Ee} solid ${pt}`,R.classList.remove("tvw-border-none")}if(te&&(R.style.borderRadius=te,R.classList.remove("tvw-rounded-full")),tt?(R.style.paddingLeft=tt,R.style.paddingRight=tt):(R.style.paddingLeft="",R.style.paddingRight=""),yt?(R.style.paddingTop=yt,R.style.paddingBottom=yt):(R.style.paddingTop="",R.style.paddingBottom=""),y.appendChild(R),Nt&&ct&&R&&y){let Ee=null,pt=()=>{if(Ee||!R)return;Ee=c("div","tvw-clear-chat-tooltip"),Ee.textContent=ct;let Ft=c("div");Ft.className="tvw-clear-chat-tooltip-arrow",Ee.appendChild(Ft);let At=R.getBoundingClientRect();Ee.style.position="fixed",Ee.style.left=`${At.left+At.width/2}px`,Ee.style.top=`${At.top-8}px`,Ee.style.transform="translate(-50%, -100%)",document.body.appendChild(Ee)},je=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};y.addEventListener("mouseenter",pt),y.addEventListener("mouseleave",je),R.addEventListener("focus",pt),R.addEventListener("blur",je),y._cleanupTooltip=()=>{je(),y&&(y.removeEventListener("mouseenter",pt),y.removeEventListener("mouseleave",je)),R&&(R.removeEventListener("focus",pt),R.removeEventListener("blur",je))}}e.appendChild(y)}let B=c("div",m==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":Q?"":"tvw-ml-auto"),g=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");g.style.height=a,g.style.width=a,g.type="button";let ke=(G=o.closeButtonTooltipText)!=null?G:"Close chat",re=(pe=o.closeButtonShowTooltip)!=null?pe:!0;g.setAttribute("aria-label",ke),g.style.display=n?"":"none";let Ne=(O=o.closeButtonIconName)!=null?O:"x",Be=(be=o.closeButtonIconText)!=null?be:"\xD7",we=Le(Ne,"20px",o.closeButtonColor||"",2);if(we?g.appendChild(we):g.textContent=Be,o.closeButtonColor?(g.style.color=o.closeButtonColor,g.classList.remove("tvw-text-cw-muted")):(g.style.color="",g.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(g.style.backgroundColor=o.closeButtonBackgroundColor,g.classList.remove("hover:tvw-bg-gray-100")):(g.style.backgroundColor="",g.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let w=o.closeButtonBorderWidth||"0px",V=o.closeButtonBorderColor||"transparent";g.style.border=`${w} solid ${V}`,g.classList.remove("tvw-border-none")}else g.style.border="",g.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(g.style.borderRadius=o.closeButtonBorderRadius,g.classList.remove("tvw-rounded-full")):(g.style.borderRadius="",g.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(g.style.paddingLeft=o.closeButtonPaddingX,g.style.paddingRight=o.closeButtonPaddingX):(g.style.paddingLeft="",g.style.paddingRight=""),o.closeButtonPaddingY?(g.style.paddingTop=o.closeButtonPaddingY,g.style.paddingBottom=o.closeButtonPaddingY):(g.style.paddingTop="",g.style.paddingBottom=""),B.appendChild(g),re&&ke){let w=null,V=()=>{if(w)return;w=c("div","tvw-clear-chat-tooltip"),w.textContent=ke;let Ie=c("div");Ie.className="tvw-clear-chat-tooltip-arrow",w.appendChild(Ie);let fe=g.getBoundingClientRect();w.style.position="fixed",w.style.left=`${fe.left+fe.width/2}px`,w.style.top=`${fe.top-8}px`,w.style.transform="translate(-50%, -100%)",document.body.appendChild(w)},K=()=>{w&&w.parentNode&&(w.parentNode.removeChild(w),w=null)};B.addEventListener("mouseenter",V),B.addEventListener("mouseleave",K),g.addEventListener("focus",V),g.addEventListener("blur",K),B._cleanupTooltip=()=>{K(),B.removeEventListener("mouseenter",V),B.removeEventListener("mouseleave",K),g.removeEventListener("focus",V),g.removeEventListener("blur",K)}}m==="top-right"?(r.style.position="relative",r.appendChild(B)):e.appendChild(B);let ee=c("div","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");ee.id="vanilla-agent-scroll-container";let Ae=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),he=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");he.textContent=(h=(ce=t==null?void 0:t.copy)==null?void 0:ce.welcomeTitle)!=null?h:"Hello \u{1F44B}";let Y=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");Y.textContent=(N=(Ye=t==null?void 0:t.copy)==null?void 0:Ye.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",Ae.append(he,Y);let ne=c("div","tvw-flex tvw-flex-col tvw-gap-3");ee.append(Ae,ne);let qt=c("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),Z=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),M=((f=t==null?void 0:t.voiceRecognition)==null?void 0:f.enabled)===!0,rt=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),st=c("form",`tvw-flex tvw-items-end ${M&&rt?"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`);st.style.outline="none";let se=c("textarea");se.placeholder=(H=(d=t==null?void 0:t.copy)==null?void 0:d.inputPlaceholder)!=null?H:"Type your message\u2026",se.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",se.rows=1;let E=(le=(ae=t==null?void 0:t.theme)==null?void 0:ae.inputFontFamily)!=null?le:"sans-serif",ve=(Re=(ue=t==null?void 0:t.theme)==null?void 0:ue.inputFontWeight)!=null?Re:"400",x=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=x(E),se.style.fontWeight=ve,se.style.border="none",se.style.outline="none",se.style.borderWidth="0",se.style.borderStyle="none",se.style.borderColor="transparent",se.addEventListener("focus",()=>{se.style.border="none",se.style.outline="none",se.style.borderWidth="0",se.style.borderStyle="none",se.style.borderColor="transparent",se.style.boxShadow="none"}),se.addEventListener("blur",()=>{se.style.border="none",se.style.outline="none"});let X=(Me=t==null?void 0:t.sendButton)!=null?Me:{},ze=(de=X.useIcon)!=null?de:!1,ut=(j=X.iconText)!=null?j:"\u2191",Qe=X.iconName,F=(ie=X.tooltipText)!=null?ie:"Send message",Ct=(me=X.showTooltip)!=null?me:!1,Oe=(Ce=X.size)!=null?Ce:"40px",gt=X.backgroundColor,Fe=X.textColor,Ve=c("div","tvw-send-button-wrapper"),D=c("button",ze?"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(D.type="submit",ze){if(D.style.width=Oe,D.style.height=Oe,D.style.minWidth=Oe,D.style.minHeight=Oe,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",Qe){let w=parseFloat(Oe)||24,V=Fe&&typeof Fe=="string"&&Fe.trim()?Fe.trim():"currentColor",K=Le(Qe,w,V,2);K?(D.appendChild(K),D.style.color=V):(D.textContent=ut,Fe?D.style.color=Fe:D.classList.add("tvw-text-white"))}else D.textContent=ut,Fe?D.style.color=Fe:D.classList.add("tvw-text-white");gt?D.style.backgroundColor=gt:D.classList.add("tvw-bg-cw-primary")}else D.textContent=(i=(He=t==null?void 0:t.copy)==null?void 0:He.sendButtonLabel)!=null?i:"Send",Fe?D.style.color=Fe:D.classList.add("tvw-text-white");if(X.borderWidth&&(D.style.borderWidth=X.borderWidth,D.style.borderStyle="solid"),X.borderColor&&(D.style.borderColor=X.borderColor),X.paddingX?(D.style.paddingLeft=X.paddingX,D.style.paddingRight=X.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),X.paddingY?(D.style.paddingTop=X.paddingY,D.style.paddingBottom=X.paddingY):(D.style.paddingTop="",D.style.paddingBottom=""),Ct&&F){let w=c("div","tvw-send-button-tooltip");w.textContent=F,Ve.appendChild(w)}Ve.appendChild(D);let ye=(l=t==null?void 0:t.voiceRecognition)!=null?l:{},Wt=ye.enabled===!0,J=null,it=null,Yt=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Wt&&Yt){it=c("div","tvw-send-button-wrapper"),J=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),J.type="button",J.setAttribute("aria-label","Start voice recognition");let w=(S=ye.iconName)!=null?S:"mic",V=(z=ye.iconSize)!=null?z:Oe,K=parseFloat(V)||24,Ie=(T=ye.backgroundColor)!=null?T:gt,fe=(W=ye.iconColor)!=null?W:Fe;J.style.width=V,J.style.height=V,J.style.minWidth=V,J.style.minHeight=V,J.style.fontSize="18px",J.style.lineHeight="1";let Je=fe||"currentColor",te=Le(w,K,Je,1.5);te?(J.appendChild(te),J.style.color=Je):(J.textContent="\u{1F3A4}",J.style.color=Je),Ie?J.style.backgroundColor=Ie:J.classList.add("tvw-bg-cw-primary"),fe?J.style.color=fe:!fe&&!Fe&&J.classList.add("tvw-text-white"),ye.borderWidth&&(J.style.borderWidth=ye.borderWidth,J.style.borderStyle="solid"),ye.borderColor&&(J.style.borderColor=ye.borderColor),ye.paddingX&&(J.style.paddingLeft=ye.paddingX,J.style.paddingRight=ye.paddingX),ye.paddingY&&(J.style.paddingTop=ye.paddingY,J.style.paddingBottom=ye.paddingY),it.appendChild(J);let tt=(b=ye.tooltipText)!=null?b:"Start voice recognition";if(((U=ye.showTooltip)!=null?U:!1)&&tt){let ct=c("div","tvw-send-button-tooltip");ct.textContent=tt,it.appendChild(ct)}}st.addEventListener("click",w=>{w.target!==D&&w.target!==Ve&&w.target!==J&&w.target!==it&&se.focus()}),st.append(se),it&&st.append(it),st.append(Ve);let mt=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),St=(Se=t==null?void 0:t.statusIndicator)!=null?Se:{},xe=(_=St.visible)!=null?_:!0;return mt.style.display=xe?"":"none",mt.textContent=(A=St.idleText)!=null?A:"Online",qt.append(Z,st,mt),r.append(e,ee,qt),{container:r,body:ee,messagesWrapper:ne,suggestions:Z,textarea:se,sendButton:D,sendButtonWrapper:Ve,micButton:J,micButtonWrapper:it,composerForm:st,statusText:mt,introTitle:he,introSubtitle:Y,closeButton:g,closeButtonWrapper:B,clearChatButton:R,clearChatButtonWrapper:y,iconHolder:u}};var hn=()=>{let t=document.createElement("div");t.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",t.appendChild(n),t.appendChild(r),t.appendChild(e),t.appendChild(o),t},vn=(t,n)=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"];t.role==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");let e=c("div",r.join(" ")),o=document.createElement("div");if(o.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(o),t.streaming&&t.role==="assistant"&&(!t.content||!t.content.trim())){let s=hn();e.appendChild(s)}return e};var yn=new Set,xn=t=>{let n=t.reasoning,r=c("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(!n)return r;let e=yn.has(t.id),o=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false");let s=c("div","tvw-flex tvw-flex-col tvw-text-left"),a=c("span","tvw-text-xs tvw-text-cw-primary");a.textContent="Thinking...",s.appendChild(a);let m=c("span","tvw-text-xs tvw-text-cw-primary");m.textContent=Lo(n),s.appendChild(m),n.status==="complete"?a.style.display="none":a.style.display="";let v=c("div","tvw-flex tvw-items-center"),u=Le(e?"chevron-up":"chevron-down",16,"currentColor",2);u?v.appendChild(u):v.textContent=e?"Hide":"Show";let I=c("div","tvw-flex tvw-items-center tvw-ml-auto");I.append(v),o.append(s,I);let k=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");k.style.display=e?"":"none";let q=n.chunks.join(""),L=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");L.textContent=q||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),k.appendChild(L);let Q=()=>{o.setAttribute("aria-expanded",e?"true":"false"),v.innerHTML="";let B=Le(e?"chevron-up":"chevron-down",16,"currentColor",2);B?v.appendChild(B):v.textContent=e?"Hide":"Show",k.style.display=e?"":"none"},R=()=>{e=!e,e?yn.add(t.id):yn.delete(t.id),Q()};return o.addEventListener("pointerdown",y=>{y.preventDefault(),R()}),o.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),R())}),Q(),r.append(o,k),r};var bn=new Set,Cn=(t,n)=>{var R;let r=t.toolCall,e=(R=n==null?void 0:n.toolCall)!=null?R:{},o=c("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(e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=bn.has(t.id),a=c("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",s?"true":"false"),e.headerBackgroundColor&&(a.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(a.style.paddingLeft=e.headerPaddingX,a.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(a.style.paddingTop=e.headerPaddingY,a.style.paddingBottom=e.headerPaddingY);let m=c("div","tvw-flex tvw-flex-col tvw-text-left"),v=c("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(v.style.color=e.headerTextColor),v.textContent=ko(r),m.appendChild(v);let P=c("div","tvw-flex tvw-items-center"),u=e.toggleTextColor||e.headerTextColor||"currentColor",I=Le(s?"chevron-up":"chevron-down",16,u,2);I?P.appendChild(I):P.textContent=s?"Hide":"Show";let k=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");k.append(P),a.append(m,k);let q=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(q.style.display=s?"":"none",e.contentBackgroundColor&&(q.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(q.style.color=e.contentTextColor),e.contentPaddingX&&(q.style.paddingLeft=e.contentPaddingX,q.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(q.style.paddingTop=e.contentPaddingY,q.style.paddingBottom=e.contentPaddingY),r.name){let y=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?y.style.color=e.contentTextColor:e.headerTextColor&&(y.style.color=e.headerTextColor),y.textContent=r.name,q.appendChild(y)}if(r.args!==void 0){let y=c("div","tvw-space-y-1"),B=c("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(B.style.color=e.labelTextColor),B.textContent="Arguments";let g=c("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");g.style.fontSize="0.75rem",g.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(g.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(g.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(g.style.color=e.codeBlockTextColor),g.textContent=mn(r.args),y.append(B,g),q.appendChild(y)}if(r.chunks&&r.chunks.length){let y=c("div","tvw-space-y-1"),B=c("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(B.style.color=e.labelTextColor),B.textContent="Activity";let g=c("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");g.style.fontSize="0.75rem",g.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(g.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(g.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(g.style.color=e.codeBlockTextColor),g.textContent=r.chunks.join(`
15
+ `),y.append(B,g),q.appendChild(y)}if(r.status==="complete"&&r.result!==void 0){let y=c("div","tvw-space-y-1"),B=c("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(B.style.color=e.labelTextColor),B.textContent="Result";let g=c("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");g.style.fontSize="0.75rem",g.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(g.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(g.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(g.style.color=e.codeBlockTextColor),g.textContent=mn(r.result),y.append(B,g),q.appendChild(y)}if(r.status==="complete"&&typeof r.duration=="number"){let y=c("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(y.style.color=e.contentTextColor),y.textContent=`Duration: ${r.duration}ms`,q.appendChild(y)}let L=()=>{a.setAttribute("aria-expanded",s?"true":"false"),P.innerHTML="";let y=e.toggleTextColor||e.headerTextColor||"currentColor",B=Le(s?"chevron-up":"chevron-down",16,y,2);B?P.appendChild(B):P.textContent=s?"Hide":"Show",q.style.display=s?"":"none"},Q=()=>{s=!s,s?bn.add(t.id):bn.delete(t.id),L()};return a.addEventListener("pointerdown",y=>{y.preventDefault(),Q()}),a.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),Q())}),L(),o.append(a,q),o};var Io=t=>{let n=[];return{buttons:n,render:(e,o,s,a)=>{if(t.innerHTML="",n.length=0,!e||!e.length||(a!=null?a:o?o.getMessages():[]).some(I=>I.role==="user"))return;let P=document.createDocumentFragment(),u=o?o.isStreaming():!1;e.forEach(I=>{let k=c("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");k.type="button",k.textContent=I,k.disabled=u,k.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(I))}),P.appendChild(k),n.push(k)}),t.appendChild(P)}}};var Po={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"}},Sn=(t,n,r,e)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var L,Q,R;if(s.dataset.enhanced==="true")return;let a=(L=s.dataset.tvForm)!=null?L:"init";s.dataset.enhanced="true";let m=(Q=Po[a])!=null?Q:Po.init;s.classList.add("tvw-form-card","tvw-space-y-4");let v=c("div","tvw-space-y-1"),P=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(P.textContent=m.title,v.appendChild(P),m.description){let y=c("p","tvw-text-sm tvw-text-cw-muted");y.textContent=m.description,v.appendChild(y)}let u=document.createElement("form");u.className="tvw-form-grid tvw-space-y-3",m.fields.forEach(y=>{var Ne,Be;let B=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");B.htmlFor=`${n.id}-${a}-${y.name}`;let g=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");g.textContent=y.label,B.appendChild(g);let ke=(Ne=y.type)!=null?Ne:"text",re;ke==="textarea"?(re=document.createElement("textarea"),re.rows=3):(re=document.createElement("input"),re.type=ke),re.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",re.id=`${n.id}-${a}-${y.name}`,re.name=y.name,re.placeholder=(Be=y.placeholder)!=null?Be:"",y.required&&(re.required=!0),B.appendChild(re),u.appendChild(B)});let I=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),k=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),q=c("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");q.type="submit",q.textContent=(R=m.submitLabel)!=null?R:"Submit",I.appendChild(k),I.appendChild(q),u.appendChild(I),s.replaceChildren(v,u),u.addEventListener("submit",async y=>{var re,Ne;y.preventDefault();let B=(re=r.formEndpoint)!=null?re:"/form",g=new FormData(u),ke={};g.forEach((Be,we)=>{ke[we]=Be}),ke.type=a,q.disabled=!0,k.textContent="Submitting\u2026";try{let Be=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ke)});if(!Be.ok)throw new Error(`Form submission failed (${Be.status})`);let we=await Be.json();k.textContent=(Ne=we.message)!=null?Ne:"Thanks! We'll be in touch soon.",we.success&&we.nextPrompt&&await e.sendMessage(String(we.nextPrompt))}catch(Be){k.textContent=Be instanceof Error?Be.message:"Something went wrong. Please try again."}finally{q.disabled=!1}})})};var Tn=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var e;let r=this.plugins.get(n);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let e=new Set(n.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...n].sort((s,a)=>{var m,v;return((m=a.priority)!=null?m:0)-((v=s.priority)!=null?v:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},Zt=new Tn;var ot={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",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,iconName:"refresh-cw",size:"29px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!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?"],debug:!1};function dn(t){var n,r,e;return t?{...ot,...t,theme:{...ot.theme,...t.theme},launcher:{...ot.launcher,...t.launcher,clearChat:{...(n=ot.launcher)==null?void 0:n.clearChat,...(r=t.launcher)==null?void 0:r.clearChat}},copy:{...ot.copy,...t.copy},sendButton:{...ot.sendButton,...t.sendButton},statusIndicator:{...ot.statusIndicator,...t.statusIndicator},voiceRecognition:{...ot.voiceRecognition,...t.voiceRecognition},features:{...ot.features,...t.features},suggestionChips:(e=t.suggestionChips)!=null?e:ot.suggestionChips}:ot}var No=()=>{let t=new Map,n=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:n,off:r,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(m=>{try{m(s)}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",v)}})}}};var ir=t=>{let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:t},ar=t=>{let n=t.trim(),r=n.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return n.slice(r,o+1)}return null},Qt=({text:t})=>{if(!t||!t.includes("{"))return null;try{let n=ir(t),r=ar(n);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},An=t=>typeof t=="string"?t:t==null?"":String(t),Xt={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:An(t.payload.text)},messageAndClick:(t,n)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,e=An(r.element);if(e&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:An(r.text)}}},Fo=t=>Array.isArray(t)?t.map(n=>String(n)):[],en=t=>{let n=new Set(Fo(t.getMetadata().processedActionMessageIds)),r=()=>{n=new Set(Fo(t.getMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(n);t.updateMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let m=a?t.parsers.reduce((P,u)=>P||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!m)return null;n.add(s.message.id),e();let v={action:m,message:s.message};t.emit("action:detected",v);for(let P of t.handlers)if(P)try{let u=P(m,{message:s.message,metadata:t.getMetadata(),updateMetadata:t.updateMetadata,document:t.documentRef});if(!u)continue;if(u.displayText!==void 0&&u.handled)return u.displayText;if(u.handled)return""}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return""},syncFromMetadata:r}};var Gt="vanilla-agent-chat-history",lr=30*1e3,Mn=t=>!t||typeof t!="object"?{}:{...t},Do=t=>t.map(n=>({...n,streaming:!1})),qo=(t,n)=>r=>{var s,a,m;let e=(s=r.text)!=null?s:"",o=(a=r.message.rawContent)!=null?a:null;if(n){let v=n.process({text:e,raw:o!=null?o:e,message:r.message,streaming:r.streaming});v!==null&&(e=v)}return t!=null&&t.postprocessMessage?t.postprocessMessage({...r,text:e,raw:(m=o!=null?o:r.text)!=null?m:""}):nn(e)},cn=(t,n,r)=>{var d,H,ae,le,ue,Re,Me,de,j,ie,me,Ce,He;(!t.id||t.id!=="vanilla-agent-root")&&(t.id="vanilla-agent-root");let e=dn(n);fn(t,e);let o=Zt.getForInstance(e.plugins),s=No(),a=e.storageAdapter,m={},v=null;if(a!=null&&a.load)try{let i=a.load();if(i&&typeof i.then=="function")v=i;else if(i){let l=i;l.metadata&&(m=Mn(l.metadata)),(d=l.messages)!=null&&d.length&&(e={...e,initialMessages:l.messages})}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",i)}let P=()=>m,u=i=>{var S;m=(S=i({...m}))!=null?S:{},Bt()},I=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Qt],k=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xt.message,Xt.messageAndClick],q=en({parsers:I,handlers:k,getMetadata:P,updateMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});q.syncFromMetadata();let L=(ae=(H=e.launcher)==null?void 0:H.enabled)!=null?ae:!0,Q=(ue=(le=e.launcher)==null?void 0:le.autoExpand)!=null?ue:!1,R=Q,y=L,B=L?Q:!0,g=qo(e,q),ke=(Me=(Re=e.features)==null?void 0:Re.showReasoning)!=null?Me:!0,re=(j=(de=e.features)==null?void 0:de.showToolCalls)!=null?j:!0,Ne=(ie=e.statusIndicator)!=null?ie:{},Be=i=>{var l,S,z,T;return i==="idle"?(l=Ne.idleText)!=null?l:Ue.idle:i==="connecting"?(S=Ne.connectingText)!=null?S:Ue.connecting:i==="connected"?(z=Ne.connectedText)!=null?z:Ue.connected:i==="error"?(T=Ne.errorText)!=null?T:Ue.error:Ue[i]},{wrapper:we,panel:ee}=Ro(e),Ae=Ho(e,L),{container:he,body:Y,messagesWrapper:ne,suggestions:qt,textarea:Z,sendButton:M,sendButtonWrapper:rt,composerForm:bt,statusText:zt,introTitle:st,introSubtitle:se,closeButton:E,iconHolder:ve}=Ae,x=Ae.micButton,X=Ae.micButtonWrapper;ee.appendChild(he),t.appendChild(we);let ze=[],ut=Io(qt),Qe=null,F,Ct=!1,Oe=!0,gt=0,Fe=0,Ve=null,D=!1,ye=0,Wt=!1,J=125,it=2e3,Yt=5,mt=50,St=new Map,xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Lt=(Ce=(me=e.voiceRecognition)==null?void 0:me.autoResume)!=null?Ce:!1,kt=i=>{s.emit("voice:state",{active:xe.active,source:i,timestamp:Date.now()})},at=()=>{u(i=>({...i,voiceState:{active:xe.active,timestamp:Date.now(),manuallyDeactivated:xe.manuallyDeactivated}}))},Ot=()=>{var z,T;if(((z=e.voiceRecognition)==null?void 0:z.enabled)===!1)return;let i=Mn(m.voiceState),l=!!i.active,S=Number((T=i.timestamp)!=null?T:0);xe.manuallyDeactivated=!!i.manuallyDeactivated,l&&Date.now()-S<lr&&setTimeout(()=>{xe.active||(xe.manuallyDeactivated=!1,vt("restore"))},1e3)},_t=()=>F?Do(F.getMessages()):[];function Bt(i){if(!(a!=null&&a.save)||!F)return;let l={messages:i?Do(i):_t(),metadata:m};try{let S=a.save(l);S instanceof Promise&&S.catch(z=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",z)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let ft=(i=!1)=>{if(!Oe)return;let l=Date.now();D&&l<ye&&!i||(D&&l>=ye&&(D=!1),!(!i&&!Ct)&&(l-Fe<J||(Fe=l,Ve&&cancelAnimationFrame(Ve),Ve=requestAnimationFrame(()=>{D||!Oe||(Wt=!0,Y.scrollTop=Y.scrollHeight,gt=Y.scrollTop,requestAnimationFrame(()=>{Wt=!1}),Ve=null)}))))},lt=null,$t=()=>we.querySelector("#vanilla-agent-scroll-container")||Y,jt=(i,l=500)=>{let S=i.scrollTop,z=i.clientHeight,T=i.scrollHeight,W=T-S;if(S+z>=T-2||Math.abs(W)<5)return;lt!==null&&(cancelAnimationFrame(lt),lt=null);let U=performance.now(),Se=A=>1-Math.pow(1-A,3),_=A=>{let w=i.scrollHeight;w!==T&&(T=w,W=T-S);let V=A-U,K=Math.min(V/l,1),Ie=Se(K),fe=S+W*Ie;i.scrollTop=fe,K<1?lt=requestAnimationFrame(_):(i.scrollTop=i.scrollHeight,lt=null)};lt=requestAnimationFrame(_)},Ut=i=>{let l=new Map;i.forEach(S=>{let z=St.get(S.id);l.set(S.id,{streaming:S.streaming,role:S.role}),!z&&S.role==="assistant"&&s.emit("assistant:message",S),S.role==="assistant"&&(z!=null&&z.streaming)&&S.streaming===!1&&s.emit("assistant:complete",S)}),St.clear(),l.forEach((S,z)=>{St.set(z,S)})},wt=(i,l,S)=>{i.innerHTML="";let z=document.createDocumentFragment();l.forEach(W=>{let b=null,U=o.find(_=>!!(W.variant==="reasoning"&&_.renderReasoning||W.variant==="tool"&&_.renderToolCall||!W.variant&&_.renderMessage));if(U)if(W.variant==="reasoning"&&W.reasoning&&U.renderReasoning){if(!ke)return;b=U.renderReasoning({message:W,defaultRenderer:()=>xn(W),config:e})}else if(W.variant==="tool"&&W.toolCall&&U.renderToolCall){if(!re)return;b=U.renderToolCall({message:W,defaultRenderer:()=>Cn(W,e),config:e})}else U.renderMessage&&(b=U.renderMessage({message:W,defaultRenderer:()=>{let _=vn(W,S);return W.role!=="user"&&Sn(_,W,e,F),_},config:e}));if(!b)if(W.variant==="reasoning"&&W.reasoning){if(!ke)return;b=xn(W)}else if(W.variant==="tool"&&W.toolCall){if(!re)return;b=Cn(W,e)}else b=vn(W,S),W.role!=="user"&&Sn(b,W,e,F);let Se=document.createElement("div");Se.className="tvw-flex",W.role==="user"&&Se.classList.add("tvw-justify-end"),Se.appendChild(b),z.appendChild(Se)});let T=l.some(W=>W.role==="assistant"&&W.streaming);if(Ct&&l.some(W=>W.role==="user")&&!T){let W=hn(),b=document.createElement("div");b.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(" "),b.appendChild(W);let U=document.createElement("div");U.className="tvw-flex",U.appendChild(b),z.appendChild(U)}i.appendChild(z),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let W=$t();jt(W)})})},ht=()=>{L&&(B?(we.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ee.classList.remove("tvw-scale-95","tvw-opacity-0"),ee.classList.add("tvw-scale-100","tvw-opacity-100"),O&&(O.element.style.display="none")):(we.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ee.classList.remove("tvw-scale-100","tvw-opacity-100"),ee.classList.add("tvw-scale-95","tvw-opacity-0"),O&&(O.element.style.display="")))},_e=i=>{L&&B!==i&&(B=i,ht(),B&&(be(),ft(!0)))},Tt=i=>{Z.disabled=i,M.disabled=i,x&&(x.disabled=i),ut.buttons.forEach(l=>{l.disabled=i})},Rt=()=>{var T,W,b,U,Se,_,A,w,V,K,Ie,fe,Je,te;st.textContent=(W=(T=e.copy)==null?void 0:T.welcomeTitle)!=null?W:"Hello \u{1F44B}",se.textContent=(U=(b=e.copy)==null?void 0:b.welcomeSubtitle)!=null?U:"Ask anything about your account or products.",Z.placeholder=(_=(Se=e.copy)==null?void 0:Se.inputPlaceholder)!=null?_:"How can I help...",((w=(A=e.sendButton)==null?void 0:A.useIcon)!=null?w:!1)||(M.textContent=(K=(V=e.copy)==null?void 0:V.sendButtonLabel)!=null?K:"Send");let l=(fe=(Ie=e.theme)==null?void 0:Ie.inputFontFamily)!=null?fe:"sans-serif",S=(te=(Je=e.theme)==null?void 0:Je.inputFontWeight)!=null?te:"400",z=tt=>{switch(tt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};Z.style.fontFamily=z(l),Z.style.fontWeight=S};F=new Jt(e,{onMessagesChanged(i){wt(ne,i,g),F&&(i.some(z=>z.role==="user")?ut.render([],F,Z,i):ut.render(e.suggestionChips,F,Z,i)),ft(!Ct),Ut(i);let l=[...i].reverse().find(S=>S.role==="user");xe.lastUserMessageWasVoice=!!(l!=null&&l.viaVoice),Bt(i)},onStatusChanged(i){var z;let l=(z=e.statusIndicator)!=null?z:{},S=T=>{var W,b,U,Se;return T==="idle"?(W=l.idleText)!=null?W:Ue.idle:T==="connecting"?(b=l.connectingText)!=null?b:Ue.connecting:T==="connected"?(U=l.connectedText)!=null?U:Ue.connected:T==="error"?(Se=l.errorText)!=null?Se:Ue.error:Ue[T]};zt.textContent=S(i)},onStreamingChanged(i){Ct=i,Tt(i),F&&wt(ne,F.getMessages(),g),i||ft(!0)}}),v&&v.then(i=>{var l;i&&(i.metadata&&(m=Mn(i.metadata),q.syncFromMetadata()),(l=i.messages)!=null&&l.length&&F.hydrateMessages(i.messages))}).catch(i=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)});let Ht=i=>{i.preventDefault();let l=Z.value.trim();l&&(Z.value="",F.sendMessage(l))},It=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),M.click())},De=null,$e=!1,dt=null,et=null,Pt=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,vt=(i="user")=>{var W,b,U,Se;if($e||F.isStreaming())return;let l=Pt();if(!l)return;De=new l;let z=(b=((W=e.voiceRecognition)!=null?W:{}).pauseDuration)!=null?b:2e3;De.continuous=!0,De.interimResults=!0,De.lang="en-US";let T=Z.value;De.onresult=_=>{let A="",w="";for(let K=0;K<_.results.length;K++){let Ie=_.results[K],fe=Ie[0].transcript;Ie.isFinal?A+=fe+" ":w=fe}let V=T+A+w;Z.value=V,dt&&clearTimeout(dt),(A||w)&&(dt=window.setTimeout(()=>{let K=Z.value.trim();K&&De&&$e&&(Xe(),Z.value="",F.sendMessage(K,{viaVoice:!0}))},z))},De.onerror=_=>{_.error!=="no-speech"&&Xe()},De.onend=()=>{if($e){let _=Z.value.trim();_&&_!==T.trim()&&(Z.value="",F.sendMessage(_,{viaVoice:!0})),Xe()}};try{if(De.start(),$e=!0,xe.active=!0,i!=="system"&&(xe.manuallyDeactivated=!1),kt(i),at(),x){et={backgroundColor:x.style.backgroundColor,color:x.style.color,borderColor:x.style.borderColor};let _=(U=e.voiceRecognition)!=null?U:{},A=(Se=_.recordingBackgroundColor)!=null?Se:"#ef4444",w=_.recordingIconColor,V=_.recordingBorderColor;if(x.classList.add("tvw-voice-recording"),x.style.backgroundColor=A,w){x.style.color=w;let K=x.querySelector("svg");K&&K.setAttribute("stroke",w)}V&&(x.style.borderColor=V),x.setAttribute("aria-label","Stop voice recognition")}}catch{Xe("system")}},Xe=(i="user")=>{if($e){if($e=!1,dt&&(clearTimeout(dt),dt=null),De){try{De.stop()}catch{}De=null}if(xe.active=!1,kt(i),at(),x){if(x.classList.remove("tvw-voice-recording"),et){x.style.backgroundColor=et.backgroundColor,x.style.color=et.color,x.style.borderColor=et.borderColor;let l=x.querySelector("svg");l&&l.setAttribute("stroke",et.color||"currentColor"),et=null}x.setAttribute("aria-label","Start voice recognition")}}},p=(i,l)=>{var fe,Je,te,tt,yt,ct,Nt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let z=c("div","tvw-send-button-wrapper"),T=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");T.type="button",T.setAttribute("aria-label","Start voice recognition");let W=(fe=i==null?void 0:i.iconName)!=null?fe:"mic",b=(Je=l==null?void 0:l.size)!=null?Je:"40px",U=(te=i==null?void 0:i.iconSize)!=null?te:b,Se=parseFloat(U)||24,_=(tt=i==null?void 0:i.backgroundColor)!=null?tt:l==null?void 0:l.backgroundColor,A=(yt=i==null?void 0:i.iconColor)!=null?yt:l==null?void 0:l.textColor;T.style.width=U,T.style.height=U,T.style.minWidth=U,T.style.minHeight=U,T.style.fontSize="18px",T.style.lineHeight="1";let w=A||"currentColor",V=Le(W,Se,w,1.5);V?(T.appendChild(V),T.style.color=w):(T.textContent="\u{1F3A4}",T.style.color=w),_?T.style.backgroundColor=_:T.classList.add("tvw-bg-cw-primary"),A?T.style.color=A:!A&&!(l!=null&&l.textColor)&&T.classList.add("tvw-text-white"),i!=null&&i.borderWidth&&(T.style.borderWidth=i.borderWidth,T.style.borderStyle="solid"),i!=null&&i.borderColor&&(T.style.borderColor=i.borderColor),i!=null&&i.paddingX&&(T.style.paddingLeft=i.paddingX,T.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(T.style.paddingTop=i.paddingY,T.style.paddingBottom=i.paddingY),z.appendChild(T);let K=(ct=i==null?void 0:i.tooltipText)!=null?ct:"Start voice recognition";if(((Nt=i==null?void 0:i.showTooltip)!=null?Nt:!1)&&K){let Vt=c("div","tvw-send-button-tooltip");Vt.textContent=K,z.appendChild(Vt)}return{micButton:T,micButtonWrapper:z}},$=()=>{if($e){let i=Z.value.trim();xe.manuallyDeactivated=!0,at(),Xe("user"),i&&(Z.value="",F.sendMessage(i))}else xe.manuallyDeactivated=!1,at(),vt("user")};x&&(x.addEventListener("click",$),ze.push(()=>{Xe("system"),x&&x.removeEventListener("click",$)}));let G=s.on("assistant:complete",()=>{Lt&&(xe.active||xe.manuallyDeactivated||Lt==="assistant"&&!xe.lastUserMessageWasVoice||setTimeout(()=>{!xe.active&&!xe.manuallyDeactivated&&vt("auto")},600))});ze.push(G);let pe=()=>{_e(!B)},O=L?wn(e,pe):null;O&&t.appendChild(O.element),ht(),ut.render(e.suggestionChips,F,Z),Rt(),Tt(F.isStreaming()),ft(!0),Ot();let be=()=>{var b,U;if(!L){ee.style.height="",ee.style.width="";return}let i=(U=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?U:e==null?void 0:e.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";ee.style.width=l,ee.style.maxWidth=l;let S=window.innerHeight,T=Math.max(200,S-64),W=Math.min(640,T);ee.style.height=`${W}px`};be(),window.addEventListener("resize",be),ze.push(()=>window.removeEventListener("resize",be)),gt=Y.scrollTop;let ce=()=>{let i=Y.scrollTop,l=Y.scrollHeight,S=Y.clientHeight,z=l-i-S,T=Math.abs(i-gt);if(gt=i,!Wt&&!(T<=Yt)){if(!Oe&&z<mt){D=!1,Oe=!0;return}Oe&&z>mt&&(D=!0,ye=Date.now()+it,Oe=!1)}};Y.addEventListener("scroll",ce,{passive:!0}),ze.push(()=>Y.removeEventListener("scroll",ce)),ze.push(()=>{Ve&&cancelAnimationFrame(Ve)});let h=()=>{E&&(Qe&&(E.removeEventListener("click",Qe),Qe=null),L?(E.style.display="",Qe=()=>{B=!1,ht()},E.addEventListener("click",Qe)):E.style.display="none")};h(),(()=>{let{clearChatButton:i}=Ae;i&&i.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(S){console.error("[AgentWidget] Failed to clear default localStorage:",S)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(S){console.error("[AgentWidget] Failed to clear custom localStorage:",S)}let l=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let S=a.clear();S instanceof Promise&&S.catch(z=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",z)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)}m={},q.syncFromMetadata()})})(),bt.addEventListener("submit",Ht),Z.addEventListener("keydown",It),ze.push(()=>{bt.removeEventListener("submit",Ht),Z.removeEventListener("keydown",It)}),ze.push(()=>{F.cancel()}),O&&ze.push(()=>{O==null||O.destroy()});let N={update(i){var Ln,kn,Bn,Rn,Hn,In,Pn,Nn,Fn,Dn,qn,zn,On,_n,$n,jn,Un,Vn,Kn,Xn,Yn,Jn,Gn,Zn,Qn,eo,to,no,oo,ro,so,io,ao,lo,co,uo,go,po,mo,fo,wo,ho,vo,yo,xo,bo,Co,So,To;let l=e.toolCall;e={...e,...i},fn(t,e);let S=Zt.getForInstance(e.plugins);o.length=0,o.push(...S),L=(kn=(Ln=e.launcher)==null?void 0:Ln.enabled)!=null?kn:!0,Q=(Rn=(Bn=e.launcher)==null?void 0:Bn.autoExpand)!=null?Rn:!1,ke=(In=(Hn=e.features)==null?void 0:Hn.showReasoning)!=null?In:!0,re=(Nn=(Pn=e.features)==null?void 0:Pn.showToolCalls)!=null?Nn:!0,((Fn=e.launcher)==null?void 0:Fn.enabled)===!1&&O&&(O.destroy(),O=null),((Dn=e.launcher)==null?void 0:Dn.enabled)!==!1&&!O&&(O=wn(e,pe),t.appendChild(O.element)),O&&O.update(e),L!==y?L?_e(Q):(B=!0,ht()):Q!==R&&_e(Q),R=Q,y=L,be(),h(),JSON.stringify(i.toolCall)!==JSON.stringify(l)&&F&&wt(ne,F.getMessages(),g);let b=(qn=e.launcher)!=null?qn:{},U=(zn=b.headerIconHidden)!=null?zn:!1,Se=b.headerIconName,_=(On=b.headerIconSize)!=null?On:"48px";if(ve){let C=he.querySelector(".tvw-border-b-cw-divider"),We=C==null?void 0:C.querySelector(".tvw-flex-col");if(U)ve.style.display="none",C&&We&&!C.contains(We)&&C.insertBefore(We,C.firstChild);else{if(ve.style.display="",ve.style.height=_,ve.style.width=_,C&&We&&(C.contains(ve)?ve.nextSibling!==We&&(ve.remove(),C.insertBefore(ve,We)):C.insertBefore(ve,We)),Se){let qe=parseFloat(_)||24,ge=Le(Se,qe*.6,"#ffffff",2);ge?ve.replaceChildren(ge):ve.textContent=(_n=b.agentIconText)!=null?_n:"\u{1F4AC}"}else if(b.iconUrl){let qe=ve.querySelector("img");if(qe)qe.src=b.iconUrl,qe.style.height=_,qe.style.width=_;else{let ge=document.createElement("img");ge.src=b.iconUrl,ge.alt="",ge.className="tvw-rounded-xl tvw-object-cover",ge.style.height=_,ge.style.width=_,ve.replaceChildren(ge)}}else{let qe=ve.querySelector("svg"),ge=ve.querySelector("img");(qe||ge)&&ve.replaceChildren(),ve.textContent=($n=b.agentIconText)!=null?$n:"\u{1F4AC}"}let Pe=ve.querySelector("img");Pe&&(Pe.style.height=_,Pe.style.width=_)}}if(E){let C=(jn=b.closeButtonSize)!=null?jn:"32px",We=(Un=b.closeButtonPlacement)!=null?Un:"inline";E.style.height=C,E.style.width=C;let Pe=We==="top-right",qe=E.classList.contains("tvw-absolute");if(Pe!==qe)if(E.remove(),Pe)E.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50 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",he.style.position="relative",he.appendChild(E);else{E.className="tvw-ml-auto 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";let oe=he.querySelector(".tvw-border-b-cw-divider");oe&&oe.appendChild(E)}if(b.closeButtonColor?(E.style.color=b.closeButtonColor,E.classList.remove("tvw-text-cw-muted")):(E.style.color="",E.classList.add("tvw-text-cw-muted")),b.closeButtonBackgroundColor?(E.style.backgroundColor=b.closeButtonBackgroundColor,E.classList.remove("hover:tvw-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:tvw-bg-gray-100")),b.closeButtonBorderWidth||b.closeButtonBorderColor){let oe=b.closeButtonBorderWidth||"0px",xt=b.closeButtonBorderColor||"transparent";E.style.border=`${oe} solid ${xt}`,E.classList.remove("tvw-border-none")}else E.style.border="",E.classList.add("tvw-border-none");b.closeButtonBorderRadius?(E.style.borderRadius=b.closeButtonBorderRadius,E.classList.remove("tvw-rounded-full")):(E.style.borderRadius="",E.classList.add("tvw-rounded-full")),b.closeButtonPaddingX?(E.style.paddingLeft=b.closeButtonPaddingX,E.style.paddingRight=b.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),b.closeButtonPaddingY?(E.style.paddingTop=b.closeButtonPaddingY,E.style.paddingBottom=b.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom="");let ge=(Vn=b.closeButtonIconName)!=null?Vn:"x",Mt=(Kn=b.closeButtonIconText)!=null?Kn:"\xD7";E.innerHTML="";let Ge=Le(ge,"20px",b.closeButtonColor||"",2);Ge?E.appendChild(Ge):E.textContent=Mt;let{closeButtonWrapper:Ke}=Ae,Te=(Xn=b.closeButtonTooltipText)!=null?Xn:"Close chat",Ze=(Yn=b.closeButtonShowTooltip)!=null?Yn:!0;if(E.setAttribute("aria-label",Te),Ke&&(Ke._cleanupTooltip&&(Ke._cleanupTooltip(),delete Ke._cleanupTooltip),Ze&&Te)){let oe=null,xt=()=>{if(oe||!E)return;oe=c("div","tvw-clear-chat-tooltip"),oe.textContent=Te;let Ao=c("div");Ao.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(Ao);let un=E.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${un.left+un.width/2}px`,oe.style.top=`${un.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},nt=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};Ke.addEventListener("mouseenter",xt),Ke.addEventListener("mouseleave",nt),E.addEventListener("focus",xt),E.addEventListener("blur",nt),Ke._cleanupTooltip=()=>{nt(),Ke&&(Ke.removeEventListener("mouseenter",xt),Ke.removeEventListener("mouseleave",nt)),E&&(E.removeEventListener("focus",xt),E.removeEventListener("blur",nt))}}}let{clearChatButton:A,clearChatButtonWrapper:w}=Ae;if(A){let C=(Jn=b.clearChat)!=null?Jn:{},We=(Gn=C.enabled)!=null?Gn:!0;if(w&&(w.style.display=We?"":"none"),We){let Pe=(Zn=C.size)!=null?Zn:"32px";A.style.height=Pe,A.style.width=Pe;let qe=(Qn=C.iconName)!=null?Qn:"refresh-cw",ge=(eo=C.iconColor)!=null?eo:"";A.innerHTML="";let Mt=Le(qe,"20px",ge||"",2);if(Mt&&A.appendChild(Mt),ge?(A.style.color=ge,A.classList.remove("tvw-text-cw-muted")):(A.style.color="",A.classList.add("tvw-text-cw-muted")),C.backgroundColor?(A.style.backgroundColor=C.backgroundColor,A.classList.remove("hover:tvw-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:tvw-bg-gray-100")),C.borderWidth||C.borderColor){let Te=C.borderWidth||"0px",Ze=C.borderColor||"transparent";A.style.border=`${Te} solid ${Ze}`,A.classList.remove("tvw-border-none")}else A.style.border="",A.classList.add("tvw-border-none");C.borderRadius?(A.style.borderRadius=C.borderRadius,A.classList.remove("tvw-rounded-full")):(A.style.borderRadius="",A.classList.add("tvw-rounded-full")),C.paddingX?(A.style.paddingLeft=C.paddingX,A.style.paddingRight=C.paddingX):(A.style.paddingLeft="",A.style.paddingRight=""),C.paddingY?(A.style.paddingTop=C.paddingY,A.style.paddingBottom=C.paddingY):(A.style.paddingTop="",A.style.paddingBottom="");let Ge=(to=C.tooltipText)!=null?to:"Clear chat",Ke=(no=C.showTooltip)!=null?no:!0;if(A.setAttribute("aria-label",Ge),w&&(w._cleanupTooltip&&(w._cleanupTooltip(),delete w._cleanupTooltip),Ke&&Ge)){let Te=null,Ze=()=>{if(Te||!A)return;Te=c("div","tvw-clear-chat-tooltip"),Te.textContent=Ge;let xt=c("div");xt.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(xt);let nt=A.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${nt.left+nt.width/2}px`,Te.style.top=`${nt.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},oe=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};w.addEventListener("mouseenter",Ze),w.addEventListener("mouseleave",oe),A.addEventListener("focus",Ze),A.addEventListener("blur",oe),w._cleanupTooltip=()=>{oe(),w&&(w.removeEventListener("mouseenter",Ze),w.removeEventListener("mouseleave",oe)),A&&(A.removeEventListener("focus",Ze),A.removeEventListener("blur",oe))}}}}let V=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Qt],K=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xt.message,Xt.messageAndClick];q=en({parsers:V,handlers:K,getMetadata:P,updateMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),g=qo(e,q),F.updateConfig(e),wt(ne,F.getMessages(),g),ut.render(e.suggestionChips,F,Z),Rt(),Tt(F.isStreaming());let Ie=((oo=e.voiceRecognition)==null?void 0:oo.enabled)===!0,fe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Je=Ie&&fe;if(bt.classList.remove("tvw-gap-1","tvw-gap-3"),bt.classList.add(Je?"tvw-gap-1":"tvw-gap-3"),Ie&&fe)if(!x||!X){let C=p(e.voiceRecognition,e.sendButton);C&&(x=C.micButton,X=C.micButtonWrapper,bt.insertBefore(X,rt),x.addEventListener("click",$),x.disabled=F.isStreaming())}else{let C=(ro=e.voiceRecognition)!=null?ro:{},We=(so=e.sendButton)!=null?so:{},Pe=(io=C.iconName)!=null?io:"mic",qe=(ao=We.size)!=null?ao:"40px",ge=(lo=C.iconSize)!=null?lo:qe,Mt=parseFloat(ge)||24;x.style.width=ge,x.style.height=ge,x.style.minWidth=ge,x.style.minHeight=ge;let Ge=(uo=(co=C.iconColor)!=null?co:We.textColor)!=null?uo:"currentColor";x.innerHTML="";let Ke=Le(Pe,Mt,Ge,2);Ke?x.appendChild(Ke):x.textContent="\u{1F3A4}";let Te=(go=C.backgroundColor)!=null?go:We.backgroundColor;Te?(x.style.backgroundColor=Te,x.classList.remove("tvw-bg-cw-primary")):(x.style.backgroundColor="",x.classList.add("tvw-bg-cw-primary")),Ge?(x.style.color=Ge,x.classList.remove("tvw-text-white")):!Ge&&!We.textColor&&(x.style.color="",x.classList.add("tvw-text-white")),C.borderWidth?(x.style.borderWidth=C.borderWidth,x.style.borderStyle="solid"):(x.style.borderWidth="",x.style.borderStyle=""),C.borderColor?x.style.borderColor=C.borderColor:x.style.borderColor="",C.paddingX?(x.style.paddingLeft=C.paddingX,x.style.paddingRight=C.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),C.paddingY?(x.style.paddingTop=C.paddingY,x.style.paddingBottom=C.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let Ze=X==null?void 0:X.querySelector(".tvw-send-button-tooltip"),oe=(po=C.tooltipText)!=null?po:"Start voice recognition";if(((mo=C.showTooltip)!=null?mo:!1)&&oe)if(Ze)Ze.textContent=oe,Ze.style.display="";else{let nt=document.createElement("div");nt.className="tvw-send-button-tooltip",nt.textContent=oe,X==null||X.insertBefore(nt,x)}else Ze&&(Ze.style.display="none");X.style.display="",x.disabled=F.isStreaming()}else x&&X&&(X.style.display="none",$e&&Xe());let te=(fo=e.sendButton)!=null?fo:{},tt=(wo=te.useIcon)!=null?wo:!1,yt=(ho=te.iconText)!=null?ho:"\u2191",ct=te.iconName,Nt=(vo=te.tooltipText)!=null?vo:"Send message",Vt=(yo=te.showTooltip)!=null?yo:!1,Ee=(xo=te.size)!=null?xo:"40px",pt=te.backgroundColor,je=te.textColor;if(tt){if(M.style.width=Ee,M.style.height=Ee,M.style.minWidth=Ee,M.style.minHeight=Ee,M.style.fontSize="18px",M.style.lineHeight="1",M.innerHTML="",ct){let C=parseFloat(Ee)||24,We=je&&typeof je=="string"&&je.trim()?je.trim():"currentColor",Pe=Le(ct,C,We,2);Pe?(M.appendChild(Pe),M.style.color=We):(M.textContent=yt,je?M.style.color=je:M.classList.add("tvw-text-white"))}else M.textContent=yt,je?M.style.color=je:M.classList.add("tvw-text-white");M.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",pt?(M.style.backgroundColor=pt,M.classList.remove("tvw-bg-cw-primary")):M.classList.add("tvw-bg-cw-primary")}else M.textContent=(Co=(bo=e.copy)==null?void 0:bo.sendButtonLabel)!=null?Co:"Send",M.style.width="",M.style.height="",M.style.minWidth="",M.style.minHeight="",M.style.fontSize="",M.style.lineHeight="",M.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",pt?(M.style.backgroundColor=pt,M.classList.remove("tvw-bg-cw-accent")):M.classList.add("tvw-bg-cw-accent"),je?M.style.color=je:M.classList.add("tvw-text-white");te.borderWidth?(M.style.borderWidth=te.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),te.borderColor?M.style.borderColor=te.borderColor:M.style.borderColor="",te.paddingX?(M.style.paddingLeft=te.paddingX,M.style.paddingRight=te.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),te.paddingY?(M.style.paddingTop=te.paddingY,M.style.paddingBottom=te.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Ft=rt==null?void 0:rt.querySelector(".tvw-send-button-tooltip");if(Vt&&Nt)if(Ft)Ft.textContent=Nt,Ft.style.display="";else{let C=document.createElement("div");C.className="tvw-send-button-tooltip",C.textContent=Nt,rt==null||rt.insertBefore(C,M)}else Ft&&(Ft.style.display="none");let At=(So=e.statusIndicator)!=null?So:{},_o=(To=At.visible)!=null?To:!0;if(zt.style.display=_o?"":"none",F){let C=F.getStatus(),We=Pe=>{var qe,ge,Mt,Ge;return Pe==="idle"?(qe=At.idleText)!=null?qe:Ue.idle:Pe==="connecting"?(ge=At.connectingText)!=null?ge:Ue.connecting:Pe==="connected"?(Mt=At.connectedText)!=null?Mt:Ue.connected:Pe==="error"?(Ge=At.errorText)!=null?Ge:Ue.error:Ue[Pe]};zt.textContent=We(C)}},open(){L&&_e(!0)},close(){L&&_e(!1)},toggle(){L&&_e(!B)},clearChat(){F.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let i=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(i),a!=null&&a.clear)try{let l=a.clear();l instanceof Promise&&l.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",l)}m={},q.syncFromMetadata()},setMessage(i){return!Z||F.isStreaming()?!1:(!B&&L&&_e(!0),Z.value=i,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(F.isStreaming())return!1;let l=(i==null?void 0:i.trim())||Z.value.trim();return l?(!B&&L&&_e(!0),Z.value="",F.sendMessage(l),!0):!1},startVoiceRecognition(){return $e||F.isStreaming()||!Pt()?!1:(!B&&L&&_e(!0),xe.manuallyDeactivated=!1,at(),vt("user"),!0)},stopVoiceRecognition(){return $e?(xe.manuallyDeactivated=!0,at(),Xe("user"),!0):!1},injectTestMessage(i){!B&&L&&_e(!0),F.injectTestEvent(i)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...m}},updatePersistentMetadata(i){u(i)},on(i,l){return s.on(i,l)},off(i,l){s.off(i,l)},destroy(){ze.forEach(i=>i()),we.remove(),O==null||O.destroy(),Qe&&E.removeEventListener("click",Qe)}};if((((He=r==null?void 0:r.debugTools)!=null?He:!1)||!!e.debug)&&typeof window!="undefined"){let i=window.AgentWidgetBrowser,l={controller:N,getMessages:N.getMessages,getStatus:N.getStatus,getMetadata:N.getPersistentMetadata,updateMetadata:N.updatePersistentMetadata,clearHistory:()=>N.clearChat(),setVoiceActive:S=>S?N.startVoiceRecognition():N.stopVoiceRecognition()};window.AgentWidgetBrowser=l,ze.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=i)})}return N};var En={},dr=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let n=document.querySelector(t);if(!n)throw new Error(`Chat widget target "${t}" was not found`);return n}return t},cr=()=>{try{if(typeof En!="undefined"&&En.url)return new URL("../widget.css",En.url).href}catch{}return null},zo=t=>{let n=cr(),r=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let o=e.cloneNode(!0);t.insertBefore(o,t.firstChild)};if(t instanceof ShadowRoot)if(n){let e=document.createElement("link");e.rel="stylesheet",e.href=n,e.setAttribute("data-vanilla-agent","true"),t.insertBefore(e,t.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},Wn=t=>{var v;let n=dr(t.target),r=document.createElement("div");r.className="vanilla-agent-host",n.appendChild(r);let e=t.useShadowDom!==!1,o,s;if(e){let P=r.attachShadow({mode:"open"});s=P,o=document.createElement("div"),o.id="vanilla-agent-root",P.appendChild(o),zo(P)}else s=r,o=document.createElement("div"),o.id="vanilla-agent-root",r.appendChild(o),zo(r);let a=cn(o,t.config,{debugTools:t.debugTools});(v=t.onReady)==null||v.call(t);let m={...a,host:r,destroy(){a.destroy(),r.remove(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}};return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=m),m};var ur=t=>{if(!t)return null;try{return JSON.parse(t)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},gr=t=>t.map(n=>({...n,streaming:!1})),Oo=(t="vanilla-agent-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?ur(r.getItem(t)):null},save:r=>{let e=n();if(e)try{let o={...r,messages:r.messages?gr(r.messages):void 0};e.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(t)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var pr=Wn;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_WIDGET_CONFIG,createActionManager,createAgentExperience,createFlexibleJsonStreamParser,createJsonStreamParser,createLocalStorageAdapter,createPlainTextParser,createRegexJsonParser,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,initAgentWidget,markdownPostprocessor,mergeWithDefaults,pluginRegistry});
16
16
  //# sourceMappingURL=index.cjs.map