vanilla-agent 1.10.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{marked as Po}from"marked";Po.setOptions({breaks:!0});var Io=e=>Po.parse(e),an=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Zo=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ho=e=>`%%FORM_PLACEHOLDER_${e}%%`,Qo=(e,n)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Ho(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=Ho(n.length);return n.push({token:s,type:o}),s}),r},er=e=>{let n=[],r=Qo(e,n),t=Io(r);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="tvw-form-directive" data-tv-form="${Zo(s)}"></div>`;t=t.replace(a,p)}),t};import{parse as Fo,STR as No,OBJ as Do}from"partial-json";var ln=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},tr=e=>{var a,l;let n=(a=e.completedAt)!=null?a:Date.now(),r=(l=e.startedAt)!=null?l:n,o=(e.durationMs!==void 0?e.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`},qo=e=>e.status==="complete"?tr(e):e.status==="pending"?"Waiting":"",nr=e=>{var o,s,a;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.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 Oo=e=>e.status==="complete"?nr(e):"Using tool...",or=()=>{let e=null,n=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.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*"((?:[^"\\]|\\.)*)/,l=t.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
3
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},tn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},cn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},dn=()=>{var n;let e=or();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},un=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=Fo(r,No|Do);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?o.text:"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=o.text))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},rr=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?s.text:"";if(s.type==="init"&&s.form)return"";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 l=Fo(s,No|Do),p=o(l);p!==null&&(n=p)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},gn=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var sr="https://api.travrse.ai/v1/dispatch";function ir(e){switch(e){case"json":return un;case"regex-json":return dn;case"xml":return gn;case"plain":default:return cn}}var Xt=class{constructor(n={}){this.config=n;var r,t,o;this.apiUrl=(r=n.apiUrl)!=null?r:sr,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:ir(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}async dispatch(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(l){let p=l instanceof Error?l:new Error(String(l));throw r({type:"error",error:p}),p}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let l=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw r({type:"error",error:l}),l}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(n){let t={messages:n.slice().sort((o,s)=>{let a=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();return a-l}).map(o=>({role:o.role,content:o.rawContent||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&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(n,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(n);if(a===null)return!1;let l=()=>{if(t.current)return t.current;let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=p,o(p),p};if(a.text!==void 0){let p=l();p.content+=a.text,o(p)}return a.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),a.error&&r({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(n,r){var G,B,ot,bt,Dt,rt,ne,R,he,qt,ve,S,De,$e,dt,st,I,ut,Ae,Ze,_,ie,gt,K,Ke,Kt,Ct,Ot,zt,St,oe,Et,Mt,it,$t,_t,Wt,mt,at,jt,Ut,Vt,ft,wt,_e,At,Lt,kt,Bt,qe,je,lt,Qe,Rt,ht,Xe;let t=n.getReader(),o=new TextDecoder,s="",a=Date.now(),l=0,p=()=>a+l++,O=f=>{let j=f.reasoning?{...f.reasoning,chunks:[...f.reasoning.chunks]}:void 0,Y=f.toolCall?{...f.toolCall,chunks:f.toolCall.chunks?[...f.toolCall.chunks]:void 0}:void 0,fe=f.tools?f.tools.map(z=>({...z,chunks:z.chunks?[...z.chunks]:void 0})):void 0;return{...f,reasoning:j,toolCall:Y,tools:fe}},u=f=>{r({type:"message",message:O(f)})},N=null,P={current:null},H=new Map,x=new Map,ee={lastId:null,byStep:new Map},k={lastId:null,byCall:new Map},b=f=>{if(f==null)return null;try{return String(f)}catch{return null}},L=f=>{var j,Y,fe,z,ye;return b((ye=(z=(fe=(Y=(j=f.stepId)!=null?j:f.step_id)!=null?Y:f.step)!=null?fe:f.parentId)!=null?z:f.flowStepId)!=null?ye:f.flow_step_id)},m=f=>{var j,Y,fe,z,ye,de,v;return b((v=(de=(ye=(z=(fe=(Y=(j=f.callId)!=null?j:f.call_id)!=null?Y:f.requestId)!=null?fe:f.request_id)!=null?z:f.toolCallId)!=null?ye:f.tool_call_id)!=null?de:f.stepId)!=null?v:f.step_id)},Le=()=>N||(N={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p()},u(N),N),pe=(f,j)=>{ee.lastId=j,f&&ee.byStep.set(f,j)},ke=(f,j)=>{var ye;let Y=(ye=f.reasoningId)!=null?ye:f.id,fe=L(f);if(Y){let de=String(Y);return pe(fe,de),de}if(fe){let de=ee.byStep.get(fe);if(de)return ee.lastId=de,de}if(ee.lastId&&!j)return ee.lastId;if(!j)return null;let z=`reason-${p()}`;return pe(fe,z),z},Re=f=>{let j=H.get(f);if(j)return j;let Y={id:`reason-${f}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:f,status:"streaming",chunks:[]}};return H.set(f,Y),u(Y),Y},Be=(f,j)=>{k.lastId=j,f&&k.byCall.set(f,j)},X=(f,j)=>{var ye;let Y=(ye=f.toolId)!=null?ye:f.id,fe=m(f);if(Y){let de=String(Y);return Be(fe,de),de}if(fe){let de=k.byCall.get(fe);if(de)return k.lastId=de,de}if(k.lastId&&!j)return k.lastId;if(!j)return null;let z=`tool-${p()}`;return Be(fe,z),z},Ne=f=>{let j=x.get(f);if(j)return j;let Y={id:`tool-${f}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:f,status:"pending"}};return x.set(f,Y),u(Y),Y},be=f=>{if(typeof f=="number"&&Number.isFinite(f))return f;if(typeof f=="string"){let j=Number(f);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let Y=Date.parse(f);if(!Number.isNaN(Y))return Y}return Date.now()},me=f=>{if(typeof f=="string")return f;if(f==null)return"";try{return JSON.stringify(f)}catch{return String(f)}},se=new Map,Ce=new Map;for(;;){let{done:f,value:j}=await t.read();if(f)break;s+=o.decode(j,{stream:!0});let Y=s.split(`
1
+ import{marked as Zs}from"marked";Zs.setOptions({breaks:!0});var Qs=n=>Zs.parse(n),mn=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Co=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Gs=n=>`%%FORM_PLACEHOLDER_${n}%%`,So=(n,e)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Gs(e.length);return e.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=Gs(e.length);return e.push({token:s,type:o}),s}),r},Ao=n=>{let e=[],r=So(n,e),t=Qs(r);return e.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="tvw-form-directive" data-tv-form="${Co(s)}"></div>`;t=t.replace(i,u)}),t};import{parse as eo,STR as to,OBJ as no}from"partial-json";var fn=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},To=n=>{var i,l;let e=(i=n.completedAt)!=null?i:Date.now(),r=(l=n.startedAt)!=null?l:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},so=n=>n.status==="complete"?To(n):n.status==="pending"?"Waiting":"",Eo=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i: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 oo=n=>n.status==="complete"?Eo(n):"Using tool...",Wo=()=>{let n=null,e=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.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 i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=t.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
3
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},ln=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},wn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},yn=()=>{var e;let n=Wo();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},vn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=eo(r,to|no);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?o.text:"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=o.text))}catch{}return e=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Mo=n=>{let e=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?s.text:"";if(s.type==="init"&&s.form)return"";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:()=>e,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return e!==null?{text:e,raw:s}:null;try{let l=eo(s,to|no),u=o(l);u!==null&&(e=u)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},bn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Lo="https://api.travrse.ai/v1/dispatch";function Bo(n){switch(n){case"json":return vn;case"regex-json":return yn;case"xml":return bn;case"plain":default:return wn}}var qt=class{constructor(e={}){this.config=e;var r,t,o;this.apiUrl=(r=e.apiUrl)!=null?r:Lo,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:Bo(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}async dispatch(e,r){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(l){let u=l instanceof Error?l:new Error(String(l));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:l}),l}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(o=>({role:o.role,content:o.rawContent||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 i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(e,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=u,o(u),u};if(i.text!==void 0){let u=l();u.content+=i.text,o(u)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,r){var se,$,qe,Je,et,wt,yt,O,de,pt,gt,Ke,rt,B,ke,it,at,St,ht,Pe,tt,Ue,N,lt,Xe,Ee,Fe,J,ye,Re,ze,nt,vt,Wt,ct,bt,ie,$t,Mt,he,mt,xt,Lt,ft,At,sn,on,rn,Pt,Ot,st,jt,Yt,Jt,Kt,Ve;let t=e.getReader(),o=new TextDecoder,s="",i=Date.now(),l=0,u=()=>i+l++,h=v=>{let G=v.reasoning?{...v.reasoning,chunks:[...v.reasoning.chunks]}:void 0,Q=v.toolCall?{...v.toolCall,chunks:v.toolCall.chunks?[...v.toolCall.chunks]:void 0}:void 0,We=v.tools?v.tools.map(Me=>({...Me,chunks:Me.chunks?[...Me.chunks]:void 0})):void 0;return{...v,reasoning:G,toolCall:Q,tools:We}},d=v=>{r({type:"message",message:h(v)})},E=null,f={current:null},C=new Map,y=new Map,j={lastId:null,byStep:new Map},F={lastId:null,byCall:new Map},m=v=>{if(v==null)return null;try{return String(v)}catch{return null}},S=v=>{var G,Q,We,Me,ve;return m((ve=(Me=(We=(Q=(G=v.stepId)!=null?G:v.step_id)!=null?Q:v.step)!=null?We:v.parentId)!=null?Me:v.flowStepId)!=null?ve:v.flow_step_id)},I=v=>{var G,Q,We,Me,ve,Le,W;return m((W=(Le=(ve=(Me=(We=(Q=(G=v.callId)!=null?G:v.call_id)!=null?Q:v.requestId)!=null?We:v.request_id)!=null?Me:v.toolCallId)!=null?ve:v.tool_call_id)!=null?Le:v.stepId)!=null?W:v.step_id)},A=()=>E||(E={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},d(E),E),z=(v,G)=>{j.lastId=G,v&&j.byStep.set(v,G)},R=(v,G)=>{var ve;let Q=(ve=v.reasoningId)!=null?ve:v.id,We=S(v);if(Q){let Le=String(Q);return z(We,Le),Le}if(We){let Le=j.byStep.get(We);if(Le)return j.lastId=Le,Le}if(j.lastId&&!G)return j.lastId;if(!G)return null;let Me=`reason-${u()}`;return z(We,Me),Me},V=v=>{let G=C.get(v);if(G)return G;let Q={id:`reason-${v}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:v,status:"streaming",chunks:[]}};return C.set(v,Q),d(Q),Q},te=(v,G)=>{F.lastId=G,v&&F.byCall.set(v,G)},T=(v,G)=>{var ve;let Q=(ve=v.toolId)!=null?ve:v.id,We=I(v);if(Q){let Le=String(Q);return te(We,Le),Le}if(We){let Le=F.byCall.get(We);if(Le)return F.lastId=Le,Le}if(F.lastId&&!G)return F.lastId;if(!G)return null;let Me=`tool-${u()}`;return te(We,Me),Me},re=v=>{let G=y.get(v);if(G)return G;let Q={id:`tool-${v}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:v,status:"pending"}};return y.set(v,Q),d(Q),Q},Y=v=>{if(typeof v=="number"&&Number.isFinite(v))return v;if(typeof v=="string"){let G=Number(v);if(!Number.isNaN(G)&&Number.isFinite(G))return G;let Q=Date.parse(v);if(!Number.isNaN(Q))return Q}return Date.now()},U=v=>{if(typeof v=="string")return v;if(v==null)return"";try{return JSON.stringify(v)}catch{return String(v)}},ne=new Map,ue=new Map;for(;;){let{done:v,value:G}=await t.read();if(v)break;s+=o.decode(G,{stream:!0});let Q=s.split(`
4
4
 
5
- `);s=(G=Y.pop())!=null?G:"";for(let fe of Y){let z=fe.split(`
6
- `),ye="message",de="";for(let q of z)q.startsWith("event:")?ye=q.replace("event:","").trim():q.startsWith("data:")&&(de+=q.replace("data:","").trim());if(!de)continue;let v;try{v=JSON.parse(de)}catch(q){r({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Ye=ye!=="message"?ye:(B=v.type)!=null?B:"message";if(this.parseSSEEvent){P.current=N;let q=await this.handleCustomSSEEvent(v,r,P,u,p);if(P.current&&!N&&(N=P.current),q)continue}if(Ye==="reason_start"){let q=(ot=ke(v,!0))!=null?ot:`reason-${p()}`,w=Re(q);w.reasoning=(bt=w.reasoning)!=null?bt:{id:q,status:"streaming",chunks:[]},w.reasoning.startedAt=(rt=w.reasoning.startedAt)!=null?rt:be((Dt=v.startedAt)!=null?Dt:v.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",u(w)}else if(Ye==="reason_chunk"){let q=(R=(ne=ke(v,!1))!=null?ne:ke(v,!0))!=null?R:`reason-${p()}`,w=Re(q);w.reasoning=(he=w.reasoning)!=null?he:{id:q,status:"streaming",chunks:[]},w.reasoning.startedAt=(ve=w.reasoning.startedAt)!=null?ve:be((qt=v.startedAt)!=null?qt:v.timestamp);let d=($e=(De=(S=v.reasoningText)!=null?S:v.text)!=null?De:v.delta)!=null?$e:"";if(d&&v.hidden!==!0&&w.reasoning.chunks.push(String(d)),w.reasoning.status=v.done?"complete":"streaming",v.done){w.reasoning.completedAt=be((dt=v.completedAt)!=null?dt:v.timestamp);let F=(st=w.reasoning.startedAt)!=null?st:Date.now();w.reasoning.durationMs=Math.max(0,((I=w.reasoning.completedAt)!=null?I:Date.now())-F)}w.streaming=w.reasoning.status!=="complete",u(w)}else if(Ye==="reason_complete"){let q=(Ae=(ut=ke(v,!1))!=null?ut:ke(v,!0))!=null?Ae:`reason-${p()}`,w=H.get(q);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=be((Ze=v.completedAt)!=null?Ze:v.timestamp);let F=(_=w.reasoning.startedAt)!=null?_:Date.now();w.reasoning.durationMs=Math.max(0,((ie=w.reasoning.completedAt)!=null?ie:Date.now())-F),w.streaming=!1,u(w)}let d=L(v);d&&ee.byStep.delete(d)}else if(Ye==="tool_start"){let q=(gt=X(v,!0))!=null?gt:`tool-${p()}`,w=Ne(q),d=(K=w.toolCall)!=null?K:{id:q,status:"pending"};d.name=(Ke=v.toolName)!=null?Ke:d.name,d.status="running",v.args!==void 0&&(d.args=v.args),d.startedAt=(Ct=d.startedAt)!=null?Ct:be((Kt=v.startedAt)!=null?Kt:v.timestamp),d.completedAt=void 0,d.durationMs=void 0,w.toolCall=d,w.streaming=!0,u(w)}else if(Ye==="tool_chunk"){let q=(zt=(Ot=X(v,!1))!=null?Ot:X(v,!0))!=null?zt:`tool-${p()}`,w=Ne(q),d=(St=w.toolCall)!=null?St:{id:q,status:"running"};d.startedAt=(Et=d.startedAt)!=null?Et:be((oe=v.startedAt)!=null?oe:v.timestamp);let F=($t=(it=(Mt=v.text)!=null?Mt:v.delta)!=null?it:v.message)!=null?$t:"";F&&(d.chunks=(_t=d.chunks)!=null?_t:[],d.chunks.push(String(F))),d.status="running",w.toolCall=d,w.streaming=!0,u(w)}else if(Ye==="tool_complete"){let q=(mt=(Wt=X(v,!1))!=null?Wt:X(v,!0))!=null?mt:`tool-${p()}`,w=Ne(q),d=(at=w.toolCall)!=null?at:{id:q,status:"running"};if(d.status="complete",v.result!==void 0&&(d.result=v.result),typeof v.duration=="number"&&(d.duration=v.duration),d.completedAt=be((jt=v.completedAt)!=null?jt:v.timestamp),typeof v.duration=="number")d.durationMs=v.duration;else{let ae=(Ut=d.startedAt)!=null?Ut:Date.now();d.durationMs=Math.max(0,((Vt=d.completedAt)!=null?Vt:Date.now())-ae)}w.toolCall=d,w.streaming=!1,u(w);let F=m(v);F&&k.byCall.delete(F)}else if(Ye==="step_chunk"){let q=v.stepType,w=v.executionType;if(q==="tool"||w==="context")continue;let d=Le(),F=(At=(_e=(wt=(ft=v.text)!=null?ft:v.delta)!=null?wt:v.content)!=null?_e:v.chunk)!=null?At:"";if(F){let le=((Lt=Ce.get(d.id))!=null?Lt:"")+F;d.rawContent=le,se.has(d.id)||se.set(d.id,this.createStreamParser());let ue=se.get(d.id),He=le.trim().startsWith("{")||le.trim().startsWith("[");if(He&&Ce.set(d.id,le),ue.__isPlainTextParser===!0){d.content+=F,Ce.delete(d.id),se.delete(d.id),d.rawContent=void 0,u(d);continue}let ce=ue.processChunk(le);if(ce instanceof Promise)ce.then(U=>{var we;let re=typeof U=="string"?U:(we=U==null?void 0:U.text)!=null?we:null;if(re!==null&&re.trim()!==""){let xe=N;xe&&xe.id===d.id&&(xe.content=re,u(xe))}else if(!He&&!le.trim().startsWith("<")){let xe=N;xe&&xe.id===d.id&&(xe.content+=F,Ce.delete(xe.id),se.delete(xe.id),xe.rawContent=void 0,u(xe))}}).catch(()=>{d.content+=F,Ce.delete(d.id),se.delete(d.id),d.rawContent=void 0,u(d)});else{let U=typeof ce=="string"?ce:(kt=ce==null?void 0:ce.text)!=null?kt:null;U!==null&&U.trim()!==""?(d.content=U,u(d)):!He&&!le.trim().startsWith("<")&&(d.content+=F,Ce.delete(d.id),se.delete(d.id),d.rawContent=void 0,u(d))}}if(v.isComplete){let ae=(qe=(Bt=v.result)==null?void 0:Bt.response)!=null?qe:d.content;if(ae){let le=Ce.get(d.id),ue=le!=null?le:me(ae);d.rawContent=ue;let He=se.get(d.id),Te=null;if(He&&(Te=He.getExtractedText(),Te===null&&(Te=tn(ue)),Te===null)){let U=He.processChunk(ue);U instanceof Promise?U.then(re=>{var xe;let we=typeof re=="string"?re:(xe=re==null?void 0:re.text)!=null?xe:null;if(we!==null){let Pe=N;Pe&&Pe.id===d.id&&(Pe.content=we,Pe.streaming=!1,u(Pe))}}):Te=typeof U=="string"?U:(je=U==null?void 0:U.text)!=null?je:null}Te!==null&&Te.trim()!==""?d.content=Te:Ce.has(d.id)||(d.content=me(ae));let ce=se.get(d.id);if(ce){let U=(lt=ce.close)==null?void 0:lt.call(ce);U instanceof Promise&&U.catch(()=>{}),se.delete(d.id)}Ce.delete(d.id),d.streaming=!1,u(d)}}}else if(Ye==="step_complete"){let q=v.stepType,w=v.executionType;if(q==="tool"||w==="context")continue;let d=(Qe=v.result)==null?void 0:Qe.response,F=Le();if(d!=null){let ae=se.get(F.id),le=!1;if(ae){let ue=ae.getExtractedText(),He=Ce.get(F.id),Te=He!=null?He:me(d);if(F.rawContent=Te,ue!==null&&ue.trim()!=="")F.content=ue,le=!0;else{let ce=tn(Te);if(ce!==null)F.content=ce,le=!0;else{let U=ae.processChunk(Te);if(U instanceof Promise)U.then(re=>{var xe;let we=typeof re=="string"?re:(xe=re==null?void 0:re.text)!=null?xe:null;if(we!==null&&we.trim()!==""){let Pe=N;Pe&&Pe.id===F.id&&(Pe.content=we,Pe.streaming=!1,u(Pe))}else{let Pe=ae.getExtractedText();if(Pe===null||Pe.trim()===""){let pt=N;pt&&pt.id===F.id&&(Ce.has(F.id)||(pt.content=me(d)),pt.streaming=!1,u(pt))}}});else{let re=typeof U=="string"?U:(Rt=U==null?void 0:U.text)!=null?Rt:null;if(re!==null&&re.trim()!=="")F.content=re,le=!0;else{let we=ae.getExtractedText();we!==null&&we.trim()!==""&&(F.content=we,le=!0)}}}}}if(!F.rawContent){let ue=Ce.get(F.id);F.rawContent=ue!=null?ue:me(d)}if(!le&&!Ce.has(F.id)&&(F.content=me(d)),ae){let ue=(ht=ae.close)==null?void 0:ht.call(ae);ue instanceof Promise&&ue.catch(()=>{})}se.delete(F.id),Ce.delete(F.id),F.streaming=!1,u(F)}else se.delete(F.id),Ce.delete(F.id),F.streaming=!1,u(F)}else if(Ye==="flow_complete"){let q=(Xe=v.result)==null?void 0:Xe.response;if(q!=null){let w=Le(),d=Ce.get(w.id),F=d!=null?d:me(q);w.rawContent=F;let ae=me(q),le=se.get(w.id);if(le){let ue=tn(F);if(ue!==null)ae=ue;else{let He=le.processChunk(F);He instanceof Promise&&He.then(ce=>{var re;let U=typeof ce=="string"?ce:(re=ce==null?void 0:ce.text)!=null?re:null;if(U!==null){let we=N;we&&we.id===w.id&&(we.content=U,we.streaming=!1,u(we))}});let Te=le.getExtractedText();Te!==null&&(ae=Te)}}se.delete(w.id),Ce.delete(w.id),ae!==w.content&&(w.content=ae,u(w)),w.streaming=!1,u(w)}else if(N!==null){let w=N;se.delete(w.id),Ce.delete(w.id),w.streaming=!1,u(w)}r({type:"status",status:"idle"})}else Ye==="error"&&v.error&&r({type:"error",error:v.error instanceof Error?v.error:new Error(String(v.error))})}}}};var Qt=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,t;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(r=this.callbacks).onError)==null||t.call(r,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Xt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(n){this.config={...this.config,...n},this.client=new Xt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}async sendMessage(n,r){var l,p,O,u,N;let t=n.trim();if(!t)return;(l=this.abortController)==null||l.abort();let o={id:`user-${Date.now()}`,role:"user",content:t,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(P){let H={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(H),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,P instanceof Error?(O=(p=this.callbacks).onError)==null||O.call(p,P):(N=(u=this.callbacks).onError)==null||N.call(u,new Error(String(P)))}}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(t=>{var o;return{...t,streaming:!1,sequence:(o=t.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),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...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,t)=>{var p,O;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(p=r.sequence)!=null?p:0,l=(O=t.sequence)!=null?O:0;return a!==l?a-l:r.id.localeCompare(t.id)})}};var pn=(e,n)=>{var t;let r=(t=n==null?void 0:n.theme)!=null?t:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let a=o.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);e.style.setProperty(`--cw-${a}`,String(s))})};import*as ar from"lucide";var We=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),s=ar[o];return s?lr(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function lr(e,n,r,t){if(!e||!Array.isArray(e))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(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let a=s[0],l=s[1];if(l){let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([O,u])=>{O!=="stroke"&&p.setAttribute(O,String(u))}),o.appendChild(p)}}}),o}var g=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};var Ue={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Nt={"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 mn=(e,n)=>{let r=g("button");r.type="button",r.innerHTML=`
5
+ `);s=(se=Q.pop())!=null?se:"";for(let We of Q){let Me=We.split(`
6
+ `),ve="message",Le="";for(let X of Me)X.startsWith("event:")?ve=X.replace("event:","").trim():X.startsWith("data:")&&(Le+=X.replace("data:","").trim());if(!Le)continue;let W;try{W=JSON.parse(Le)}catch(X){r({type:"error",error:X instanceof Error?X:new Error("Failed to parse chat stream payload")});continue}let ut=ve!=="message"?ve:($=W.type)!=null?$:"message";if(this.parseSSEEvent){f.current=E;let X=await this.handleCustomSSEEvent(W,r,f,d,u);if(f.current&&!E&&(E=f.current),X)continue}if(ut==="reason_start"){let X=(qe=R(W,!0))!=null?qe:`reason-${u()}`,w=V(X);w.reasoning=(Je=w.reasoning)!=null?Je:{id:X,status:"streaming",chunks:[]},w.reasoning.startedAt=(wt=w.reasoning.startedAt)!=null?wt:Y((et=W.startedAt)!=null?et:W.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",d(w)}else if(ut==="reason_chunk"){let X=(O=(yt=R(W,!1))!=null?yt:R(W,!0))!=null?O:`reason-${u()}`,w=V(X);w.reasoning=(de=w.reasoning)!=null?de:{id:X,status:"streaming",chunks:[]},w.reasoning.startedAt=(gt=w.reasoning.startedAt)!=null?gt:Y((pt=W.startedAt)!=null?pt:W.timestamp);let g=(B=(rt=(Ke=W.reasoningText)!=null?Ke:W.text)!=null?rt:W.delta)!=null?B:"";if(g&&W.hidden!==!0&&w.reasoning.chunks.push(String(g)),w.reasoning.status=W.done?"complete":"streaming",W.done){w.reasoning.completedAt=Y((ke=W.completedAt)!=null?ke:W.timestamp);let D=(it=w.reasoning.startedAt)!=null?it:Date.now();w.reasoning.durationMs=Math.max(0,((at=w.reasoning.completedAt)!=null?at:Date.now())-D)}w.streaming=w.reasoning.status!=="complete",d(w)}else if(ut==="reason_complete"){let X=(ht=(St=R(W,!1))!=null?St:R(W,!0))!=null?ht:`reason-${u()}`,w=C.get(X);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=Y((Pe=W.completedAt)!=null?Pe:W.timestamp);let D=(tt=w.reasoning.startedAt)!=null?tt:Date.now();w.reasoning.durationMs=Math.max(0,((Ue=w.reasoning.completedAt)!=null?Ue:Date.now())-D),w.streaming=!1,d(w)}let g=S(W);g&&j.byStep.delete(g)}else if(ut==="tool_start"){let X=(N=T(W,!0))!=null?N:`tool-${u()}`,w=re(X),g=(lt=w.toolCall)!=null?lt:{id:X,status:"pending"};g.name=(Xe=W.toolName)!=null?Xe:g.name,g.status="running",W.args!==void 0&&(g.args=W.args),g.startedAt=(Fe=g.startedAt)!=null?Fe:Y((Ee=W.startedAt)!=null?Ee:W.timestamp),g.completedAt=void 0,g.durationMs=void 0,w.toolCall=g,w.streaming=!0,d(w)}else if(ut==="tool_chunk"){let X=(ye=(J=T(W,!1))!=null?J:T(W,!0))!=null?ye:`tool-${u()}`,w=re(X),g=(Re=w.toolCall)!=null?Re:{id:X,status:"running"};g.startedAt=(nt=g.startedAt)!=null?nt:Y((ze=W.startedAt)!=null?ze:W.timestamp);let D=(ct=(Wt=(vt=W.text)!=null?vt:W.delta)!=null?Wt:W.message)!=null?ct:"";D&&(g.chunks=(bt=g.chunks)!=null?bt:[],g.chunks.push(String(D))),g.status="running",w.toolCall=g,w.streaming=!0,d(w)}else if(ut==="tool_complete"){let X=($t=(ie=T(W,!1))!=null?ie:T(W,!0))!=null?$t:`tool-${u()}`,w=re(X),g=(Mt=w.toolCall)!=null?Mt:{id:X,status:"running"};if(g.status="complete",W.result!==void 0&&(g.result=W.result),typeof W.duration=="number"&&(g.duration=W.duration),g.completedAt=Y((he=W.completedAt)!=null?he:W.timestamp),typeof W.duration=="number")g.durationMs=W.duration;else{let be=(mt=g.startedAt)!=null?mt:Date.now();g.durationMs=Math.max(0,((xt=g.completedAt)!=null?xt:Date.now())-be)}w.toolCall=g,w.streaming=!1,d(w);let D=I(W);D&&F.byCall.delete(D)}else if(ut==="step_chunk"){let X=W.stepType,w=W.executionType;if(X==="tool"||w==="context")continue;let g=A(),D=(sn=(At=(ft=(Lt=W.text)!=null?Lt:W.delta)!=null?ft:W.content)!=null?At:W.chunk)!=null?sn:"";if(D){let xe=((on=ue.get(g.id))!=null?on:"")+D;g.rawContent=xe,ne.has(g.id)||ne.set(g.id,this.createStreamParser());let Ie=ne.get(g.id),Ce=xe.trim().startsWith("{")||xe.trim().startsWith("[");if(Ce&&ue.set(g.id,xe),Ie.__isPlainTextParser===!0){g.content+=D,ue.delete(g.id),ne.delete(g.id),g.rawContent=void 0,d(g);continue}let Se=Ie.processChunk(xe);if(Se instanceof Promise)Se.then(oe=>{var Be;let we=typeof oe=="string"?oe:(Be=oe==null?void 0:oe.text)!=null?Be:null;if(we!==null&&we.trim()!==""){let $e=E;$e&&$e.id===g.id&&($e.content=we,d($e))}else if(!Ce&&!xe.trim().startsWith("<")){let $e=E;$e&&$e.id===g.id&&($e.content+=D,ue.delete($e.id),ne.delete($e.id),$e.rawContent=void 0,d($e))}}).catch(()=>{g.content+=D,ue.delete(g.id),ne.delete(g.id),g.rawContent=void 0,d(g)});else{let oe=typeof Se=="string"?Se:(rn=Se==null?void 0:Se.text)!=null?rn:null;oe!==null&&oe.trim()!==""?(g.content=oe,d(g)):!Ce&&!xe.trim().startsWith("<")&&(g.content+=D,ue.delete(g.id),ne.delete(g.id),g.rawContent=void 0,d(g))}}if(W.isComplete){let be=(Ot=(Pt=W.result)==null?void 0:Pt.response)!=null?Ot:g.content;if(be){let xe=ue.get(g.id),Ie=xe!=null?xe:U(be);g.rawContent=Ie;let Ce=ne.get(g.id),De=null;if(Ce&&(De=Ce.getExtractedText(),De===null&&(De=ln(Ie)),De===null)){let oe=Ce.processChunk(Ie);oe instanceof Promise?oe.then(we=>{var $e;let Be=typeof we=="string"?we:($e=we==null?void 0:we.text)!=null?$e:null;if(Be!==null){let je=E;je&&je.id===g.id&&(je.content=Be,je.streaming=!1,d(je))}}):De=typeof oe=="string"?oe:(st=oe==null?void 0:oe.text)!=null?st:null}De!==null&&De.trim()!==""?g.content=De:ue.has(g.id)||(g.content=U(be));let Se=ne.get(g.id);if(Se){let oe=(jt=Se.close)==null?void 0:jt.call(Se);oe instanceof Promise&&oe.catch(()=>{}),ne.delete(g.id)}ue.delete(g.id),g.streaming=!1,d(g)}}}else if(ut==="step_complete"){let X=W.stepType,w=W.executionType;if(X==="tool"||w==="context")continue;let g=(Yt=W.result)==null?void 0:Yt.response,D=A();if(g!=null){let be=ne.get(D.id),xe=!1;if(be){let Ie=be.getExtractedText(),Ce=ue.get(D.id),De=Ce!=null?Ce:U(g);if(D.rawContent=De,Ie!==null&&Ie.trim()!=="")D.content=Ie,xe=!0;else{let Se=ln(De);if(Se!==null)D.content=Se,xe=!0;else{let oe=be.processChunk(De);if(oe instanceof Promise)oe.then(we=>{var $e;let Be=typeof we=="string"?we:($e=we==null?void 0:we.text)!=null?$e:null;if(Be!==null&&Be.trim()!==""){let je=E;je&&je.id===D.id&&(je.content=Be,je.streaming=!1,d(je))}else{let je=be.getExtractedText();if(je===null||je.trim()===""){let Bt=E;Bt&&Bt.id===D.id&&(ue.has(D.id)||(Bt.content=U(g)),Bt.streaming=!1,d(Bt))}}});else{let we=typeof oe=="string"?oe:(Jt=oe==null?void 0:oe.text)!=null?Jt:null;if(we!==null&&we.trim()!=="")D.content=we,xe=!0;else{let Be=be.getExtractedText();Be!==null&&Be.trim()!==""&&(D.content=Be,xe=!0)}}}}}if(!D.rawContent){let Ie=ue.get(D.id);D.rawContent=Ie!=null?Ie:U(g)}if(!xe&&!ue.has(D.id)&&(D.content=U(g)),be){let Ie=(Kt=be.close)==null?void 0:Kt.call(be);Ie instanceof Promise&&Ie.catch(()=>{})}ne.delete(D.id),ue.delete(D.id),D.streaming=!1,d(D)}else ne.delete(D.id),ue.delete(D.id),D.streaming=!1,d(D)}else if(ut==="flow_complete"){let X=(Ve=W.result)==null?void 0:Ve.response;if(X!=null){let w=A(),g=ue.get(w.id),D=g!=null?g:U(X);w.rawContent=D;let be=U(X),xe=ne.get(w.id);if(xe){let Ie=ln(D);if(Ie!==null)be=Ie;else{let Ce=xe.processChunk(D);Ce instanceof Promise&&Ce.then(Se=>{var we;let oe=typeof Se=="string"?Se:(we=Se==null?void 0:Se.text)!=null?we:null;if(oe!==null){let Be=E;Be&&Be.id===w.id&&(Be.content=oe,Be.streaming=!1,d(Be))}});let De=xe.getExtractedText();De!==null&&(be=De)}}ne.delete(w.id),ue.delete(w.id),be!==w.content&&(w.content=be,d(w)),w.streaming=!1,d(w)}else if(E!==null){let w=E;ne.delete(w.id),ue.delete(w.id),w.streaming=!1,d(w)}r({type:"status",status:"idle"})}else ut==="error"&&W.error&&r({type:"error",error:W.error instanceof Error?W.error:new Error(String(W.error))})}}}};var Gt=class{constructor(e={},r){this.config=e;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=e=>{var r,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(r=this.callbacks).onError)==null||t.call(r,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new qt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(e){this.config={...this.config,...e},this.client=new qt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,r){var l,u,h,d,E;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let o={id:`user-${Date.now()}`,role:"user",content:t,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 i=[...this.messages];try{await this.client.dispatch({messages:i,signal:s.signal},this.handleEvent)}catch(f){let C={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(C),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f instanceof Error?(h=(u=this.callbacks).onError)==null||h.call(u,f):(E=(d=this.callbacks).onError)==null||E.call(d,new Error(String(f)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let r=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let r=this.ensureSequence(e),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((r,t)=>{var u,h;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(u=r.sequence)!=null?u:0,l=(h=t.sequence)!=null?h:0;return i!==l?i-l:r.id.localeCompare(t.id)})}};var xn=(n,e)=>{var t;let r=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(r).forEach(([o,s])=>{if(s==null||s==="")return;let i=o.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(s))})};import*as Ho from"lucide";var ge=(n,e=24,r="currentColor",t=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ho[o];return s?ko(s,e,r,t):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function ko(n,e,r,t){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([h,d])=>{h!=="stroke"&&u.setAttribute(h,String(d))}),o.appendChild(u)}}}),o}var c=(n,e)=>{let r=document.createElement(n);return e&&(r.className=e),r};var Ye={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var It={"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 Zt=(n,e)=>{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,51 @@ import{marked as Po}from"marked";Po.setOptions({breaks:!0});var Io=e=>Po.parse(e
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 t=s=>{var ee,k,b,L,m,Le,pe,ke,Re,Be;let a=(ee=s.launcher)!=null?ee:{},l=r.querySelector("[data-role='launcher-title']");l&&(l.textContent=(k=a.title)!=null?k:"Chat Assistant");let p=r.querySelector("[data-role='launcher-subtitle']");p&&(p.textContent=(b=a.subtitle)!=null?b:"Get answers fast");let O=r.querySelector(".tvw-flex-col");O&&(a.textHidden?O.style.display="none":O.style.display="");let u=r.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let X=(L=a.agentIconSize)!=null?L:"40px";if(u.style.height=X,u.style.width=X,u.innerHTML="",a.agentIconName){let Ne=parseFloat(X)||24,be=We(a.agentIconName,Ne*.6,"#ffffff",2);be?(u.appendChild(be),u.style.display=""):(u.textContent=(m=a.agentIconText)!=null?m:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(Le=a.agentIconText)!=null?Le:"\u{1F4AC}",u.style.display="")}let N=r.querySelector("[data-role='launcher-image']");if(N){let X=(pe=a.agentIconSize)!=null?pe:"40px";N.style.height=X,N.style.width=X,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(N.src=a.iconUrl,N.style.display="block"):N.style.display="none"}let P=r.querySelector("[data-role='launcher-call-to-action-icon']");if(P){let X=(ke=a.callToActionIconSize)!=null?ke:"32px";P.style.height=X,P.style.width=X,a.callToActionIconBackgroundColor?(P.style.backgroundColor=a.callToActionIconBackgroundColor,P.classList.remove("tvw-bg-cw-primary")):(P.style.backgroundColor="",P.classList.add("tvw-bg-cw-primary"));let Ne=0;if(a.callToActionIconPadding?(P.style.boxSizing="border-box",P.style.padding=a.callToActionIconPadding,Ne=(parseFloat(a.callToActionIconPadding)||0)*2):(P.style.boxSizing="",P.style.padding=""),a.callToActionIconHidden)P.style.display="none";else if(P.style.display="",P.innerHTML="",a.callToActionIconName){let be=parseFloat(X)||24,me=Math.max(be-Ne,8),se=We(a.callToActionIconName,me,"currentColor",2);se?P.appendChild(se):P.textContent=(Re=a.callToActionIconText)!=null?Re:"\u2197"}else P.textContent=(Be=a.callToActionIconText)!=null?Be:"\u2197"}let H=a.position&&Nt[a.position]?Nt[a.position]:Nt["bottom-right"],x="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=`${x} ${H}`},o=()=>{r.removeEventListener("click",n),r.remove()};return e&&t(e),{element:r,update:t,destroy:o}};var zo=e=>{var p,O,u,N,P;if(!((O=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?O:!0)){let H=g("div","tvw-relative tvw-w-full tvw-h-full"),x=g("div","tvw-relative tvw-w-full tvw-h-full tvw-min-h-[360px]");return H.appendChild(x),{wrapper:H,panel:x}}let r=(u=e==null?void 0:e.launcher)!=null?u:{},t=r.position&&Nt[r.position]?Nt[r.position]:Nt["bottom-right"],o=g("div",`tvw-fixed ${t} tvw-z-50 tvw-transition`),s=g("div","tvw-relative tvw-min-h-[320px]"),a=(P=(N=e==null?void 0:e.launcher)==null?void 0:N.width)!=null?P:e==null?void 0:e.launcherWidth,l=a!=null?a:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,o.appendChild(s),{wrapper:o,panel:s}},$o=(e,n=!0)=>{var St,oe,Et,Mt,it,$t,_t,Wt,mt,at,jt,Ut,Vt,ft,wt,_e,At,Lt,kt,Bt,qe,je,lt,Qe,Rt,ht,Xe,f,j,Y,fe,z,ye,de,v,Ye,q,w,d,F,ae,le,ue,He,Te,ce,U,re,we,xe,Pe,pt,i,c,A,D,M,y,C,V;let r=g("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"),t=g("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=(St=e==null?void 0:e.launcher)!=null?St:{},s=(oe=o.headerIconSize)!=null?oe:"48px",a=(Et=o.closeButtonSize)!=null?Et:"32px",l=(Mt=o.closeButtonPlacement)!=null?Mt:"inline",p=(it=o.headerIconHidden)!=null?it:!1,O=o.headerIconName,u=g("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,!p)if(O){let E=parseFloat(s)||24,W=We(O,E*.6,"#ffffff",2);W?u.replaceChildren(W):u.textContent=(_t=($t=e==null?void 0:e.launcher)==null?void 0:$t.agentIconText)!=null?_t:"\u{1F4AC}"}else if((Wt=e==null?void 0:e.launcher)!=null&&Wt.iconUrl){let E=g("img");E.src=e.launcher.iconUrl,E.alt="",E.className="tvw-rounded-xl tvw-object-cover",E.style.height=s,E.style.width=s,u.replaceChildren(E)}else u.textContent=(at=(mt=e==null?void 0:e.launcher)==null?void 0:mt.agentIconText)!=null?at:"\u{1F4AC}";let N=g("div","tvw-flex tvw-flex-col"),P=g("span","tvw-text-base tvw-font-semibold");P.textContent=(Ut=(jt=e==null?void 0:e.launcher)==null?void 0:jt.title)!=null?Ut:"Chat Assistant";let H=g("span","tvw-text-xs tvw-text-cw-muted");H.textContent=(ft=(Vt=e==null?void 0:e.launcher)==null?void 0:Vt.subtitle)!=null?ft:"Here to help you get answers fast",N.append(P,H),p?t.append(N):t.append(u,N);let x=(wt=o.clearChat)!=null?wt:{},ee=(_e=x.enabled)!=null?_e:!0,k=null,b=null;if(ee){let E=(At=x.size)!=null?At:"32px",W=(Lt=x.iconName)!=null?Lt:"refresh-cw",h=(kt=x.iconColor)!=null?kt:"",$=(Bt=x.backgroundColor)!=null?Bt:"",J=(qe=x.borderWidth)!=null?qe:"",Z=(je=x.borderColor)!=null?je:"",Oe=(lt=x.borderRadius)!=null?lt:"",Ie=(Qe=x.paddingX)!=null?Qe:"",ct=(Rt=x.paddingY)!=null?Rt:"",Q=(ht=x.tooltipText)!=null?ht:"Clear chat",Ht=(Xe=x.showTooltip)!=null?Xe:!0;b=g("div","tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),k=g("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"),k.style.height=E,k.style.width=E,k.type="button",k.setAttribute("aria-label",Q);let Pt=We(W,"20px",h||"",2);if(Pt&&k.appendChild(Pt),h&&(k.style.color=h,k.classList.remove("tvw-text-cw-muted")),$&&(k.style.backgroundColor=$,k.classList.remove("hover:tvw-bg-gray-100")),J||Z){let Ee=J||"0px",et=Z||"transparent";k.style.border=`${Ee} solid ${et}`,k.classList.remove("tvw-border-none")}if(Oe&&(k.style.borderRadius=Oe,k.classList.remove("tvw-rounded-full")),Ie?(k.style.paddingLeft=Ie,k.style.paddingRight=Ie):(k.style.paddingLeft="",k.style.paddingRight=""),ct?(k.style.paddingTop=ct,k.style.paddingBottom=ct):(k.style.paddingTop="",k.style.paddingBottom=""),b.appendChild(k),Ht&&Q&&k&&b){let Ee=null,et=()=>{if(Ee||!k)return;Ee=g("div","tvw-clear-chat-tooltip"),Ee.textContent=Q;let It=g("div");It.className="tvw-clear-chat-tooltip-arrow",Ee.appendChild(It);let Ft=k.getBoundingClientRect();Ee.style.position="fixed",Ee.style.left=`${Ft.left+Ft.width/2}px`,Ee.style.top=`${Ft.top-8}px`,Ee.style.transform="translate(-50%, -100%)",document.body.appendChild(Ee)},vt=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};b.addEventListener("mouseenter",et),b.addEventListener("mouseleave",vt),k.addEventListener("focus",et),k.addEventListener("blur",vt),b._cleanupTooltip=()=>{vt(),b&&(b.removeEventListener("mouseenter",et),b.removeEventListener("mouseleave",vt)),k&&(k.removeEventListener("focus",et),k.removeEventListener("blur",vt))}}t.appendChild(b)}let L=g("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":ee?"":"tvw-ml-auto"),m=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");m.style.height=a,m.style.width=a,m.type="button";let Le=(f=o.closeButtonTooltipText)!=null?f:"Close chat",pe=(j=o.closeButtonShowTooltip)!=null?j:!0;m.setAttribute("aria-label",Le),m.style.display=n?"":"none";let ke=(Y=o.closeButtonIconName)!=null?Y:"x",Re=(fe=o.closeButtonIconText)!=null?fe:"\xD7",Be=We(ke,"20px",o.closeButtonColor||"",2);if(Be?m.appendChild(Be):m.textContent=Re,o.closeButtonColor?(m.style.color=o.closeButtonColor,m.classList.remove("tvw-text-cw-muted")):(m.style.color="",m.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(m.style.backgroundColor=o.closeButtonBackgroundColor,m.classList.remove("hover:tvw-bg-gray-100")):(m.style.backgroundColor="",m.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let E=o.closeButtonBorderWidth||"0px",W=o.closeButtonBorderColor||"transparent";m.style.border=`${E} solid ${W}`,m.classList.remove("tvw-border-none")}else m.style.border="",m.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(m.style.borderRadius=o.closeButtonBorderRadius,m.classList.remove("tvw-rounded-full")):(m.style.borderRadius="",m.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(m.style.paddingLeft=o.closeButtonPaddingX,m.style.paddingRight=o.closeButtonPaddingX):(m.style.paddingLeft="",m.style.paddingRight=""),o.closeButtonPaddingY?(m.style.paddingTop=o.closeButtonPaddingY,m.style.paddingBottom=o.closeButtonPaddingY):(m.style.paddingTop="",m.style.paddingBottom=""),L.appendChild(m),pe&&Le){let E=null,W=()=>{if(E)return;E=g("div","tvw-clear-chat-tooltip"),E.textContent=Le;let $=g("div");$.className="tvw-clear-chat-tooltip-arrow",E.appendChild($);let J=m.getBoundingClientRect();E.style.position="fixed",E.style.left=`${J.left+J.width/2}px`,E.style.top=`${J.top-8}px`,E.style.transform="translate(-50%, -100%)",document.body.appendChild(E)},h=()=>{E&&E.parentNode&&(E.parentNode.removeChild(E),E=null)};L.addEventListener("mouseenter",W),L.addEventListener("mouseleave",h),m.addEventListener("focus",W),m.addEventListener("blur",h),L._cleanupTooltip=()=>{h(),L.removeEventListener("mouseenter",W),L.removeEventListener("mouseleave",h),m.removeEventListener("focus",W),m.removeEventListener("blur",h)}}l==="top-right"?(r.style.position="relative",r.appendChild(L)):t.appendChild(L);let X=g("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");X.id="vanilla-agent-scroll-container";let Ne=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),be=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");be.textContent=(ye=(z=e==null?void 0:e.copy)==null?void 0:z.welcomeTitle)!=null?ye:"Hello \u{1F44B}";let me=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");me.textContent=(v=(de=e==null?void 0:e.copy)==null?void 0:de.welcomeSubtitle)!=null?v:"Ask anything about your account or products.",Ne.append(be,me);let se=g("div","tvw-flex tvw-flex-col tvw-gap-3");X.append(Ne,se);let Ce=g("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),G=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),B=((Ye=e==null?void 0:e.voiceRecognition)==null?void 0:Ye.enabled)===!0,ot=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),rt=g("form",`tvw-flex tvw-items-end ${B&&ot?"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`);rt.style.outline="none";let ne=g("textarea");ne.placeholder=(w=(q=e==null?void 0:e.copy)==null?void 0:q.inputPlaceholder)!=null?w:"Type your message\u2026",ne.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",ne.rows=1;let R=(F=(d=e==null?void 0:e.theme)==null?void 0:d.inputFontFamily)!=null?F:"sans-serif",he=(le=(ae=e==null?void 0:e.theme)==null?void 0:ae.inputFontWeight)!=null?le:"400",qt=E=>{switch(E){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};ne.style.fontFamily=qt(R),ne.style.fontWeight=he,ne.style.border="none",ne.style.outline="none",ne.style.borderWidth="0",ne.style.borderStyle="none",ne.style.borderColor="transparent",ne.addEventListener("focus",()=>{ne.style.border="none",ne.style.outline="none",ne.style.borderWidth="0",ne.style.borderStyle="none",ne.style.borderColor="transparent",ne.style.boxShadow="none"}),ne.addEventListener("blur",()=>{ne.style.border="none",ne.style.outline="none"});let ve=(ue=e==null?void 0:e.sendButton)!=null?ue:{},S=(He=ve.useIcon)!=null?He:!1,De=(Te=ve.iconText)!=null?Te:"\u2191",$e=ve.iconName,dt=(ce=ve.tooltipText)!=null?ce:"Send message",st=(U=ve.showTooltip)!=null?U:!1,I=(re=ve.size)!=null?re:"40px",ut=ve.backgroundColor,Ae=ve.textColor,Ze=g("div","tvw-send-button-wrapper"),_=g("button",S?"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(_.type="submit",S){if(_.style.width=I,_.style.height=I,_.style.minWidth=I,_.style.minHeight=I,_.style.fontSize="18px",_.style.lineHeight="1",_.innerHTML="",$e){let E=parseFloat(I)||24,W=Ae&&typeof Ae=="string"&&Ae.trim()?Ae.trim():"currentColor",h=We($e,E,W,2);h?(_.appendChild(h),_.style.color=W):(_.textContent=De,Ae?_.style.color=Ae:_.classList.add("tvw-text-white"))}else _.textContent=De,Ae?_.style.color=Ae:_.classList.add("tvw-text-white");ut?_.style.backgroundColor=ut:_.classList.add("tvw-bg-cw-primary")}else _.textContent=(xe=(we=e==null?void 0:e.copy)==null?void 0:we.sendButtonLabel)!=null?xe:"Send",Ae?_.style.color=Ae:_.classList.add("tvw-text-white");if(ve.borderWidth&&(_.style.borderWidth=ve.borderWidth,_.style.borderStyle="solid"),ve.borderColor&&(_.style.borderColor=ve.borderColor),ve.paddingX?(_.style.paddingLeft=ve.paddingX,_.style.paddingRight=ve.paddingX):(_.style.paddingLeft="",_.style.paddingRight=""),ve.paddingY?(_.style.paddingTop=ve.paddingY,_.style.paddingBottom=ve.paddingY):(_.style.paddingTop="",_.style.paddingBottom=""),st&&dt){let E=g("div","tvw-send-button-tooltip");E.textContent=dt,Ze.appendChild(E)}Ze.appendChild(_);let ie=(Pe=e==null?void 0:e.voiceRecognition)!=null?Pe:{},gt=ie.enabled===!0,K=null,Ke=null,Kt=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(gt&&Kt){Ke=g("div","tvw-send-button-wrapper"),K=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),K.type="button",K.setAttribute("aria-label","Start voice recognition");let E=(pt=ie.iconName)!=null?pt:"mic",W=(i=ie.iconSize)!=null?i:I,h=parseFloat(W)||24,$=(c=ie.backgroundColor)!=null?c:ut,J=(A=ie.iconColor)!=null?A:Ae;K.style.width=W,K.style.height=W,K.style.minWidth=W,K.style.minHeight=W,K.style.fontSize="18px",K.style.lineHeight="1";let Z=J||"currentColor",Oe=We(E,h,Z,1.5);Oe?(K.appendChild(Oe),K.style.color=Z):(K.textContent="\u{1F3A4}",K.style.color=Z),$?K.style.backgroundColor=$:K.classList.add("tvw-bg-cw-primary"),J?K.style.color=J:!J&&!Ae&&K.classList.add("tvw-text-white"),ie.borderWidth&&(K.style.borderWidth=ie.borderWidth,K.style.borderStyle="solid"),ie.borderColor&&(K.style.borderColor=ie.borderColor),ie.paddingX&&(K.style.paddingLeft=ie.paddingX,K.style.paddingRight=ie.paddingX),ie.paddingY&&(K.style.paddingTop=ie.paddingY,K.style.paddingBottom=ie.paddingY),Ke.appendChild(K);let Ie=(D=ie.tooltipText)!=null?D:"Start voice recognition";if(((M=ie.showTooltip)!=null?M:!1)&&Ie){let Q=g("div","tvw-send-button-tooltip");Q.textContent=Ie,Ke.appendChild(Q)}}rt.addEventListener("click",E=>{E.target!==_&&E.target!==Ze&&E.target!==K&&E.target!==Ke&&ne.focus()}),rt.append(ne),Ke&&rt.append(Ke),rt.append(Ze);let Ct=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Ot=(y=e==null?void 0:e.statusIndicator)!=null?y:{},zt=(C=Ot.visible)!=null?C:!0;return Ct.style.display=zt?"":"none",Ct.textContent=(V=Ot.idleText)!=null?V:"Online",Ce.append(G,rt,Ct),r.append(t,X,Ce),{container:r,body:X,messagesWrapper:se,suggestions:G,textarea:ne,sendButton:_,sendButtonWrapper:Ze,micButton:K,micButtonWrapper:Ke,composerForm:rt,statusText:Ct,introTitle:be,introSubtitle:me,closeButton:m,closeButtonWrapper:L,clearChatButton:k,clearChatButtonWrapper:b,iconHolder:u,headerTitle:P,headerSubtitle:H}};var fn=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let 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 t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(r),e.appendChild(t),e.appendChild(o),e},wn=(e,n)=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"];e.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 t=g("div",r.join(" ")),o=document.createElement("div");if(o.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),t.appendChild(o),e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let s=fn();t.appendChild(s)}return t};var hn=new Set,vn=e=>{let n=e.reasoning,r=g("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 t=hn.has(e.id),o=g("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",t?"true":"false");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent="Thinking...",s.appendChild(a);let l=g("span","tvw-text-xs tvw-text-cw-primary");l.textContent=qo(n),s.appendChild(l),n.status==="complete"?a.style.display="none":a.style.display="";let p=g("div","tvw-flex tvw-items-center"),u=We(t?"chevron-up":"chevron-down",16,"currentColor",2);u?p.appendChild(u):p.textContent=t?"Hide":"Show";let N=g("div","tvw-flex tvw-items-center tvw-ml-auto");N.append(p),o.append(s,N);let P=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");P.style.display=t?"":"none";let H=n.chunks.join(""),x=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");x.textContent=H||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),P.appendChild(x);let ee=()=>{o.setAttribute("aria-expanded",t?"true":"false"),p.innerHTML="";let L=We(t?"chevron-up":"chevron-down",16,"currentColor",2);L?p.appendChild(L):p.textContent=t?"Hide":"Show",P.style.display=t?"":"none"},k=()=>{t=!t,t?hn.add(e.id):hn.delete(e.id),ee()};return o.addEventListener("pointerdown",b=>{b.preventDefault(),k()}),o.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),k())}),ee(),r.append(o,P),r};var yn=new Set,xn=(e,n)=>{var k;let r=e.toolCall,t=(k=n==null?void 0:n.toolCall)!=null?k:{},o=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=yn.has(e.id),a=g("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"),t.headerBackgroundColor&&(a.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(a.style.paddingLeft=t.headerPaddingX,a.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(a.style.paddingTop=t.headerPaddingY,a.style.paddingBottom=t.headerPaddingY);let l=g("div","tvw-flex tvw-flex-col tvw-text-left"),p=g("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(p.style.color=t.headerTextColor),p.textContent=Oo(r),l.appendChild(p);let O=g("div","tvw-flex tvw-items-center"),u=t.toggleTextColor||t.headerTextColor||"currentColor",N=We(s?"chevron-up":"chevron-down",16,u,2);N?O.appendChild(N):O.textContent=s?"Hide":"Show";let P=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");P.append(O),a.append(l,P);let H=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(H.style.display=s?"":"none",t.contentBackgroundColor&&(H.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(H.style.color=t.contentTextColor),t.contentPaddingX&&(H.style.paddingLeft=t.contentPaddingX,H.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(H.style.paddingTop=t.contentPaddingY,H.style.paddingBottom=t.contentPaddingY),r.name){let b=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?b.style.color=t.contentTextColor:t.headerTextColor&&(b.style.color=t.headerTextColor),b.textContent=r.name,H.appendChild(b)}if(r.args!==void 0){let b=g("div","tvw-space-y-1"),L=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(L.style.color=t.labelTextColor),L.textContent="Arguments";let m=g("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");m.style.fontSize="0.75rem",m.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(m.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(m.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(m.style.color=t.codeBlockTextColor),m.textContent=ln(r.args),b.append(L,m),H.appendChild(b)}if(r.chunks&&r.chunks.length){let b=g("div","tvw-space-y-1"),L=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(L.style.color=t.labelTextColor),L.textContent="Activity";let m=g("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");m.style.fontSize="0.75rem",m.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(m.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(m.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(m.style.color=t.codeBlockTextColor),m.textContent=r.chunks.join(`
15
- `),b.append(L,m),H.appendChild(b)}if(r.status==="complete"&&r.result!==void 0){let b=g("div","tvw-space-y-1"),L=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(L.style.color=t.labelTextColor),L.textContent="Result";let m=g("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");m.style.fontSize="0.75rem",m.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(m.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(m.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(m.style.color=t.codeBlockTextColor),m.textContent=ln(r.result),b.append(L,m),H.appendChild(b)}if(r.status==="complete"&&typeof r.duration=="number"){let b=g("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(b.style.color=t.contentTextColor),b.textContent=`Duration: ${r.duration}ms`,H.appendChild(b)}let x=()=>{a.setAttribute("aria-expanded",s?"true":"false"),O.innerHTML="";let b=t.toggleTextColor||t.headerTextColor||"currentColor",L=We(s?"chevron-up":"chevron-down",16,b,2);L?O.appendChild(L):O.textContent=s?"Hide":"Show",H.style.display=s?"":"none"},ee=()=>{s=!s,s?yn.add(e.id):yn.delete(e.id),x()};return a.addEventListener("pointerdown",b=>{b.preventDefault(),ee()}),a.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),ee())}),x(),o.append(a,H),o};var _o=e=>{let n=[];return{buttons:n,render:(t,o,s,a,l)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(a!=null?a:o?o.getMessages():[]).some(H=>H.role==="user"))return;let u=document.createDocumentFragment(),N=o?o.isStreaming():!1,P=H=>{switch(H){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(H=>{let x=g("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");x.type="button",x.textContent=H,x.disabled=N,l!=null&&l.fontFamily&&(x.style.fontFamily=P(l.fontFamily)),l!=null&&l.fontWeight&&(x.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(x.style.paddingLeft=l.paddingX,x.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(x.style.paddingTop=l.paddingY,x.style.paddingBottom=l.paddingY),x.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(H))}),u.appendChild(x),n.push(x)}),e.appendChild(u)}}};var jo={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},bn=(e,n,r,t)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,ee,k;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let l=(ee=jo[a])!=null?ee:jo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let p=g("div","tvw-space-y-1"),O=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(O.textContent=l.title,p.appendChild(O),l.description){let b=g("p","tvw-text-sm tvw-text-cw-muted");b.textContent=l.description,p.appendChild(b)}let u=document.createElement("form");u.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(b=>{var ke,Re;let L=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");L.htmlFor=`${n.id}-${a}-${b.name}`;let m=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");m.textContent=b.label,L.appendChild(m);let Le=(ke=b.type)!=null?ke:"text",pe;Le==="textarea"?(pe=document.createElement("textarea"),pe.rows=3):(pe=document.createElement("input"),pe.type=Le),pe.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",pe.id=`${n.id}-${a}-${b.name}`,pe.name=b.name,pe.placeholder=(Re=b.placeholder)!=null?Re:"",b.required&&(pe.required=!0),L.appendChild(pe),u.appendChild(L)});let N=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),P=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),H=g("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");H.type="submit",H.textContent=(k=l.submitLabel)!=null?k:"Submit",N.appendChild(P),N.appendChild(H),u.appendChild(N),s.replaceChildren(p,u),u.addEventListener("submit",async b=>{var pe,ke;b.preventDefault();let L=(pe=r.formEndpoint)!=null?pe:"/form",m=new FormData(u),Le={};m.forEach((Re,Be)=>{Le[Be]=Re}),Le.type=a,H.disabled=!0,P.textContent="Submitting\u2026";try{let Re=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Le)});if(!Re.ok)throw new Error(`Form submission failed (${Re.status})`);let Be=await Re.json();P.textContent=(ke=Be.message)!=null?ke:"Thanks! We'll be in touch soon.",Be.success&&Be.nextPrompt&&await t.sendMessage(String(Be.nextPrompt))}catch(Re){P.textContent=Re instanceof Error?Re.message:"Something went wrong. Please try again."}finally{H.disabled=!1}})})};var Cn=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 t;let r=this.plugins.get(n);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let t=new Set(n.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...n].sort((s,a)=>{var l,p;return((l=a.priority)!=null?l:0)-((p=s.priority)!=null?p:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},nn=new Cn;var nt={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?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},debug:!1};function Sn(e){var n,r,t;return e?{...nt,...e,theme:{...nt.theme,...e.theme},launcher:{...nt.launcher,...e.launcher,clearChat:{...(n=nt.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...nt.copy,...e.copy},sendButton:{...nt.sendButton,...e.sendButton},statusIndicator:{...nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...nt.voiceRecognition,...e.voiceRecognition},features:{...nt.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:nt.suggestionChips,suggestionChipsConfig:{...nt.suggestionChipsConfig,...e.suggestionChipsConfig}}:nt}var Uo=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:n,off:r,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(l=>{try{l(s)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var cr=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},dr=e=>{let n=e.trim(),r=n.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(r,o+1)}return null},on=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=cr(e),r=dr(n);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},An=e=>typeof e=="string"?e:e==null?"":String(e),Yt={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:An(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=An(r.element);if(t&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:An(r.text)}}},Vo=e=>Array.isArray(e)?e.map(n=>String(n)):[],rn=e=>{let n=new Set(Vo(e.getMetadata().processedActionMessageIds)),r=()=>{n=new Set(Vo(e.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(n);e.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 l=a?e.parsers.reduce((O,u)=>O||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!l)return null;n.add(s.message.id),t();let p={action:l,message:s.message};e.emit("action:detected",p);for(let O of e.handlers)if(O)try{let u=O(l,{message:s.message,metadata:e.getMetadata(),updateMetadata:e.updateMetadata,document:e.documentRef});if(!u)continue;if(u.handled){let N=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:N}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:r}};var ur=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},gr=e=>e.map(n=>({...n,streaming:!1})),Tn=(e="vanilla-agent-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?ur(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?gr(r.messages):void 0};t.setItem(e,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(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var En=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([r,t])=>{this.register(r,t)})}},en=new En;import{parse as pr,STR as mr,OBJ as fr}from"partial-json";function wr(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function hr(e,n){if(!wr(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:n}}function Mn(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e;try{let o=pr(r,mr|fr),s=hr(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function vr(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Wn(e,n){let{config:r,message:t,onPropsUpdate:o}=n,s=en.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:t,config:r,updateProps:l=>{o&&o(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function yr(){let e=Mn();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ln(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function kn(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var Jt="vanilla-agent-chat-history",xr=30*1e3,Bn=e=>!e||typeof e!="object"?{}:{...e},Ko=e=>e.map(n=>({...n,streaming:!1})),Xo=(e,n)=>r=>{var s,a,l;let t=(s=r.text)!=null?s:"",o=(a=r.message.rawContent)!=null?a:null;if(n){let p=n.process({text:t,raw:o!=null?o:t,message:r.message,streaming:r.streaming});p!==null&&(t=p.text,p.persist||(r.message.__skipPersist=!0))}return e!=null&&e.postprocessMessage?e.postprocessMessage({...r,text:t,raw:(l=o!=null?o:r.text)!=null?l:""}):an(t)},Rn=(e,n,r)=>{var d,F,ae,le,ue,He,Te,ce,U,re,we,xe,Pe,pt;(!e.id||e.id!=="vanilla-agent-root")&&(e.id="vanilla-agent-root");let t=Sn(n);pn(e,t);let o=nn.getForInstance(t.plugins);t.components&&en.registerAll(t.components);let s=Uo(),a=(d=t.storageAdapter)!=null?d:Tn(),l={},p=null;if(a!=null&&a.load)try{let i=a.load();if(i&&typeof i.then=="function")p=i;else if(i){let c=i;c.metadata&&(l=Bn(c.metadata)),(F=c.messages)!=null&&F.length&&(t={...t,initialMessages:c.messages})}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",i)}let O=()=>l,u=i=>{var A;l=(A=i({...l}))!=null?A:{},Wt()},N=t.actionParsers&&t.actionParsers.length?t.actionParsers:[on],P=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Yt.message,Yt.messageAndClick],H=rn({parsers:N,handlers:P,getMetadata:O,updateMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});H.syncFromMetadata();let x=(le=(ae=t.launcher)==null?void 0:ae.enabled)!=null?le:!0,ee=(He=(ue=t.launcher)==null?void 0:ue.autoExpand)!=null?He:!1,k=ee,b=x,L=x?ee:!0,m=Xo(t,H),Le=(ce=(Te=t.features)==null?void 0:Te.showReasoning)!=null?ce:!0,pe=(re=(U=t.features)==null?void 0:U.showToolCalls)!=null?re:!0,ke=(we=t.statusIndicator)!=null?we:{},Re=i=>{var c,A,D,M;return i==="idle"?(c=ke.idleText)!=null?c:Ue.idle:i==="connecting"?(A=ke.connectingText)!=null?A:Ue.connecting:i==="connected"?(D=ke.connectedText)!=null?D:Ue.connected:i==="error"?(M=ke.errorText)!=null?M:Ue.error:Ue[i]},{wrapper:Be,panel:X}=zo(t),Ne=$o(t,x),{container:be,body:me,messagesWrapper:se,suggestions:Ce,textarea:G,sendButton:B,sendButtonWrapper:ot,composerForm:bt,statusText:Dt,introTitle:rt,introSubtitle:ne,closeButton:R,iconHolder:he,headerTitle:qt,headerSubtitle:ve}=Ne,S=Ne.micButton,De=Ne.micButtonWrapper;X.appendChild(be),e.appendChild(Be);let $e=[],dt=_o(Ce),st=null,I,ut=!1,Ae=!0,Ze=0,_=0,ie=null,gt=!1,K=0,Ke=!1,Kt=125,Ct=2e3,Ot=5,zt=50,St=new Map,oe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Et=(Pe=(xe=t.voiceRecognition)==null?void 0:xe.autoResume)!=null?Pe:!1,Mt=i=>{s.emit("voice:state",{active:oe.active,source:i,timestamp:Date.now()})},it=()=>{u(i=>({...i,voiceState:{active:oe.active,timestamp:Date.now(),manuallyDeactivated:oe.manuallyDeactivated}}))},$t=()=>{var D,M;if(((D=t.voiceRecognition)==null?void 0:D.enabled)===!1)return;let i=Bn(l.voiceState),c=!!i.active,A=Number((M=i.timestamp)!=null?M:0);oe.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-A<xr&&setTimeout(()=>{oe.active||(oe.manuallyDeactivated=!1,ht("restore"))},1e3)},_t=()=>I?Ko(I.getMessages()).filter(i=>!i.__skipPersist):[];function Wt(i){if(!(a!=null&&a.save))return;let A={messages:i?Ko(i):I?_t():[],metadata:l};try{let D=a.save(A);D instanceof Promise&&D.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(D){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)}}let mt=(i=!1)=>{if(!Ae)return;let c=Date.now();gt&&c<K&&!i||(gt&&c>=K&&(gt=!1),!(!i&&!ut)&&(c-_<Kt||(_=c,ie&&cancelAnimationFrame(ie),ie=requestAnimationFrame(()=>{gt||!Ae||(Ke=!0,me.scrollTop=me.scrollHeight,Ze=me.scrollTop,requestAnimationFrame(()=>{Ke=!1}),ie=null)}))))},at=null,jt=()=>Be.querySelector("#vanilla-agent-scroll-container")||me,Ut=(i,c=500)=>{let A=i.scrollTop,D=i.clientHeight,M=i.scrollHeight,y=M-A;if(A+D>=M-2||Math.abs(y)<5)return;at!==null&&(cancelAnimationFrame(at),at=null);let V=performance.now(),E=h=>1-Math.pow(1-h,3),W=h=>{let $=i.scrollHeight;$!==M&&(M=$,y=M-A);let J=h-V,Z=Math.min(J/c,1),Oe=E(Z),Ie=A+y*Oe;i.scrollTop=Ie,Z<1?at=requestAnimationFrame(W):(i.scrollTop=i.scrollHeight,at=null)};at=requestAnimationFrame(W)},Vt=i=>{let c=new Map;i.forEach(A=>{let D=St.get(A.id);c.set(A.id,{streaming:A.streaming,role:A.role}),!D&&A.role==="assistant"&&s.emit("assistant:message",A),A.role==="assistant"&&(D!=null&&D.streaming)&&A.streaming===!1&&s.emit("assistant:complete",A)}),St.clear(),c.forEach((A,D)=>{St.set(D,A)})},ft=(i,c,A)=>{i.innerHTML="";let D=document.createDocumentFragment();c.forEach(y=>{let C=null,V=o.find(W=>!!(y.variant==="reasoning"&&W.renderReasoning||y.variant==="tool"&&W.renderToolCall||!y.variant&&W.renderMessage));if(V)if(y.variant==="reasoning"&&y.reasoning&&V.renderReasoning){if(!Le)return;C=V.renderReasoning({message:y,defaultRenderer:()=>vn(y),config:t})}else if(y.variant==="tool"&&y.toolCall&&V.renderToolCall){if(!pe)return;C=V.renderToolCall({message:y,defaultRenderer:()=>xn(y,t),config:t})}else V.renderMessage&&(C=V.renderMessage({message:y,defaultRenderer:()=>{let W=wn(y,A);return y.role!=="user"&&bn(W,y,t,I),W},config:t}));if(!C&&y.role==="assistant"&&!y.variant&&t.enableComponentStreaming!==!1&&Ln(y)){let h=kn(y);if(h){let $=Wn(h,{config:t,message:y,transform:A});if($){let J=document.createElement("div");if(J.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),J.setAttribute("data-message-id",y.id),y.content&&y.content.trim()){let Z=document.createElement("div");Z.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Z.innerHTML=A({text:y.content,message:y,streaming:!!y.streaming,raw:y.rawContent}),J.appendChild(Z)}J.appendChild($),C=J}}}if(!C)if(y.variant==="reasoning"&&y.reasoning){if(!Le)return;C=vn(y)}else if(y.variant==="tool"&&y.toolCall){if(!pe)return;C=xn(y,t)}else C=wn(y,A),y.role!=="user"&&bn(C,y,t,I);let E=document.createElement("div");E.className="tvw-flex",y.role==="user"&&E.classList.add("tvw-justify-end"),E.appendChild(C),D.appendChild(E)});let M=c.some(y=>y.role==="assistant"&&y.streaming);if(ut&&c.some(y=>y.role==="user")&&!M){let y=fn(),C=document.createElement("div");C.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(" "),C.appendChild(y);let V=document.createElement("div");V.className="tvw-flex",V.appendChild(C),D.appendChild(V)}i.appendChild(D),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let y=jt();Ut(y)})})},wt=()=>{x&&(L?(Be.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),X.classList.remove("tvw-scale-95","tvw-opacity-0"),X.classList.add("tvw-scale-100","tvw-opacity-100"),z&&(z.element.style.display="none")):(Be.classList.add("tvw-pointer-events-none","tvw-opacity-0"),X.classList.remove("tvw-scale-100","tvw-opacity-100"),X.classList.add("tvw-scale-95","tvw-opacity-0"),z&&(z.element.style.display="")))},_e=(i,c="user")=>{if(!x||L===i)return;let A=L;L=i,wt(),L&&(ye(),mt(!0));let D={open:L,source:c,timestamp:Date.now()};L&&!A?s.emit("widget:opened",D):!L&&A&&s.emit("widget:closed",D),s.emit("widget:state",{open:L,launcherEnabled:x,voiceActive:oe.active,streaming:I.isStreaming()})},At=i=>{G.disabled=i,B.disabled=i,S&&(S.disabled=i),dt.buttons.forEach(c=>{c.disabled=i})},Lt=()=>{var M,y,C,V,E,W,h,$,J,Z,Oe,Ie,ct,Q;rt.textContent=(y=(M=t.copy)==null?void 0:M.welcomeTitle)!=null?y:"Hello \u{1F44B}",ne.textContent=(V=(C=t.copy)==null?void 0:C.welcomeSubtitle)!=null?V:"Ask anything about your account or products.",G.placeholder=(W=(E=t.copy)==null?void 0:E.inputPlaceholder)!=null?W:"How can I help...",(($=(h=t.sendButton)==null?void 0:h.useIcon)!=null?$:!1)||(B.textContent=(Z=(J=t.copy)==null?void 0:J.sendButtonLabel)!=null?Z:"Send");let c=(Ie=(Oe=t.theme)==null?void 0:Oe.inputFontFamily)!=null?Ie:"sans-serif",A=(Q=(ct=t.theme)==null?void 0:ct.inputFontWeight)!=null?Q:"400",D=Ht=>{switch(Ht){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'}};G.style.fontFamily=D(c),G.style.fontWeight=A};I=new Qt(t,{onMessagesChanged(i){ft(se,i,m),I&&(i.some(D=>D.role==="user")?dt.render([],I,G,i):dt.render(t.suggestionChips,I,G,i,t.suggestionChipsConfig)),mt(!ut),Vt(i);let c=[...i].reverse().find(A=>A.role==="user");oe.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),Wt(i)},onStatusChanged(i){var D;let c=(D=t.statusIndicator)!=null?D:{},A=M=>{var y,C,V,E;return M==="idle"?(y=c.idleText)!=null?y:Ue.idle:M==="connecting"?(C=c.connectingText)!=null?C:Ue.connecting:M==="connected"?(V=c.connectedText)!=null?V:Ue.connected:M==="error"?(E=c.errorText)!=null?E:Ue.error:Ue[M]};Dt.textContent=A(i)},onStreamingChanged(i){ut=i,At(i),I&&ft(se,I.getMessages(),m),i||mt(!0)}}),p&&p.then(i=>{var c;i&&(i.metadata&&(l=Bn(i.metadata),H.syncFromMetadata()),(c=i.messages)!=null&&c.length&&I.hydrateMessages(i.messages))}).catch(i=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)});let kt=i=>{i.preventDefault();let c=G.value.trim();c&&(G.value="",I.sendMessage(c))},Bt=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),B.click())},qe=null,je=!1,lt=null,Qe=null,Rt=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ht=(i="user")=>{var y,C,V,E;if(je||I.isStreaming())return;let c=Rt();if(!c)return;qe=new c;let D=(C=((y=t.voiceRecognition)!=null?y:{}).pauseDuration)!=null?C:2e3;qe.continuous=!0,qe.interimResults=!0,qe.lang="en-US";let M=G.value;qe.onresult=W=>{let h="",$="";for(let Z=0;Z<W.results.length;Z++){let Oe=W.results[Z],Ie=Oe[0].transcript;Oe.isFinal?h+=Ie+" ":$=Ie}let J=M+h+$;G.value=J,lt&&clearTimeout(lt),(h||$)&&(lt=window.setTimeout(()=>{let Z=G.value.trim();Z&&qe&&je&&(Xe(),G.value="",I.sendMessage(Z,{viaVoice:!0}))},D))},qe.onerror=W=>{W.error!=="no-speech"&&Xe()},qe.onend=()=>{if(je){let W=G.value.trim();W&&W!==M.trim()&&(G.value="",I.sendMessage(W,{viaVoice:!0})),Xe()}};try{if(qe.start(),je=!0,oe.active=!0,i!=="system"&&(oe.manuallyDeactivated=!1),Mt(i),it(),S){Qe={backgroundColor:S.style.backgroundColor,color:S.style.color,borderColor:S.style.borderColor};let W=(V=t.voiceRecognition)!=null?V:{},h=(E=W.recordingBackgroundColor)!=null?E:"#ef4444",$=W.recordingIconColor,J=W.recordingBorderColor;if(S.classList.add("tvw-voice-recording"),S.style.backgroundColor=h,$){S.style.color=$;let Z=S.querySelector("svg");Z&&Z.setAttribute("stroke",$)}J&&(S.style.borderColor=J),S.setAttribute("aria-label","Stop voice recognition")}}catch{Xe("system")}},Xe=(i="user")=>{if(je){if(je=!1,lt&&(clearTimeout(lt),lt=null),qe){try{qe.stop()}catch{}qe=null}if(oe.active=!1,Mt(i),it(),S){if(S.classList.remove("tvw-voice-recording"),Qe){S.style.backgroundColor=Qe.backgroundColor,S.style.color=Qe.color,S.style.borderColor=Qe.borderColor;let c=S.querySelector("svg");c&&c.setAttribute("stroke",Qe.color||"currentColor"),Qe=null}S.setAttribute("aria-label","Start voice recognition")}}},f=(i,c)=>{var Ie,ct,Q,Ht,Pt,Ee,et;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let D=g("div","tvw-send-button-wrapper"),M=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");M.type="button",M.setAttribute("aria-label","Start voice recognition");let y=(Ie=i==null?void 0:i.iconName)!=null?Ie:"mic",C=(ct=c==null?void 0:c.size)!=null?ct:"40px",V=(Q=i==null?void 0:i.iconSize)!=null?Q:C,E=parseFloat(V)||24,W=(Ht=i==null?void 0:i.backgroundColor)!=null?Ht:c==null?void 0:c.backgroundColor,h=(Pt=i==null?void 0:i.iconColor)!=null?Pt:c==null?void 0:c.textColor;M.style.width=V,M.style.height=V,M.style.minWidth=V,M.style.minHeight=V,M.style.fontSize="18px",M.style.lineHeight="1";let $=h||"currentColor",J=We(y,E,$,1.5);J?(M.appendChild(J),M.style.color=$):(M.textContent="\u{1F3A4}",M.style.color=$),W?M.style.backgroundColor=W:M.classList.add("tvw-bg-cw-primary"),h?M.style.color=h:!h&&!(c!=null&&c.textColor)&&M.classList.add("tvw-text-white"),i!=null&&i.borderWidth&&(M.style.borderWidth=i.borderWidth,M.style.borderStyle="solid"),i!=null&&i.borderColor&&(M.style.borderColor=i.borderColor),i!=null&&i.paddingX&&(M.style.paddingLeft=i.paddingX,M.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(M.style.paddingTop=i.paddingY,M.style.paddingBottom=i.paddingY),D.appendChild(M);let Z=(Ee=i==null?void 0:i.tooltipText)!=null?Ee:"Start voice recognition";if(((et=i==null?void 0:i.showTooltip)!=null?et:!1)&&Z){let vt=g("div","tvw-send-button-tooltip");vt.textContent=Z,D.appendChild(vt)}return{micButton:M,micButtonWrapper:D}},j=()=>{if(je){let i=G.value.trim();oe.manuallyDeactivated=!0,it(),Xe("user"),i&&(G.value="",I.sendMessage(i))}else oe.manuallyDeactivated=!1,it(),ht("user")};S&&(S.addEventListener("click",j),$e.push(()=>{Xe("system"),S&&S.removeEventListener("click",j)}));let Y=s.on("assistant:complete",()=>{Et&&(oe.active||oe.manuallyDeactivated||Et==="assistant"&&!oe.lastUserMessageWasVoice||setTimeout(()=>{!oe.active&&!oe.manuallyDeactivated&&ht("auto")},600))});$e.push(Y);let fe=()=>{_e(!L,"user")},z=x?mn(t,fe):null;z&&e.appendChild(z.element),wt(),dt.render(t.suggestionChips,I,G,void 0,t.suggestionChipsConfig),Lt(),At(I.isStreaming()),mt(!0),$t();let ye=()=>{var C,V;if(!x){X.style.height="",X.style.width="";return}let i=(V=(C=t==null?void 0:t.launcher)==null?void 0:C.width)!=null?V:t==null?void 0:t.launcherWidth,c=i!=null?i:"min(400px, calc(100vw - 24px))";X.style.width=c,X.style.maxWidth=c;let A=window.innerHeight,M=Math.max(200,A-64),y=Math.min(640,M);X.style.height=`${y}px`};ye(),window.addEventListener("resize",ye),$e.push(()=>window.removeEventListener("resize",ye)),Ze=me.scrollTop;let de=()=>{let i=me.scrollTop,c=me.scrollHeight,A=me.clientHeight,D=c-i-A,M=Math.abs(i-Ze);if(Ze=i,!Ke&&!(M<=Ot)){if(!Ae&&D<zt){gt=!1,Ae=!0;return}Ae&&D>zt&&(gt=!0,K=Date.now()+Ct,Ae=!1)}};me.addEventListener("scroll",de,{passive:!0}),$e.push(()=>me.removeEventListener("scroll",de)),$e.push(()=>{ie&&cancelAnimationFrame(ie)});let v=()=>{R&&(st&&(R.removeEventListener("click",st),st=null),x?(R.style.display="",st=()=>{L=!1,wt()},R.addEventListener("click",st)):R.style.display="none")};v(),(()=>{let{clearChatButton:i}=Ne;i&&i.addEventListener("click",()=>{I.clearMessages();try{localStorage.removeItem(Jt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Jt}`)}catch(A){console.error("[AgentWidget] Failed to clear default localStorage:",A)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Jt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(A){console.error("[AgentWidget] Failed to clear custom localStorage:",A)}let c=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),a!=null&&a.clear)try{let A=a.clear();A instanceof Promise&&A.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",D)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)}l={},H.syncFromMetadata()})})(),bt.addEventListener("submit",kt),G.addEventListener("keydown",Bt),$e.push(()=>{bt.removeEventListener("submit",kt),G.removeEventListener("keydown",Bt)}),$e.push(()=>{I.cancel()}),z&&$e.push(()=>{z==null||z.destroy()});let q={update(i){var Pn,In,Fn,Nn,Dn,qn,On,zn,$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,Ao,To,Eo,Mo,Wo,Lo,ko,Bo;let c=t.toolCall;t={...t,...i},pn(e,t);let A=nn.getForInstance(t.plugins);o.length=0,o.push(...A),x=(In=(Pn=t.launcher)==null?void 0:Pn.enabled)!=null?In:!0,ee=(Nn=(Fn=t.launcher)==null?void 0:Fn.autoExpand)!=null?Nn:!1,Le=(qn=(Dn=t.features)==null?void 0:Dn.showReasoning)!=null?qn:!0,pe=(zn=(On=t.features)==null?void 0:On.showToolCalls)!=null?zn:!0,(($n=t.launcher)==null?void 0:$n.enabled)===!1&&z&&(z.destroy(),z=null),((_n=t.launcher)==null?void 0:_n.enabled)!==!1&&!z&&(z=mn(t,fe),e.appendChild(z.element)),z&&z.update(t),qt&&((jn=t.launcher)==null?void 0:jn.title)!==void 0&&(qt.textContent=t.launcher.title),ve&&((Un=t.launcher)==null?void 0:Un.subtitle)!==void 0&&(ve.textContent=t.launcher.subtitle),x!==b?x?_e(ee,"auto"):(L=!0,wt()):ee!==k&&_e(ee,"auto"),k=ee,b=x,ye(),v(),JSON.stringify(i.toolCall)!==JSON.stringify(c)&&I&&ft(se,I.getMessages(),m);let C=(Vn=t.launcher)!=null?Vn:{},V=(Kn=C.headerIconHidden)!=null?Kn:!1,E=C.headerIconName,W=(Xn=C.headerIconSize)!=null?Xn:"48px";if(he){let T=be.querySelector(".tvw-border-b-cw-divider"),Me=T==null?void 0:T.querySelector(".tvw-flex-col");if(V)he.style.display="none",T&&Me&&!T.contains(Me)&&T.insertBefore(Me,T.firstChild);else{if(he.style.display="",he.style.height=W,he.style.width=W,T&&Me&&(T.contains(he)?he.nextSibling!==Me&&(he.remove(),T.insertBefore(he,Me)):T.insertBefore(he,Me)),E){let ze=parseFloat(W)||24,ge=We(E,ze*.6,"#ffffff",2);ge?he.replaceChildren(ge):he.textContent=(Yn=C.agentIconText)!=null?Yn:"\u{1F4AC}"}else if(C.iconUrl){let ze=he.querySelector("img");if(ze)ze.src=C.iconUrl,ze.style.height=W,ze.style.width=W;else{let ge=document.createElement("img");ge.src=C.iconUrl,ge.alt="",ge.className="tvw-rounded-xl tvw-object-cover",ge.style.height=W,ge.style.width=W,he.replaceChildren(ge)}}else{let ze=he.querySelector("svg"),ge=he.querySelector("img");(ze||ge)&&he.replaceChildren(),he.textContent=(Jn=C.agentIconText)!=null?Jn:"\u{1F4AC}"}let Fe=he.querySelector("img");Fe&&(Fe.style.height=W,Fe.style.width=W)}}if(R){let T=(Gn=C.closeButtonSize)!=null?Gn:"32px",Me=(Zn=C.closeButtonPlacement)!=null?Zn:"inline";R.style.height=T,R.style.width=T;let Fe=Me==="top-right",ze=R.classList.contains("tvw-absolute");if(Fe!==ze)if(R.remove(),Fe)R.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",be.style.position="relative",be.appendChild(R);else{R.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 te=be.querySelector(".tvw-border-b-cw-divider");te&&te.appendChild(R)}if(C.closeButtonColor?(R.style.color=C.closeButtonColor,R.classList.remove("tvw-text-cw-muted")):(R.style.color="",R.classList.add("tvw-text-cw-muted")),C.closeButtonBackgroundColor?(R.style.backgroundColor=C.closeButtonBackgroundColor,R.classList.remove("hover:tvw-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:tvw-bg-gray-100")),C.closeButtonBorderWidth||C.closeButtonBorderColor){let te=C.closeButtonBorderWidth||"0px",xt=C.closeButtonBorderColor||"transparent";R.style.border=`${te} solid ${xt}`,R.classList.remove("tvw-border-none")}else R.style.border="",R.classList.add("tvw-border-none");C.closeButtonBorderRadius?(R.style.borderRadius=C.closeButtonBorderRadius,R.classList.remove("tvw-rounded-full")):(R.style.borderRadius="",R.classList.add("tvw-rounded-full")),C.closeButtonPaddingX?(R.style.paddingLeft=C.closeButtonPaddingX,R.style.paddingRight=C.closeButtonPaddingX):(R.style.paddingLeft="",R.style.paddingRight=""),C.closeButtonPaddingY?(R.style.paddingTop=C.closeButtonPaddingY,R.style.paddingBottom=C.closeButtonPaddingY):(R.style.paddingTop="",R.style.paddingBottom="");let ge=(Qn=C.closeButtonIconName)!=null?Qn:"x",Tt=(eo=C.closeButtonIconText)!=null?eo:"\xD7";R.innerHTML="";let Je=We(ge,"20px",C.closeButtonColor||"",2);Je?R.appendChild(Je):R.textContent=Tt;let{closeButtonWrapper:Ve}=Ne,Se=(to=C.closeButtonTooltipText)!=null?to:"Close chat",Ge=(no=C.closeButtonShowTooltip)!=null?no:!0;if(R.setAttribute("aria-label",Se),Ve&&(Ve._cleanupTooltip&&(Ve._cleanupTooltip(),delete Ve._cleanupTooltip),Ge&&Se)){let te=null,xt=()=>{if(te||!R)return;te=g("div","tvw-clear-chat-tooltip"),te.textContent=Se;let Ro=g("div");Ro.className="tvw-clear-chat-tooltip-arrow",te.appendChild(Ro);let sn=R.getBoundingClientRect();te.style.position="fixed",te.style.left=`${sn.left+sn.width/2}px`,te.style.top=`${sn.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},tt=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};Ve.addEventListener("mouseenter",xt),Ve.addEventListener("mouseleave",tt),R.addEventListener("focus",xt),R.addEventListener("blur",tt),Ve._cleanupTooltip=()=>{tt(),Ve&&(Ve.removeEventListener("mouseenter",xt),Ve.removeEventListener("mouseleave",tt)),R&&(R.removeEventListener("focus",xt),R.removeEventListener("blur",tt))}}}let{clearChatButton:h,clearChatButtonWrapper:$}=Ne;if(h){let T=(oo=C.clearChat)!=null?oo:{},Me=(ro=T.enabled)!=null?ro:!0;if($&&($.style.display=Me?"":"none"),Me){let Fe=(so=T.size)!=null?so:"32px";h.style.height=Fe,h.style.width=Fe;let ze=(io=T.iconName)!=null?io:"refresh-cw",ge=(ao=T.iconColor)!=null?ao:"";h.innerHTML="";let Tt=We(ze,"20px",ge||"",2);if(Tt&&h.appendChild(Tt),ge?(h.style.color=ge,h.classList.remove("tvw-text-cw-muted")):(h.style.color="",h.classList.add("tvw-text-cw-muted")),T.backgroundColor?(h.style.backgroundColor=T.backgroundColor,h.classList.remove("hover:tvw-bg-gray-100")):(h.style.backgroundColor="",h.classList.add("hover:tvw-bg-gray-100")),T.borderWidth||T.borderColor){let Se=T.borderWidth||"0px",Ge=T.borderColor||"transparent";h.style.border=`${Se} solid ${Ge}`,h.classList.remove("tvw-border-none")}else h.style.border="",h.classList.add("tvw-border-none");T.borderRadius?(h.style.borderRadius=T.borderRadius,h.classList.remove("tvw-rounded-full")):(h.style.borderRadius="",h.classList.add("tvw-rounded-full")),T.paddingX?(h.style.paddingLeft=T.paddingX,h.style.paddingRight=T.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),T.paddingY?(h.style.paddingTop=T.paddingY,h.style.paddingBottom=T.paddingY):(h.style.paddingTop="",h.style.paddingBottom="");let Je=(lo=T.tooltipText)!=null?lo:"Clear chat",Ve=(co=T.showTooltip)!=null?co:!0;if(h.setAttribute("aria-label",Je),$&&($._cleanupTooltip&&($._cleanupTooltip(),delete $._cleanupTooltip),Ve&&Je)){let Se=null,Ge=()=>{if(Se||!h)return;Se=g("div","tvw-clear-chat-tooltip"),Se.textContent=Je;let xt=g("div");xt.className="tvw-clear-chat-tooltip-arrow",Se.appendChild(xt);let tt=h.getBoundingClientRect();Se.style.position="fixed",Se.style.left=`${tt.left+tt.width/2}px`,Se.style.top=`${tt.top-8}px`,Se.style.transform="translate(-50%, -100%)",document.body.appendChild(Se)},te=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};$.addEventListener("mouseenter",Ge),$.addEventListener("mouseleave",te),h.addEventListener("focus",Ge),h.addEventListener("blur",te),$._cleanupTooltip=()=>{te(),$&&($.removeEventListener("mouseenter",Ge),$.removeEventListener("mouseleave",te)),h&&(h.removeEventListener("focus",Ge),h.removeEventListener("blur",te))}}}}let J=t.actionParsers&&t.actionParsers.length?t.actionParsers:[on],Z=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Yt.message,Yt.messageAndClick];H=rn({parsers:J,handlers:Z,getMetadata:O,updateMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),m=Xo(t,H),I.updateConfig(t),ft(se,I.getMessages(),m),dt.render(t.suggestionChips,I,G,void 0,t.suggestionChipsConfig),Lt(),At(I.isStreaming());let Oe=((uo=t.voiceRecognition)==null?void 0:uo.enabled)===!0,Ie=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ct=Oe&&Ie;if(bt.classList.remove("tvw-gap-1","tvw-gap-3"),bt.classList.add(ct?"tvw-gap-1":"tvw-gap-3"),Oe&&Ie)if(!S||!De){let T=f(t.voiceRecognition,t.sendButton);T&&(S=T.micButton,De=T.micButtonWrapper,bt.insertBefore(De,ot),S.addEventListener("click",j),S.disabled=I.isStreaming())}else{let T=(go=t.voiceRecognition)!=null?go:{},Me=(po=t.sendButton)!=null?po:{},Fe=(mo=T.iconName)!=null?mo:"mic",ze=(fo=Me.size)!=null?fo:"40px",ge=(wo=T.iconSize)!=null?wo:ze,Tt=parseFloat(ge)||24;S.style.width=ge,S.style.height=ge,S.style.minWidth=ge,S.style.minHeight=ge;let Je=(vo=(ho=T.iconColor)!=null?ho:Me.textColor)!=null?vo:"currentColor";S.innerHTML="";let Ve=We(Fe,Tt,Je,2);Ve?S.appendChild(Ve):S.textContent="\u{1F3A4}";let Se=(yo=T.backgroundColor)!=null?yo:Me.backgroundColor;Se?(S.style.backgroundColor=Se,S.classList.remove("tvw-bg-cw-primary")):(S.style.backgroundColor="",S.classList.add("tvw-bg-cw-primary")),Je?(S.style.color=Je,S.classList.remove("tvw-text-white")):!Je&&!Me.textColor&&(S.style.color="",S.classList.add("tvw-text-white")),T.borderWidth?(S.style.borderWidth=T.borderWidth,S.style.borderStyle="solid"):(S.style.borderWidth="",S.style.borderStyle=""),T.borderColor?S.style.borderColor=T.borderColor:S.style.borderColor="",T.paddingX?(S.style.paddingLeft=T.paddingX,S.style.paddingRight=T.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),T.paddingY?(S.style.paddingTop=T.paddingY,S.style.paddingBottom=T.paddingY):(S.style.paddingTop="",S.style.paddingBottom="");let Ge=De==null?void 0:De.querySelector(".tvw-send-button-tooltip"),te=(xo=T.tooltipText)!=null?xo:"Start voice recognition";if(((bo=T.showTooltip)!=null?bo:!1)&&te)if(Ge)Ge.textContent=te,Ge.style.display="";else{let tt=document.createElement("div");tt.className="tvw-send-button-tooltip",tt.textContent=te,De==null||De.insertBefore(tt,S)}else Ge&&(Ge.style.display="none");De.style.display="",S.disabled=I.isStreaming()}else S&&De&&(De.style.display="none",je&&Xe());let Q=(Co=t.sendButton)!=null?Co:{},Ht=(So=Q.useIcon)!=null?So:!1,Pt=(Ao=Q.iconText)!=null?Ao:"\u2191",Ee=Q.iconName,et=(To=Q.tooltipText)!=null?To:"Send message",vt=(Eo=Q.showTooltip)!=null?Eo:!1,It=(Mo=Q.size)!=null?Mo:"40px",Ft=Q.backgroundColor,yt=Q.textColor;if(Ht){if(B.style.width=It,B.style.height=It,B.style.minWidth=It,B.style.minHeight=It,B.style.fontSize="18px",B.style.lineHeight="1",B.innerHTML="",Ee){let T=parseFloat(It)||24,Me=yt&&typeof yt=="string"&&yt.trim()?yt.trim():"currentColor",Fe=We(Ee,T,Me,2);Fe?(B.appendChild(Fe),B.style.color=Me):(B.textContent=Pt,yt?B.style.color=yt:B.classList.add("tvw-text-white"))}else B.textContent=Pt,yt?B.style.color=yt:B.classList.add("tvw-text-white");B.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Ft?(B.style.backgroundColor=Ft,B.classList.remove("tvw-bg-cw-primary")):B.classList.add("tvw-bg-cw-primary")}else B.textContent=(Lo=(Wo=t.copy)==null?void 0:Wo.sendButtonLabel)!=null?Lo:"Send",B.style.width="",B.style.height="",B.style.minWidth="",B.style.minHeight="",B.style.fontSize="",B.style.lineHeight="",B.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",Ft?(B.style.backgroundColor=Ft,B.classList.remove("tvw-bg-cw-accent")):B.classList.add("tvw-bg-cw-accent"),yt?B.style.color=yt:B.classList.add("tvw-text-white");Q.borderWidth?(B.style.borderWidth=Q.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),Q.borderColor?B.style.borderColor=Q.borderColor:B.style.borderColor="",Q.paddingX?(B.style.paddingLeft=Q.paddingX,B.style.paddingRight=Q.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),Q.paddingY?(B.style.paddingTop=Q.paddingY,B.style.paddingBottom=Q.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Gt=ot==null?void 0:ot.querySelector(".tvw-send-button-tooltip");if(vt&&et)if(Gt)Gt.textContent=et,Gt.style.display="";else{let T=document.createElement("div");T.className="tvw-send-button-tooltip",T.textContent=et,ot==null||ot.insertBefore(T,B)}else Gt&&(Gt.style.display="none");let Zt=(ko=t.statusIndicator)!=null?ko:{},Go=(Bo=Zt.visible)!=null?Bo:!0;if(Dt.style.display=Go?"":"none",I){let T=I.getStatus(),Me=Fe=>{var ze,ge,Tt,Je;return Fe==="idle"?(ze=Zt.idleText)!=null?ze:Ue.idle:Fe==="connecting"?(ge=Zt.connectingText)!=null?ge:Ue.connecting:Fe==="connected"?(Tt=Zt.connectedText)!=null?Tt:Ue.connected:Fe==="error"?(Je=Zt.errorText)!=null?Je:Ue.error:Ue[Fe]};Dt.textContent=Me(T)}},open(){x&&_e(!0,"api")},close(){x&&_e(!1,"api")},toggle(){x&&_e(!L,"api")},clearChat(){I.clearMessages();try{localStorage.removeItem(Jt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Jt}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Jt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(i),a!=null&&a.clear)try{let c=a.clear();c instanceof Promise&&c.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}l={},H.syncFromMetadata()},setMessage(i){return!G||I.isStreaming()?!1:(!L&&x&&_e(!0,"system"),G.value=i,G.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(I.isStreaming())return!1;let c=(i==null?void 0:i.trim())||G.value.trim();return c?(!L&&x&&_e(!0,"system"),G.value="",I.sendMessage(c),!0):!1},startVoiceRecognition(){return je||I.isStreaming()||!Rt()?!1:(!L&&x&&_e(!0,"system"),oe.manuallyDeactivated=!1,it(),ht("user"),!0)},stopVoiceRecognition(){return je?(oe.manuallyDeactivated=!0,it(),Xe("user"),!0):!1},injectTestMessage(i){!L&&x&&_e(!0,"system"),I.injectTestEvent(i)},getMessages(){return I.getMessages()},getStatus(){return I.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(i){u(i)},on(i,c){return s.on(i,c)},off(i,c){s.off(i,c)},isOpen(){return x&&L},isVoiceActive(){return oe.active},getState(){return{open:x&&L,launcherEnabled:x,voiceActive:oe.active,streaming:I.isStreaming()}},destroy(){$e.forEach(i=>i()),Be.remove(),z==null||z.destroy(),st&&R.removeEventListener("click",st)}};if((((pt=r==null?void 0:r.debugTools)!=null?pt:!1)||!!t.debug)&&typeof window!="undefined"){let i=window.AgentWidgetBrowser,c={controller:q,getMessages:q.getMessages,getStatus:q.getStatus,getMetadata:q.getPersistentMetadata,updateMetadata:q.updatePersistentMetadata,clearHistory:()=>q.clearChat(),setVoiceActive:A=>A?q.startVoiceRecognition():q.stopVoiceRecognition()};window.AgentWidgetBrowser=c,$e.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}return q};var Hn={},br=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},Cr=()=>{try{if(typeof Hn!="undefined"&&Hn.url)return new URL("../widget.css",Hn.url).href}catch{}return null},Yo=e=>{let n=Cr(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-vanilla-agent","true"),e.insertBefore(t,e.firstChild)}else 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)}},Jo=e=>{var p;let n=br(e.target),r=document.createElement("div");r.className="vanilla-agent-host",n.appendChild(r);let t=e.useShadowDom!==!1,o,s;if(t){let O=r.attachShadow({mode:"open"});s=O,o=document.createElement("div"),o.id="vanilla-agent-root",O.appendChild(o),Yo(O)}else s=r,o=document.createElement("div"),o.id="vanilla-agent-root",r.appendChild(o),Yo(r);let a=Rn(o,e.config,{debugTools:e.debugTools});(p=e.onReady)==null||p.call(e);let l={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=l),l};var _s=Jo;export{Xt as AgentWidgetClient,Qt as AgentWidgetSession,nt as DEFAULT_WIDGET_CONFIG,en as componentRegistry,rn as createActionManager,Rn as createAgentExperience,yr as createComponentMiddleware,Mn as createComponentStreamParser,rr as createFlexibleJsonStreamParser,un as createJsonStreamParser,Tn as createLocalStorageAdapter,cn as createPlainTextParser,dn as createRegexJsonParser,gn as createXmlParser,_s as default,Yt as defaultActionHandlers,on as defaultJsonActionParser,er as directivePostprocessor,an as escapeHtml,kn as extractComponentDirectiveFromMessage,Ln as hasComponentDirective,Jo as initAgentWidget,vr as isComponentDirectiveType,Io as markdownPostprocessor,Sn as mergeWithDefaults,nn as pluginRegistry,Wn as renderComponentDirective};
14
+ `,r.addEventListener("click",e);let t=s=>{var j,F,m,S,I,A,z,R,V,te;let i=(j=s.launcher)!=null?j:{},l=r.querySelector("[data-role='launcher-title']");l&&(l.textContent=(F=i.title)!=null?F:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(m=i.subtitle)!=null?m:"Get answers fast");let h=r.querySelector(".tvw-flex-col");h&&(i.textHidden?h.style.display="none":h.style.display="");let d=r.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let T=(S=i.agentIconSize)!=null?S:"40px";if(d.style.height=T,d.style.width=T,d.innerHTML="",i.agentIconName){let re=parseFloat(T)||24,Y=ge(i.agentIconName,re*.6,"#ffffff",2);Y?(d.appendChild(Y),d.style.display=""):(d.textContent=(I=i.agentIconText)!=null?I:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(A=i.agentIconText)!=null?A:"\u{1F4AC}",d.style.display="")}let E=r.querySelector("[data-role='launcher-image']");if(E){let T=(z=i.agentIconSize)!=null?z:"40px";E.style.height=T,E.style.width=T,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(E.src=i.iconUrl,E.style.display="block"):E.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let T=(R=i.callToActionIconSize)!=null?R:"32px";f.style.height=T,f.style.width=T,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let re=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,re=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let Y=parseFloat(T)||24,U=Math.max(Y-re,8),ne=ge(i.callToActionIconName,U,"currentColor",2);ne?f.appendChild(ne):f.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}else f.textContent=(te=i.callToActionIconText)!=null?te:"\u2197"}let C=i.position&&It[i.position]?It[i.position]:It["bottom-right"],y="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=`${y} ${C}`},o=()=>{r.removeEventListener("click",e),r.remove()};return n&&t(n),{element:r,update:t,destroy:o}};var Dt=n=>{var re,Y,U,ne,ue,se,$,qe,Je,et,wt,yt,O,de,pt,gt,Ke,rt,B,ke,it,at,St,ht,Pe,tt,Ue,N,lt,Xe,Ee,Fe;let{config:e,showClose:r=!0}=n,t=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=(re=e==null?void 0:e.launcher)!=null?re:{},s=(Y=o.headerIconSize)!=null?Y:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",l=(ne=o.closeButtonPlacement)!=null?ne:"inline",u=(ue=o.headerIconHidden)!=null?ue:!1,h=o.headerIconName,d=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(d.style.height=s,d.style.width=s,!u)if(h){let J=parseFloat(s)||24,ye=ge(h,J*.6,"#ffffff",2);ye?d.replaceChildren(ye):d.textContent=($=(se=e==null?void 0:e.launcher)==null?void 0:se.agentIconText)!=null?$:"\u{1F4AC}"}else if((qe=e==null?void 0:e.launcher)!=null&&qe.iconUrl){let J=c("img");J.src=e.launcher.iconUrl,J.alt="",J.className="tvw-rounded-xl tvw-object-cover",J.style.height=s,J.style.width=s,d.replaceChildren(J)}else d.textContent=(et=(Je=e==null?void 0:e.launcher)==null?void 0:Je.agentIconText)!=null?et:"\u{1F4AC}";let E=c("div","tvw-flex tvw-flex-col"),f=c("span","tvw-text-base tvw-font-semibold");f.textContent=(yt=(wt=e==null?void 0:e.launcher)==null?void 0:wt.title)!=null?yt:"Chat Assistant";let C=c("span","tvw-text-xs tvw-text-cw-muted");C.textContent=(de=(O=e==null?void 0:e.launcher)==null?void 0:O.subtitle)!=null?de:"Here to help you get answers fast",E.append(f,C),u?t.append(E):t.append(d,E);let y=(pt=o.clearChat)!=null?pt:{},j=(gt=y.enabled)!=null?gt:!0,F=(Ke=y.placement)!=null?Ke:"inline",m=null,S=null;if(j){let J=(rt=y.size)!=null?rt:"32px",ye=(B=y.iconName)!=null?B:"refresh-cw",Re=(ke=y.iconColor)!=null?ke:"",ze=(it=y.backgroundColor)!=null?it:"",nt=(at=y.borderWidth)!=null?at:"",vt=(St=y.borderColor)!=null?St:"",Wt=(ht=y.borderRadius)!=null?ht:"",ct=(Pe=y.paddingX)!=null?Pe:"",bt=(tt=y.paddingY)!=null?tt:"",ie=(Ue=y.tooltipText)!=null?Ue:"Clear chat",$t=(N=y.showTooltip)!=null?N:!0;S=c("div",F==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),F==="top-right"&&(S.style.right="48px"),m=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"),m.style.height=J,m.style.width=J,m.type="button",m.setAttribute("aria-label",ie);let Mt=ge(ye,"20px",Re||"",2);if(Mt&&m.appendChild(Mt),Re&&(m.style.color=Re,m.classList.remove("tvw-text-cw-muted")),ze&&(m.style.backgroundColor=ze,m.classList.remove("hover:tvw-bg-gray-100")),nt||vt){let he=nt||"0px",mt=vt||"transparent";m.style.border=`${he} solid ${mt}`,m.classList.remove("tvw-border-none")}if(Wt&&(m.style.borderRadius=Wt,m.classList.remove("tvw-rounded-full")),ct?(m.style.paddingLeft=ct,m.style.paddingRight=ct):(m.style.paddingLeft="",m.style.paddingRight=""),bt?(m.style.paddingTop=bt,m.style.paddingBottom=bt):(m.style.paddingTop="",m.style.paddingBottom=""),S.appendChild(m),$t&&ie&&m&&S){let he=null,mt=()=>{if(he||!m)return;he=c("div","tvw-clear-chat-tooltip"),he.textContent=ie;let Lt=c("div");Lt.className="tvw-clear-chat-tooltip-arrow",he.appendChild(Lt);let ft=m.getBoundingClientRect();he.style.position="fixed",he.style.left=`${ft.left+ft.width/2}px`,he.style.top=`${ft.top-8}px`,he.style.transform="translate(-50%, -100%)",document.body.appendChild(he)},xt=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};S.addEventListener("mouseenter",mt),S.addEventListener("mouseleave",xt),m.addEventListener("focus",mt),m.addEventListener("blur",xt),S._cleanupTooltip=()=>{xt(),S&&(S.removeEventListener("mouseenter",mt),S.removeEventListener("mouseleave",xt)),m&&(m.removeEventListener("focus",mt),m.removeEventListener("blur",xt))}}F==="inline"&&t.appendChild(S)}let I=c("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":j&&F==="inline"?"":"tvw-ml-auto"),A=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");A.style.height=i,A.style.width=i,A.type="button";let z=(lt=o.closeButtonTooltipText)!=null?lt:"Close chat",R=(Xe=o.closeButtonShowTooltip)!=null?Xe:!0;A.setAttribute("aria-label",z),A.style.display=r?"":"none";let V=(Ee=o.closeButtonIconName)!=null?Ee:"x",te=(Fe=o.closeButtonIconText)!=null?Fe:"\xD7",T=ge(V,"20px",o.closeButtonColor||"",2);if(T?A.appendChild(T):A.textContent=te,o.closeButtonColor?(A.style.color=o.closeButtonColor,A.classList.remove("tvw-text-cw-muted")):(A.style.color="",A.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(A.style.backgroundColor=o.closeButtonBackgroundColor,A.classList.remove("hover:tvw-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let J=o.closeButtonBorderWidth||"0px",ye=o.closeButtonBorderColor||"transparent";A.style.border=`${J} solid ${ye}`,A.classList.remove("tvw-border-none")}else A.style.border="",A.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(A.style.borderRadius=o.closeButtonBorderRadius,A.classList.remove("tvw-rounded-full")):(A.style.borderRadius="",A.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(A.style.paddingLeft=o.closeButtonPaddingX,A.style.paddingRight=o.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),o.closeButtonPaddingY?(A.style.paddingTop=o.closeButtonPaddingY,A.style.paddingBottom=o.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom=""),I.appendChild(A),R&&z){let J=null,ye=()=>{if(J)return;J=c("div","tvw-clear-chat-tooltip"),J.textContent=z;let ze=c("div");ze.className="tvw-clear-chat-tooltip-arrow",J.appendChild(ze);let nt=A.getBoundingClientRect();J.style.position="fixed",J.style.left=`${nt.left+nt.width/2}px`,J.style.top=`${nt.top-8}px`,J.style.transform="translate(-50%, -100%)",document.body.appendChild(J)},Re=()=>{J&&J.parentNode&&(J.parentNode.removeChild(J),J=null)};I.addEventListener("mouseenter",ye),I.addEventListener("mouseleave",Re),A.addEventListener("focus",ye),A.addEventListener("blur",Re),I._cleanupTooltip=()=>{Re(),I.removeEventListener("mouseenter",ye),I.removeEventListener("mouseleave",Re),A.removeEventListener("focus",ye),A.removeEventListener("blur",Re)}}return l!=="top-right"&&t.appendChild(I),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:C,closeButton:A,closeButtonWrapper:I,clearChatButton:m,clearChatButtonWrapper:S}},Qt=(n,e,r)=>{var i,l,u,h;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(l=t.closeButtonPlacement)!=null?l:"inline",s=(h=(u=t.clearChat)==null?void 0:u.placement)!=null?h:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var ro=n=>Dt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),io=n=>{var y,j,F,m;let{config:e,showClose:r=!0,onClose:t}=n,o=(y=e==null?void 0:e.launcher)!=null?y:{},s=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=c("span","tvw-text-base tvw-font-semibold");i.textContent=(j=o.title)!=null?j:"Chat Assistant",s.appendChild(i);let l=(F=o.closeButtonSize)!=null?F:"32px",u=c("div",""),h=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");h.style.height=l,h.style.width=l,h.type="button",h.setAttribute("aria-label","Close chat"),h.style.display=r?"":"none";let d=(m=o.closeButtonIconName)!=null?m:"x",E=ge(d,"20px",o.closeButtonColor||"",2);E?h.appendChild(E):h.textContent="\xD7",t&&h.addEventListener("click",t),u.appendChild(h),s.appendChild(u);let f=c("div");f.style.display="none";let C=c("span");return C.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:C,closeButton:h,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},ao=n=>{var A,z,R,V,te,T,re,Y;let{config:e,showClose:r=!0,onClose:t,onClearChat:o}=n,s=(A=e==null?void 0:e.launcher)!=null?A:{},i=c("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=c("div","tvw-flex tvw-items-center tvw-gap-3"),u=(z=s.headerIconSize)!=null?z:"56px",h=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");h.style.height=u,h.style.width=u;let d=s.headerIconName;if(d){let U=parseFloat(u)||24,ne=ge(d,U*.5,"#ffffff",2);ne?h.replaceChildren(ne):h.textContent=(R=s.agentIconText)!=null?R:"\u{1F4AC}"}else if(s.iconUrl){let U=c("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=u,U.style.width=u,h.replaceChildren(U)}else h.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let E=c("div","tvw-flex tvw-flex-col tvw-flex-1"),f=c("span","tvw-text-lg tvw-font-semibold");f.textContent=(te=s.title)!=null?te:"Chat Assistant";let C=c("span","tvw-text-sm tvw-text-cw-muted");C.textContent=(T=s.subtitle)!=null?T:"Here to help you get answers fast",E.append(f,C),l.append(h,E);let y=(re=s.closeButtonSize)!=null?re:"32px",j=c("div",""),F=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");F.style.height=y,F.style.width=y,F.type="button",F.setAttribute("aria-label","Close chat"),F.style.display=r?"":"none";let m=(Y=s.closeButtonIconName)!=null?Y:"x",S=ge(m,"20px",s.closeButtonColor||"",2);S?F.appendChild(S):F.textContent="\xD7",t&&F.addEventListener("click",t),j.appendChild(F),l.appendChild(j),i.appendChild(l);let I=c("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return I.textContent="Online and ready to help",i.appendChild(I),{header:i,iconHolder:h,headerTitle:f,headerSubtitle:C,closeButton:F,closeButtonWrapper:j,clearChatButton:null,clearChatButtonWrapper:null}},Cn={default:ro,minimal:io,expanded:ao},lo=n=>{var e;return(e=Cn[n])!=null?e:Cn.default},Sn=(n,e,r)=>{var i,l,u;if(e!=null&&e.render){let h=e.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),d=c("div");d.style.display="none";let E=c("span"),f=c("span"),C=c("button");C.style.display="none";let y=c("div");return y.style.display="none",{header:h,iconHolder:d,headerTitle:E,headerSubtitle:f,closeButton:C,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=lo(t)({config:n,showClose:(u=(l=e==null?void 0:e.showCloseButton)!=null?l:r==null?void 0:r.showClose)!=null?u:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ro=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},en=n=>{var se,$,qe,Je,et,wt,yt,O,de,pt,gt,Ke,rt,B,ke,it,at,St,ht,Pe,tt,Ue,N,lt,Xe;let{config:e}=n,r=c("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=((se=e==null?void 0:e.voiceRecognition)==null?void 0:se.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),u=c("form",`tvw-flex tvw-items-end ${o&&s?"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`);u.style.outline="none";let h=c("textarea");h.placeholder=(qe=($=e==null?void 0:e.copy)==null?void 0:$.inputPlaceholder)!=null?qe:"Type your message\u2026",h.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",h.rows=1;let d=(et=(Je=e==null?void 0:e.theme)==null?void 0:Je.inputFontFamily)!=null?et:"sans-serif",E=(yt=(wt=e==null?void 0:e.theme)==null?void 0:wt.inputFontWeight)!=null?yt:"400";h.style.fontFamily=Ro(d),h.style.fontWeight=E,h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.addEventListener("focus",()=>{h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.style.boxShadow="none"}),h.addEventListener("blur",()=>{h.style.border="none",h.style.outline="none"});let f=(O=e==null?void 0:e.sendButton)!=null?O:{},C=(de=f.useIcon)!=null?de:!1,y=(pt=f.iconText)!=null?pt:"\u2191",j=f.iconName,F=(gt=f.tooltipText)!=null?gt:"Send message",m=(Ke=f.showTooltip)!=null?Ke:!1,S=(rt=f.size)!=null?rt:"40px",I=f.backgroundColor,A=f.textColor,z=c("div","tvw-send-button-wrapper"),R=c("button",C?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(R.type="submit",C){if(R.style.width=S,R.style.height=S,R.style.minWidth=S,R.style.minHeight=S,R.style.fontSize="18px",R.style.lineHeight="1",R.innerHTML="",j){let Ee=parseFloat(S)||24,Fe=A&&typeof A=="string"&&A.trim()?A.trim():"currentColor",J=ge(j,Ee,Fe,2);J?(R.appendChild(J),R.style.color=Fe):(R.textContent=y,A?R.style.color=A:R.classList.add("tvw-text-white"))}else R.textContent=y,A?R.style.color=A:R.classList.add("tvw-text-white");I?R.style.backgroundColor=I:R.classList.add("tvw-bg-cw-primary")}else R.textContent=(ke=(B=e==null?void 0:e.copy)==null?void 0:B.sendButtonLabel)!=null?ke:"Send",A?R.style.color=A:R.classList.add("tvw-text-white");if(f.borderWidth&&(R.style.borderWidth=f.borderWidth,R.style.borderStyle="solid"),f.borderColor&&(R.style.borderColor=f.borderColor),f.paddingX?(R.style.paddingLeft=f.paddingX,R.style.paddingRight=f.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),f.paddingY?(R.style.paddingTop=f.paddingY,R.style.paddingBottom=f.paddingY):(R.style.paddingTop="",R.style.paddingBottom=""),m&&F){let Ee=c("div","tvw-send-button-tooltip");Ee.textContent=F,z.appendChild(Ee)}z.appendChild(R);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},te=V.enabled===!0,T=null,re=null,Y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(te&&Y){re=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 Ee=(at=V.iconName)!=null?at:"mic",Fe=(St=V.iconSize)!=null?St:S,J=parseFloat(Fe)||24,ye=(ht=V.backgroundColor)!=null?ht:I,Re=(Pe=V.iconColor)!=null?Pe:A;T.style.width=Fe,T.style.height=Fe,T.style.minWidth=Fe,T.style.minHeight=Fe,T.style.fontSize="18px",T.style.lineHeight="1";let ze=Re||"currentColor",nt=ge(Ee,J,ze,1.5);nt?(T.appendChild(nt),T.style.color=ze):(T.textContent="\u{1F3A4}",T.style.color=ze),ye?T.style.backgroundColor=ye:T.classList.add("tvw-bg-cw-primary"),Re?T.style.color=Re:!Re&&!A&&T.classList.add("tvw-text-white"),V.borderWidth&&(T.style.borderWidth=V.borderWidth,T.style.borderStyle="solid"),V.borderColor&&(T.style.borderColor=V.borderColor),V.paddingX&&(T.style.paddingLeft=V.paddingX,T.style.paddingRight=V.paddingX),V.paddingY&&(T.style.paddingTop=V.paddingY,T.style.paddingBottom=V.paddingY),re.appendChild(T);let vt=(tt=V.tooltipText)!=null?tt:"Start voice recognition";if(((Ue=V.showTooltip)!=null?Ue:!1)&&vt){let ct=c("div","tvw-send-button-tooltip");ct.textContent=vt,re.appendChild(ct)}}u.addEventListener("click",Ee=>{Ee.target!==R&&Ee.target!==z&&Ee.target!==T&&Ee.target!==re&&h.focus()}),u.append(h),re&&u.append(re),u.append(z);let U=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),ne=(N=e==null?void 0:e.statusIndicator)!=null?N:{},ue=(lt=ne.visible)!=null?lt:!0;return U.style.display=ue?"":"none",U.textContent=(Xe=ne.idleText)!=null?Xe:"Online",r.append(t,u,U),{footer:r,suggestions:t,composerForm:u,textarea:h,sendButton:R,sendButtonWrapper:z,micButton:T,micButtonWrapper:re,statusText:U}};var co=n=>{var u,h,d,E,f;if(!((h=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?h:!0)){let C=c("div","tvw-relative tvw-w-full tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),y=c("div","tvw-relative tvw-w-full tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0");return C.appendChild(y),{wrapper:C,panel:y}}let r=(d=n==null?void 0:n.launcher)!=null?d:{},t=r.position&&It[r.position]?It[r.position]:It["bottom-right"],o=c("div",`tvw-fixed ${t} tvw-z-50 tvw-transition`),s=c("div","tvw-relative tvw-min-h-[320px]"),i=(f=(E=n==null?void 0:n.launcher)==null?void 0:E.width)!=null?f:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,o.appendChild(s),{wrapper:o,panel:s}},uo=(n,e=!0)=>{var E,f,C,y,j;let r=c("div","tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-shadow-2xl tvw-border tvw-border-cw-border"),t=(E=n==null?void 0:n.layout)==null?void 0:E.header,o=t?Sn(n,t,{showClose:e}):Dt({config:n,showClose:e}),s=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");s.id="vanilla-agent-scroll-container";let i=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(C=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?C:"Hello \u{1F44B}";let u=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(j=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeSubtitle)!=null?j:"Ask anything about your account or products.",i.append(l,u);let h=c("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,h);let d=en({config:n});return Qt(r,o,n),r.append(s,d.footer),{container:r,body:s,messagesWrapper:h,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:l,introSubtitle:u,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:d.footer}};var dn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let 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 t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(r),n.appendChild(t),n.appendChild(o),n},Io=(n,e)=>{let r=c("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=c("img");o.src=t,o.alt=e==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=e==="user"?"U":"A",r.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},po=(n,e)=>{let r=c("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?r.textContent=e.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},$o=(n,e="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="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");break}return r},tn=(n,e,r)=>{var F,m,S,I,A;let t=r!=null?r:{},o=(F=t.layout)!=null?F:"bubble",s=t.avatar,i=t.timestamp,l=(m=s==null?void 0:s.show)!=null?m:!1,u=(S=i==null?void 0:i.show)!=null?S:!1,h=(I=s==null?void 0:s.position)!=null?I:"left",d=(A=i==null?void 0:i.position)!=null?A:"below",E=$o(n.role,o),f=c("div",E.join(" ")),C=document.createElement("div");if(C.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),u&&d==="inline"&&n.createdAt){let z=po(n,i);z.classList.add("tvw-ml-2","tvw-inline"),C.appendChild(z)}if(f.appendChild(C),u&&d==="below"&&n.createdAt){let z=po(n,i);z.classList.add("tvw-mt-1"),f.appendChild(z)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let z=dn();f.appendChild(z)}if(!l||n.role==="system")return f;let y=c("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),j=Io(s,n.role);return h==="right"||h==="left"&&n.role==="user"?y.append(f,j):y.append(j,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},Po=(n,e,r)=>{let t=r!=null?r:{};return n.role==="user"&&t.renderUserMessage?t.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&t.renderAssistantMessage?t.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):tn(n,e,r)};var An=new Set,Tn=n=>{let e=n.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(!e)return r;let t=An.has(n.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",t?"true":"false");let s=c("div","tvw-flex tvw-flex-col tvw-text-left"),i=c("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=c("span","tvw-text-xs tvw-text-cw-primary");l.textContent=so(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let u=c("div","tvw-flex tvw-items-center"),d=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);d?u.appendChild(d):u.textContent=t?"Hide":"Show";let E=c("div","tvw-flex tvw-items-center tvw-ml-auto");E.append(u),o.append(s,E);let f=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let C=e.chunks.join(""),y=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");y.textContent=C||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(y);let j=()=>{o.setAttribute("aria-expanded",t?"true":"false"),u.innerHTML="";let S=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);S?u.appendChild(S):u.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},F=()=>{t=!t,t?An.add(n.id):An.delete(n.id),j()};return o.addEventListener("pointerdown",m=>{m.preventDefault(),F()}),o.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),F())}),j(),r.append(o,f),r};var En=new Set,Wn=(n,e)=>{var F;let r=n.toolCall,t=(F=e==null?void 0:e.toolCall)!=null?F:{},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(t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=En.has(n.id),i=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");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=c("div","tvw-flex tvw-flex-col tvw-text-left"),u=c("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(u.style.color=t.headerTextColor),u.textContent=oo(r),l.appendChild(u);let h=c("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",E=ge(s?"chevron-up":"chevron-down",16,d,2);E?h.appendChild(E):h.textContent=s?"Hide":"Show";let f=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(h),i.append(l,f);let C=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(C.style.display=s?"":"none",t.contentBackgroundColor&&(C.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(C.style.color=t.contentTextColor),t.contentPaddingX&&(C.style.paddingLeft=t.contentPaddingX,C.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(C.style.paddingTop=t.contentPaddingY,C.style.paddingBottom=t.contentPaddingY),r.name){let m=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?m.style.color=t.contentTextColor:t.headerTextColor&&(m.style.color=t.headerTextColor),m.textContent=r.name,C.appendChild(m)}if(r.args!==void 0){let m=c("div","tvw-space-y-1"),S=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Arguments";let I=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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=fn(r.args),m.append(S,I),C.appendChild(m)}if(r.chunks&&r.chunks.length){let m=c("div","tvw-space-y-1"),S=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Activity";let I=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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=r.chunks.join(`
15
+ `),m.append(S,I),C.appendChild(m)}if(r.status==="complete"&&r.result!==void 0){let m=c("div","tvw-space-y-1"),S=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Result";let I=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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=fn(r.result),m.append(S,I),C.appendChild(m)}if(r.status==="complete"&&typeof r.duration=="number"){let m=c("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${r.duration}ms`,C.appendChild(m)}let y=()=>{i.setAttribute("aria-expanded",s?"true":"false"),h.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",S=ge(s?"chevron-up":"chevron-down",16,m,2);S?h.appendChild(S):h.textContent=s?"Hide":"Show",C.style.display=s?"":"none"},j=()=>{s=!s,s?En.add(n.id):En.delete(n.id),y()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),j()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),j())}),y(),o.append(i,C),o};var go=n=>{let e=[];return{buttons:e,render:(t,o,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(C=>C.role==="user"))return;let d=document.createDocumentFragment(),E=o?o.isStreaming():!1,f=C=>{switch(C){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(C=>{let y=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");y.type="button",y.textContent=C,y.disabled=E,l!=null&&l.fontFamily&&(y.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(y.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(y.style.paddingLeft=l.paddingX,y.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(y.style.paddingTop=l.paddingY,y.style.paddingBottom=l.paddingY),y.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(C))}),d.appendChild(y),e.push(y)}),n.appendChild(d)}}};var ho={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"}},Mn=(n,e,r,t)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,j,F;if(s.dataset.enhanced==="true")return;let i=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let l=(j=ho[i])!=null?j:ho.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=c("div","tvw-space-y-1"),h=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(h.textContent=l.title,u.appendChild(h),l.description){let m=c("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,u.appendChild(m)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var R,V;let S=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${e.id}-${i}-${m.name}`;let I=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=m.label,S.appendChild(I);let A=(R=m.type)!=null?R:"text",z;A==="textarea"?(z=document.createElement("textarea"),z.rows=3):(z=document.createElement("input"),z.type=A),z.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",z.id=`${e.id}-${i}-${m.name}`,z.name=m.name,z.placeholder=(V=m.placeholder)!=null?V:"",m.required&&(z.required=!0),S.appendChild(z),d.appendChild(S)});let E=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),C=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");C.type="submit",C.textContent=(F=l.submitLabel)!=null?F:"Submit",E.appendChild(f),E.appendChild(C),d.appendChild(E),s.replaceChildren(u,d),d.addEventListener("submit",async m=>{var z,R;m.preventDefault();let S=(z=r.formEndpoint)!=null?z:"/form",I=new FormData(d),A={};I.forEach((V,te)=>{A[te]=V}),A.type=i,C.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let te=await V.json();f.textContent=(R=te.message)!=null?R:"Thanks! We'll be in touch soon.",te.success&&te.nextPrompt&&await t.sendMessage(String(te.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{C.disabled=!1}})})};var Ln=class{constructor(){this.plugins=new Map}register(e){var r;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(r=e.onRegister)==null||r.call(e)}unregister(e){var t;let r=this.plugins.get(e);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let r=this.getAll();if(!e||e.length===0)return r;let t=new Set(e.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,u;return((l=i.priority)!=null?l:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},cn=new Ln;var Oe={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,placement:"inline",iconName:"refresh-cw",size:"32px",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?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},debug:!1};function Bn(n){var e,r,t,o,s,i,l,u,h,d,E,f,C,y,j,F,m;return n?{...Oe,...n,theme:{...Oe.theme,...n.theme},launcher:{...Oe.launcher,...n.launcher,clearChat:{...(e=Oe.launcher)==null?void 0:e.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...Oe.copy,...n.copy},sendButton:{...Oe.sendButton,...n.sendButton},statusIndicator:{...Oe.statusIndicator,...n.statusIndicator},voiceRecognition:{...Oe.voiceRecognition,...n.voiceRecognition},features:{...Oe.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Oe.suggestionChips,suggestionChipsConfig:{...Oe.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Oe.layout,...n.layout,header:{...(o=Oe.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Oe.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(h=(u=Oe.layout)==null?void 0:u.messages)==null?void 0:h.avatar,...(E=(d=n.layout)==null?void 0:d.messages)==null?void 0:E.avatar},timestamp:{...(C=(f=Oe.layout)==null?void 0:f.messages)==null?void 0:C.timestamp,...(j=(y=n.layout)==null?void 0:y.messages)==null?void 0:j.timestamp}},slots:{...(F=Oe.layout)==null?void 0:F.slots,...(m=n.layout)==null?void 0:m.slots}}}:Oe}var mo=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:e,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(l=>{try{l(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Oo=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},No=n=>{let e=n.trim(),r=e.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<e.length;o+=1){let s=e[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(r,o+1)}return null},un=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Oo(n),r=No(e);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},Hn=n=>typeof n=="string"?n:n==null?"":String(n),Ut={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Hn(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,t=Hn(r.element);if(t&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Hn(r.text)}}},fo=n=>Array.isArray(n)?n.map(e=>String(e)):[],pn=n=>{let e=new Set(fo(n.getMetadata().processedActionMessageIds)),r=()=>{e=new Set(fo(n.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((h,d)=>h||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let u={action:l,message:s.message};n.emit("action:detected",u);for(let h of n.handlers)if(h)try{let d=h(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let E=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:E}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:r}};var Fo=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},Do=n=>n.map(e=>({...e,streaming:!1})),kn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?Fo(r.getItem(n)):null},save:r=>{let t=e();if(t)try{let o={...r,messages:r.messages?Do(r.messages):void 0};t.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=e();if(r)try{r.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Rn=class{constructor(){this.components=new Map}register(e,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,r)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([r,t])=>{this.register(r,t)})}},nn=new Rn;import{parse as jo,STR as _o,OBJ as qo}from"partial-json";function Uo(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function zo(n,e){if(!Uo(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:e}}function In(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=e)return n;try{let o=jo(r,_o|qo),s=zo(o,r);s&&(n=s)}catch{}return e=r.length,n},reset:()=>{n=null,e=0}}}function Yo(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function $n(n,e){let{config:r,message:t,onPropsUpdate:o}=e,s=nn.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:l=>{o&&o(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Jo(){let n=In();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Pn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function On(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var zt="vanilla-agent-chat-history",Ko=30*1e3,Nn=n=>!n||typeof n!="object"?{}:{...n},wo=n=>n.map(e=>({...e,streaming:!1})),yo=(n,e)=>r=>{var s,i,l;let t=(s=r.text)!=null?s:"",o=(i=r.message.rawContent)!=null?i:null;if(e){let u=e.process({text:t,raw:o!=null?o:t,message:r.message,streaming:r.streaming});u!==null&&(t=u.text,u.persist||(r.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...r,text:t,raw:(l=o!=null?o:r.text)!=null?l:""}):mn(t)},Fn=(n,e,r)=>{var Se,oe,we,Be,$e,je,Bt,jn,_n,qn,Un,zn,Yn,Jn;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Bn(e);xn(n,t);let o=cn.getForInstance(t.plugins);t.components&&nn.registerAll(t.components);let s=mo(),i=(Se=t.storageAdapter)!=null?Se:kn(),l={},u=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")u=a;else if(a){let p=a;p.metadata&&(l=Nn(p.metadata)),(oe=p.messages)!=null&&oe.length&&(t={...t,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let h=()=>l,d=a=>{var M;l=(M=a({...l}))!=null?M:{},Lt()},E=t.actionParsers&&t.actionParsers.length?t.actionParsers:[un],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Ut.message,Ut.messageAndClick],C=pn({parsers:E,handlers:f,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let y=(Be=(we=t.launcher)==null?void 0:we.enabled)!=null?Be:!0,j=(je=($e=t.launcher)==null?void 0:$e.autoExpand)!=null?je:!1,F=j,m=y,S=y?j:!0,I=yo(t,C),A=(jn=(Bt=t.features)==null?void 0:Bt.showReasoning)!=null?jn:!0,z=(qn=(_n=t.features)==null?void 0:_n.showToolCalls)!=null?qn:!0,R=(Un=t.statusIndicator)!=null?Un:{},V=a=>{var p,M,P,H;return a==="idle"?(p=R.idleText)!=null?p:Ye.idle:a==="connecting"?(M=R.connectingText)!=null?M:Ye.connecting:a==="connected"?(P=R.connectedText)!=null?P:Ye.connected:a==="error"?(H=R.errorText)!=null?H:Ye.error:Ye[a]},{wrapper:te,panel:T}=co(t),re=uo(t,y),{container:Y,body:U,messagesWrapper:ne,suggestions:ue,textarea:se,sendButton:$,sendButtonWrapper:qe,composerForm:Je,statusText:et,introTitle:wt,introSubtitle:yt,closeButton:O,iconHolder:de,headerTitle:pt,headerSubtitle:gt,header:Ke,footer:rt}=re,B=re.micButton,ke=re.micButtonWrapper,it=o.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let p=Dt({config:t,showClose:y});return Qt(Y,p,t),p.header},onClose:()=>st(!1,"user")});if(a){let p=Y.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Ke=a)}}let at=o.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>en({config:t}).footer,onSubmit:p=>{N&&!N.isStreaming()&&N.sendMessage(p)},disabled:!1});a&&(rt.replaceWith(a),rt=a)}(()=>{var P,H;let a=(H=(P=t.layout)==null?void 0:P.slots)!=null?H:{},p=b=>{switch(b){case"body-top":return Y.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return ne;case"footer-top":return ue;case"composer":return Je;case"footer-bottom":return et;default:return null}},M=(b,x)=>{var K;switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")Ke.insertBefore(x,Ke.firstChild);else if(b==="header-right")Ke.appendChild(x);else{let _=Ke.querySelector(".tvw-flex-col");_?(K=_.parentNode)==null||K.insertBefore(x,_.nextSibling):Ke.appendChild(x)}break;case"body-top":let ae=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ae?ae.replaceWith(x):U.insertBefore(x,U.firstChild);break;case"body-bottom":U.appendChild(x);break;case"footer-top":ue.replaceWith(x);break;case"footer-bottom":et.replaceWith(x);break;default:break}};for(let[b,x]of Object.entries(a))if(x)try{let K=x({config:t,defaultContent:()=>p(b)});K&&M(b,K)}catch(K){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,K)}})(),T.appendChild(Y),n.appendChild(te);let ht=()=>{var q,ee,me,_e,He,ot,pe,Tt,Ht,kt,Et,Nt;let a=(ee=(q=t.launcher)==null?void 0:q.sidebarMode)!=null?ee:!1,p=a||((_e=(me=t.launcher)==null?void 0:me.fullHeight)!=null?_e:!1),M=(He=t.theme)!=null?He:{},P=(pe=(ot=t.launcher)==null?void 0:ot.position)!=null?pe:"bottom-left",H=P==="bottom-left"||P==="top-left",b=a?"none":"1px solid var(--tvw-cw-border)",x=a?H?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",K=a?"0":"16px",ae=(Tt=M.panelBorder)!=null?Tt:b,_=(Ht=M.panelShadow)!=null?Ht:x,k=(kt=M.panelBorderRadius)!=null?kt:K;if(Y.style.border=ae,Y.style.boxShadow=_,Y.style.borderRadius=k,p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.height="100%",te.style.overflow="hidden",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1 1 0%",T.style.minHeight="0",T.style.maxHeight="100%",T.style.height="100%",T.style.overflow="hidden",Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",rt.style.flexShrink="0"),a){let Ft=(Nt=(Et=t.launcher)==null?void 0:Et.sidebarWidth)!=null?Nt:"420px";te.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),te.style.cssText=`
16
+ position: fixed !important;
17
+ top: 0 !important;
18
+ bottom: 0 !important;
19
+ width: ${Ft} !important;
20
+ height: 100vh !important;
21
+ max-height: 100vh !important;
22
+ margin: 0 !important;
23
+ padding: 0 !important;
24
+ display: flex !important;
25
+ flex-direction: column !important;
26
+ ${H?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
27
+ `,T.style.cssText=`
28
+ position: relative !important;
29
+ display: flex !important;
30
+ flex-direction: column !important;
31
+ flex: 1 1 0% !important;
32
+ width: 100% !important;
33
+ max-width: 100% !important;
34
+ height: 100% !important;
35
+ min-height: 0 !important;
36
+ margin: 0 !important;
37
+ padding: 0 !important;
38
+ `,T.style.setProperty("width","100%","important"),T.style.setProperty("max-width","100%","important"),Y.style.cssText=`
39
+ display: flex !important;
40
+ flex-direction: column !important;
41
+ flex: 1 1 0% !important;
42
+ width: 100% !important;
43
+ height: 100% !important;
44
+ min-height: 0 !important;
45
+ max-height: 100% !important;
46
+ overflow: hidden !important;
47
+ border-radius: ${k} !important;
48
+ border: ${ae} !important;
49
+ box-shadow: ${_} !important;
50
+ `,rt.style.cssText=`
51
+ flex-shrink: 0 !important;
52
+ border-top: none !important;
53
+ padding: 8px 16px 12px 16px !important;
54
+ `}};ht();let Pe=[],tt=go(ue),Ue=null,N,lt=!1,Xe=!0,Ee=0,Fe=0,J=null,ye=!1,Re=0,ze=!1,nt=125,vt=2e3,Wt=5,ct=50,bt=new Map,ie={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},$t=(Yn=(zn=t.voiceRecognition)==null?void 0:zn.autoResume)!=null?Yn:!1,Mt=a=>{s.emit("voice:state",{active:ie.active,source:a,timestamp:Date.now()})},he=()=>{d(a=>({...a,voiceState:{active:ie.active,timestamp:Date.now(),manuallyDeactivated:ie.manuallyDeactivated}}))},mt=()=>{var P,H;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let a=Nn(l.voiceState),p=!!a.active,M=Number((H=a.timestamp)!=null?H:0);ie.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-M<Ko&&setTimeout(()=>{ie.active||(ie.manuallyDeactivated=!1,Me("restore"))},1e3)},xt=()=>N?wo(N.getMessages()).filter(a=>!a.__skipPersist):[];function Lt(a){if(!(i!=null&&i.save))return;let M={messages:a?wo(a):N?xt():[],metadata:l};try{let P=i.save(M);P instanceof Promise&&P.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)})}catch(P){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)}}let ft=(a=!1)=>{if(!Xe)return;let p=Date.now();ye&&p<Re&&!a||(ye&&p>=Re&&(ye=!1),!(!a&&!lt)&&(p-Fe<nt||(Fe=p,J&&cancelAnimationFrame(J),J=requestAnimationFrame(()=>{ye||!Xe||(ze=!0,U.scrollTop=U.scrollHeight,Ee=U.scrollTop,requestAnimationFrame(()=>{ze=!1}),J=null)}))))},At=null,sn=()=>te.querySelector("#vanilla-agent-scroll-container")||U,on=(a,p=500)=>{let M=a.scrollTop,P=a.clientHeight,H=a.scrollHeight,b=H-M;if(M+P>=H-2||Math.abs(b)<5)return;At!==null&&(cancelAnimationFrame(At),At=null);let K=performance.now(),ae=k=>1-Math.pow(1-k,3),_=k=>{let q=a.scrollHeight;q!==H&&(H=q,b=H-M);let ee=k-K,me=Math.min(ee/p,1),_e=ae(me),He=M+b*_e;a.scrollTop=He,me<1?At=requestAnimationFrame(_):(a.scrollTop=a.scrollHeight,At=null)};At=requestAnimationFrame(_)},rn=a=>{let p=new Map;a.forEach(M=>{let P=bt.get(M.id);p.set(M.id,{streaming:M.streaming,role:M.role}),!P&&M.role==="assistant"&&s.emit("assistant:message",M),M.role==="assistant"&&(P!=null&&P.streaming)&&M.streaming===!1&&s.emit("assistant:complete",M)}),bt.clear(),p.forEach((M,P)=>{bt.set(P,M)})},Pt=(a,p,M)=>{a.innerHTML="";let P=document.createDocumentFragment();p.forEach(b=>{var k,q;let x=null,K=o.find(ee=>!!(b.variant==="reasoning"&&ee.renderReasoning||b.variant==="tool"&&ee.renderToolCall||!b.variant&&ee.renderMessage)),ae=(k=t.layout)==null?void 0:k.messages;if(K)if(b.variant==="reasoning"&&b.reasoning&&K.renderReasoning){if(!A)return;x=K.renderReasoning({message:b,defaultRenderer:()=>Tn(b),config:t})}else if(b.variant==="tool"&&b.toolCall&&K.renderToolCall){if(!z)return;x=K.renderToolCall({message:b,defaultRenderer:()=>Wn(b,t),config:t})}else K.renderMessage&&(x=K.renderMessage({message:b,defaultRenderer:()=>{let ee=tn(b,M,ae);return b.role!=="user"&&Mn(ee,b,t,N),ee},config:t}));if(!x&&b.role==="assistant"&&!b.variant&&t.enableComponentStreaming!==!1&&Pn(b)){let me=On(b);if(me){let _e=$n(me,{config:t,message:b,transform:M});if(_e){let He=document.createElement("div");if(He.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),He.setAttribute("data-message-id",b.id),b.content&&b.content.trim()){let ot=document.createElement("div");ot.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ot.innerHTML=M({text:b.content,message:b,streaming:!!b.streaming,raw:b.rawContent}),He.appendChild(ot)}He.appendChild(_e),x=He}}}if(!x)if(b.variant==="reasoning"&&b.reasoning){if(!A)return;x=Tn(b)}else if(b.variant==="tool"&&b.toolCall){if(!z)return;x=Wn(b,t)}else{let ee=(q=t.layout)==null?void 0:q.messages;ee!=null&&ee.renderUserMessage&&b.role==="user"?x=ee.renderUserMessage({message:b,config:t,streaming:!!b.streaming}):ee!=null&&ee.renderAssistantMessage&&b.role==="assistant"?x=ee.renderAssistantMessage({message:b,config:t,streaming:!!b.streaming}):x=tn(b,M,ee),b.role!=="user"&&x&&Mn(x,b,t,N)}let _=document.createElement("div");_.className="tvw-flex",b.role==="user"&&_.classList.add("tvw-justify-end"),_.appendChild(x),P.appendChild(_)});let H=p.some(b=>b.role==="assistant"&&b.streaming);if(lt&&p.some(b=>b.role==="user")&&!H){let b=dn(),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(b);let K=document.createElement("div");K.className="tvw-flex",K.appendChild(x),P.appendChild(K)}a.appendChild(P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let b=sn();on(b)})})},Ot=()=>{y&&(S?(te.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),T.classList.remove("tvw-scale-95","tvw-opacity-0"),T.classList.add("tvw-scale-100","tvw-opacity-100"),w?w.element.style.display="none":g&&(g.style.display="none")):(te.classList.add("tvw-pointer-events-none","tvw-opacity-0"),T.classList.remove("tvw-scale-100","tvw-opacity-100"),T.classList.add("tvw-scale-95","tvw-opacity-0"),w?w.element.style.display="":g&&(g.style.display="")))},st=(a,p="user")=>{if(!y||S===a)return;let M=S;S=a,Ot(),S&&(D(),ft(!0));let P={open:S,source:p,timestamp:Date.now()};S&&!M?s.emit("widget:opened",P):!S&&M&&s.emit("widget:closed",P),s.emit("widget:state",{open:S,launcherEnabled:y,voiceActive:ie.active,streaming:N.isStreaming()})},jt=a=>{se.disabled=a,$.disabled=a,B&&(B.disabled=a),tt.buttons.forEach(p=>{p.disabled=a})},Yt=()=>{var H,b,x,K,ae,_,k,q,ee,me,_e,He,ot,pe;wt.textContent=(b=(H=t.copy)==null?void 0:H.welcomeTitle)!=null?b:"Hello \u{1F44B}",yt.textContent=(K=(x=t.copy)==null?void 0:x.welcomeSubtitle)!=null?K:"Ask anything about your account or products.",se.placeholder=(_=(ae=t.copy)==null?void 0:ae.inputPlaceholder)!=null?_:"How can I help...",((q=(k=t.sendButton)==null?void 0:k.useIcon)!=null?q:!1)||($.textContent=(me=(ee=t.copy)==null?void 0:ee.sendButtonLabel)!=null?me:"Send");let p=(He=(_e=t.theme)==null?void 0:_e.inputFontFamily)!=null?He:"sans-serif",M=(pe=(ot=t.theme)==null?void 0:ot.inputFontWeight)!=null?pe:"400",P=Tt=>{switch(Tt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=P(p),se.style.fontWeight=M};N=new Gt(t,{onMessagesChanged(a){Pt(ne,a,I),N&&(a.some(P=>P.role==="user")?tt.render([],N,se,a):tt.render(t.suggestionChips,N,se,a,t.suggestionChipsConfig)),ft(!lt),rn(a);let p=[...a].reverse().find(M=>M.role==="user");ie.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Lt(a)},onStatusChanged(a){var P;let p=(P=t.statusIndicator)!=null?P:{},M=H=>{var b,x,K,ae;return H==="idle"?(b=p.idleText)!=null?b:Ye.idle:H==="connecting"?(x=p.connectingText)!=null?x:Ye.connecting:H==="connected"?(K=p.connectedText)!=null?K:Ye.connected:H==="error"?(ae=p.errorText)!=null?ae:Ye.error:Ye[H]};et.textContent=M(a)},onStreamingChanged(a){lt=a,jt(a),N&&Pt(ne,N.getMessages(),I),a||ft(!0)}}),u&&u.then(a=>{var p;a&&(a.metadata&&(l=Nn(a.metadata),C.syncFromMetadata()),(p=a.messages)!=null&&p.length&&N.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let Jt=a=>{a.preventDefault();let p=se.value.trim();p&&(se.value="",N.sendMessage(p))},Kt=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),$.click())},Ve=null,v=!1,G=null,Q=null,We=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Me=(a="user")=>{var b,x,K,ae;if(v||N.isStreaming())return;let p=We();if(!p)return;Ve=new p;let P=(x=((b=t.voiceRecognition)!=null?b:{}).pauseDuration)!=null?x:2e3;Ve.continuous=!0,Ve.interimResults=!0,Ve.lang="en-US";let H=se.value;Ve.onresult=_=>{let k="",q="";for(let me=0;me<_.results.length;me++){let _e=_.results[me],He=_e[0].transcript;_e.isFinal?k+=He+" ":q=He}let ee=H+k+q;se.value=ee,G&&clearTimeout(G),(k||q)&&(G=window.setTimeout(()=>{let me=se.value.trim();me&&Ve&&v&&(ve(),se.value="",N.sendMessage(me,{viaVoice:!0}))},P))},Ve.onerror=_=>{_.error!=="no-speech"&&ve()},Ve.onend=()=>{if(v){let _=se.value.trim();_&&_!==H.trim()&&(se.value="",N.sendMessage(_,{viaVoice:!0})),ve()}};try{if(Ve.start(),v=!0,ie.active=!0,a!=="system"&&(ie.manuallyDeactivated=!1),Mt(a),he(),B){Q={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor};let _=(K=t.voiceRecognition)!=null?K:{},k=(ae=_.recordingBackgroundColor)!=null?ae:"#ef4444",q=_.recordingIconColor,ee=_.recordingBorderColor;if(B.classList.add("tvw-voice-recording"),B.style.backgroundColor=k,q){B.style.color=q;let me=B.querySelector("svg");me&&me.setAttribute("stroke",q)}ee&&(B.style.borderColor=ee),B.setAttribute("aria-label","Stop voice recognition")}}catch{ve("system")}},ve=(a="user")=>{if(v){if(v=!1,G&&(clearTimeout(G),G=null),Ve){try{Ve.stop()}catch{}Ve=null}if(ie.active=!1,Mt(a),he(),B){if(B.classList.remove("tvw-voice-recording"),Q){B.style.backgroundColor=Q.backgroundColor,B.style.color=Q.color,B.style.borderColor=Q.borderColor;let p=B.querySelector("svg");p&&p.setAttribute("stroke",Q.color||"currentColor"),Q=null}B.setAttribute("aria-label","Start voice recognition")}}},Le=(a,p)=>{var He,ot,pe,Tt,Ht,kt,Et;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=c("div","tvw-send-button-wrapper"),H=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");H.type="button",H.setAttribute("aria-label","Start voice recognition");let b=(He=a==null?void 0:a.iconName)!=null?He:"mic",x=(ot=p==null?void 0:p.size)!=null?ot:"40px",K=(pe=a==null?void 0:a.iconSize)!=null?pe:x,ae=parseFloat(K)||24,_=(Tt=a==null?void 0:a.backgroundColor)!=null?Tt:p==null?void 0:p.backgroundColor,k=(Ht=a==null?void 0:a.iconColor)!=null?Ht:p==null?void 0:p.textColor;H.style.width=K,H.style.height=K,H.style.minWidth=K,H.style.minHeight=K,H.style.fontSize="18px",H.style.lineHeight="1";let q=k||"currentColor",ee=ge(b,ae,q,1.5);ee?(H.appendChild(ee),H.style.color=q):(H.textContent="\u{1F3A4}",H.style.color=q),_?H.style.backgroundColor=_:H.classList.add("tvw-bg-cw-primary"),k?H.style.color=k:!k&&!(p!=null&&p.textColor)&&H.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(H.style.borderWidth=a.borderWidth,H.style.borderStyle="solid"),a!=null&&a.borderColor&&(H.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(H.style.paddingLeft=a.paddingX,H.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(H.style.paddingTop=a.paddingY,H.style.paddingBottom=a.paddingY),P.appendChild(H);let me=(kt=a==null?void 0:a.tooltipText)!=null?kt:"Start voice recognition";if(((Et=a==null?void 0:a.showTooltip)!=null?Et:!1)&&me){let Nt=c("div","tvw-send-button-tooltip");Nt.textContent=me,P.appendChild(Nt)}return{micButton:H,micButtonWrapper:P}},W=()=>{if(v){let a=se.value.trim();ie.manuallyDeactivated=!0,he(),ve("user"),a&&(se.value="",N.sendMessage(a))}else ie.manuallyDeactivated=!1,he(),Me("user")};B&&(B.addEventListener("click",W),Pe.push(()=>{ve("system"),B&&B.removeEventListener("click",W)}));let ut=s.on("assistant:complete",()=>{$t&&(ie.active||ie.manuallyDeactivated||$t==="assistant"&&!ie.lastUserMessageWasVoice||setTimeout(()=>{!ie.active&&!ie.manuallyDeactivated&&Me("auto")},600))});Pe.push(ut);let X=()=>{st(!S,"user")},w=null,g=null;if(y){let a=o.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:t,defaultRenderer:()=>Zt(t,X).element,onToggle:X});p&&(g=p)}g||(w=Zt(t,X))}w?n.appendChild(w.element):g&&n.appendChild(g),Ot(),tt.render(t.suggestionChips,N,se,void 0,t.suggestionChipsConfig),Yt(),jt(N.isStreaming()),ft(!0),mt();let D=()=>{var M,P,H,b,x,K;let a=(P=(M=t.launcher)==null?void 0:M.sidebarMode)!=null?P:!1,p=a||((b=(H=t.launcher)==null?void 0:H.fullHeight)!=null?b:!1);if(!y){T.style.height="",T.style.width="";return}if(!a){let ae=(K=(x=t==null?void 0:t.launcher)==null?void 0:x.width)!=null?K:t==null?void 0:t.launcherWidth,_=ae!=null?ae:"min(400px, calc(100vw - 24px))";T.style.width=_,T.style.maxWidth=_}if(!p){let ae=window.innerHeight,k=Math.max(200,ae-64),q=Math.min(640,k);T.style.height=`${q}px`}};D(),window.addEventListener("resize",D),Pe.push(()=>window.removeEventListener("resize",D)),Ee=U.scrollTop;let be=()=>{let a=U.scrollTop,p=U.scrollHeight,M=U.clientHeight,P=p-a-M,H=Math.abs(a-Ee);if(Ee=a,!ze&&!(H<=Wt)){if(!Xe&&P<ct){ye=!1,Xe=!0;return}Xe&&P>ct&&(ye=!0,Re=Date.now()+vt,Xe=!1)}};U.addEventListener("scroll",be,{passive:!0}),Pe.push(()=>U.removeEventListener("scroll",be)),Pe.push(()=>{J&&cancelAnimationFrame(J)});let xe=()=>{O&&(Ue&&(O.removeEventListener("click",Ue),Ue=null),y?(O.style.display="",Ue=()=>{S=!1,Ot()},O.addEventListener("click",Ue)):O.style.display="none")};xe(),(()=>{let{clearChatButton:a}=re;a&&a.addEventListener("click",()=>{N.clearMessages();try{localStorage.removeItem(zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zt}`)}catch(M){console.error("[AgentWidget] Failed to clear default localStorage:",M)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(M){console.error("[AgentWidget] Failed to clear custom localStorage:",M)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let M=i.clear();M instanceof Promise&&M.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",P)})}catch(M){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",M)}l={},C.syncFromMetadata()})})(),Je.addEventListener("submit",Jt),se.addEventListener("keydown",Kt),Pe.push(()=>{Je.removeEventListener("submit",Jt),se.removeEventListener("keydown",Kt)}),Pe.push(()=>{N.cancel()}),w?Pe.push(()=>{w==null||w.destroy()}):g&&Pe.push(()=>{g==null||g.remove()});let Ce={update(a){var Kn,Xn,Vn,Gn,Zn,Qn,es,ts,ns,ss,os,rs,is,as,ls,ds,cs,us,ps,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,Hs,ks,Rs,Is,$s,Ps,Os,Ns,Fs,Ds,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs;let p=t.toolCall;t={...t,...a},xn(n,t),ht();let M=cn.getForInstance(t.plugins);if(o.length=0,o.push(...M),y=(Xn=(Kn=t.launcher)==null?void 0:Kn.enabled)!=null?Xn:!0,j=(Gn=(Vn=t.launcher)==null?void 0:Vn.autoExpand)!=null?Gn:!1,A=(Qn=(Zn=t.features)==null?void 0:Zn.showReasoning)!=null?Qn:!0,z=(ts=(es=t.features)==null?void 0:es.showToolCalls)!=null?ts:!0,((ns=t.launcher)==null?void 0:ns.enabled)===!1&&w&&(w.destroy(),w=null),((ss=t.launcher)==null?void 0:ss.enabled)===!1&&g&&(g.remove(),g=null),((os=t.launcher)==null?void 0:os.enabled)!==!1&&!w&&!g){let L=o.find(ce=>ce.renderLauncher);if(L!=null&&L.renderLauncher){let ce=L.renderLauncher({config:t,defaultRenderer:()=>Zt(t,X).element,onToggle:X});ce&&(g=ce,n.appendChild(g))}g||(w=Zt(t,X),n.appendChild(w.element))}w&&w.update(t),pt&&((rs=t.launcher)==null?void 0:rs.title)!==void 0&&(pt.textContent=t.launcher.title),gt&&((is=t.launcher)==null?void 0:is.subtitle)!==void 0&&(gt.textContent=t.launcher.subtitle),y!==m?y?st(j,"auto"):(S=!0,Ot()):j!==F&&st(j,"auto"),F=j,m=y,D(),xe(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&N&&Pt(ne,N.getMessages(),I);let x=(as=t.launcher)!=null?as:{},K=(ls=x.headerIconHidden)!=null?ls:!1,ae=x.headerIconName,_=(ds=x.headerIconSize)!=null?ds:"48px";if(de){let L=Y.querySelector(".tvw-border-b-cw-divider"),ce=L==null?void 0:L.querySelector(".tvw-flex-col");if(K)de.style.display="none",L&&ce&&!L.contains(ce)&&L.insertBefore(ce,L.firstChild);else{if(de.style.display="",de.style.height=_,de.style.width=_,L&&ce&&(L.contains(de)?de.nextSibling!==ce&&(de.remove(),L.insertBefore(de,ce)):L.insertBefore(de,ce)),ae){let Te=parseFloat(_)||24,fe=ge(ae,Te*.6,"#ffffff",2);fe?de.replaceChildren(fe):de.textContent=(cs=x.agentIconText)!=null?cs:"\u{1F4AC}"}else if(x.iconUrl){let Te=de.querySelector("img");if(Te)Te.src=x.iconUrl,Te.style.height=_,Te.style.width=_;else{let fe=document.createElement("img");fe.src=x.iconUrl,fe.alt="",fe.className="tvw-rounded-xl tvw-object-cover",fe.style.height=_,fe.style.width=_,de.replaceChildren(fe)}}else{let Te=de.querySelector("svg"),fe=de.querySelector("img");(Te||fe)&&de.replaceChildren(),de.textContent=(us=x.agentIconText)!=null?us:"\u{1F4AC}"}let Z=de.querySelector("img");Z&&(Z.style.height=_,Z.style.width=_)}}if(O){let L=(ps=x.closeButtonSize)!=null?ps:"32px",ce=(gs=x.closeButtonPlacement)!=null?gs:"inline";O.style.height=L,O.style.width=L;let{closeButtonWrapper:Z}=re,Te=ce==="top-right",fe=Z==null?void 0:Z.classList.contains("tvw-absolute");if(Z&&Te!==fe)if(Z.remove(),Te)Z.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(Z);else{let le=(ms=(hs=x.clearChat)==null?void 0:hs.placement)!=null?ms:"inline",Ze=(ws=(fs=x.clearChat)==null?void 0:fs.enabled)!=null?ws:!0;Z.className=Ze&&le==="inline"?"":"tvw-ml-auto";let Qe=Y.querySelector(".tvw-border-b-cw-divider");Qe&&Qe.appendChild(Z)}if(x.closeButtonColor?(O.style.color=x.closeButtonColor,O.classList.remove("tvw-text-cw-muted")):(O.style.color="",O.classList.add("tvw-text-cw-muted")),x.closeButtonBackgroundColor?(O.style.backgroundColor=x.closeButtonBackgroundColor,O.classList.remove("hover:tvw-bg-gray-100")):(O.style.backgroundColor="",O.classList.add("hover:tvw-bg-gray-100")),x.closeButtonBorderWidth||x.closeButtonBorderColor){let le=x.closeButtonBorderWidth||"0px",Ze=x.closeButtonBorderColor||"transparent";O.style.border=`${le} solid ${Ze}`,O.classList.remove("tvw-border-none")}else O.style.border="",O.classList.add("tvw-border-none");x.closeButtonBorderRadius?(O.style.borderRadius=x.closeButtonBorderRadius,O.classList.remove("tvw-rounded-full")):(O.style.borderRadius="",O.classList.add("tvw-rounded-full")),x.closeButtonPaddingX?(O.style.paddingLeft=x.closeButtonPaddingX,O.style.paddingRight=x.closeButtonPaddingX):(O.style.paddingLeft="",O.style.paddingRight=""),x.closeButtonPaddingY?(O.style.paddingTop=x.closeButtonPaddingY,O.style.paddingBottom=x.closeButtonPaddingY):(O.style.paddingTop="",O.style.paddingBottom="");let Ge=(ys=x.closeButtonIconName)!=null?ys:"x",Ne=(vs=x.closeButtonIconText)!=null?vs:"\xD7";O.innerHTML="";let dt=ge(Ge,"20px",x.closeButtonColor||"",2);dt?O.appendChild(dt):O.textContent=Ne;let Rt=(bs=x.closeButtonTooltipText)!=null?bs:"Close chat",Ae=(xs=x.closeButtonShowTooltip)!=null?xs:!0;if(O.setAttribute("aria-label",Rt),Z&&(Z._cleanupTooltip&&(Z._cleanupTooltip(),delete Z._cleanupTooltip),Ae&&Rt)){let le=null,Ze=()=>{if(le||!O)return;le=c("div","tvw-clear-chat-tooltip"),le.textContent=Rt;let _t=c("div");_t.className="tvw-clear-chat-tooltip-arrow",le.appendChild(_t);let hn=O.getBoundingClientRect();le.style.position="fixed",le.style.left=`${hn.left+hn.width/2}px`,le.style.top=`${hn.top-8}px`,le.style.transform="translate(-50%, -100%)",document.body.appendChild(le)},Qe=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};Z.addEventListener("mouseenter",Ze),Z.addEventListener("mouseleave",Qe),O.addEventListener("focus",Ze),O.addEventListener("blur",Qe),Z._cleanupTooltip=()=>{Qe(),Z&&(Z.removeEventListener("mouseenter",Ze),Z.removeEventListener("mouseleave",Qe)),O&&(O.removeEventListener("focus",Ze),O.removeEventListener("blur",Qe))}}}let{clearChatButton:k,clearChatButtonWrapper:q}=re;if(k){let L=(Cs=x.clearChat)!=null?Cs:{},ce=(Ss=L.enabled)!=null?Ss:!0,Z=(As=L.placement)!=null?As:"inline";if(q){q.style.display=ce?"":"none";let Te=Z==="top-right",fe=q.classList.contains("tvw-absolute");if(Te!==fe&&ce){if(q.remove(),Te)q.className="tvw-absolute tvw-top-4 tvw-z-50",q.style.right="48px",Y.style.position="relative",Y.appendChild(q);else{q.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",q.style.right="";let Ne=Y.querySelector(".tvw-border-b-cw-divider"),dt=re.closeButtonWrapper;Ne&&dt&&dt.parentElement===Ne?Ne.insertBefore(q,dt):Ne&&Ne.appendChild(q)}let Ge=re.closeButtonWrapper;Ge&&!Ge.classList.contains("tvw-absolute")&&(Te?Ge.classList.add("tvw-ml-auto"):Ge.classList.remove("tvw-ml-auto"))}}if(ce){let Te=(Ts=L.size)!=null?Ts:"32px";k.style.height=Te,k.style.width=Te;let fe=(Es=L.iconName)!=null?Es:"refresh-cw",Ge=(Ws=L.iconColor)!=null?Ws:"";k.innerHTML="";let Ne=ge(fe,"20px",Ge||"",2);if(Ne&&k.appendChild(Ne),Ge?(k.style.color=Ge,k.classList.remove("tvw-text-cw-muted")):(k.style.color="",k.classList.add("tvw-text-cw-muted")),L.backgroundColor?(k.style.backgroundColor=L.backgroundColor,k.classList.remove("hover:tvw-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let Ae=L.borderWidth||"0px",le=L.borderColor||"transparent";k.style.border=`${Ae} solid ${le}`,k.classList.remove("tvw-border-none")}else k.style.border="",k.classList.add("tvw-border-none");L.borderRadius?(k.style.borderRadius=L.borderRadius,k.classList.remove("tvw-rounded-full")):(k.style.borderRadius="",k.classList.add("tvw-rounded-full")),L.paddingX?(k.style.paddingLeft=L.paddingX,k.style.paddingRight=L.paddingX):(k.style.paddingLeft="",k.style.paddingRight=""),L.paddingY?(k.style.paddingTop=L.paddingY,k.style.paddingBottom=L.paddingY):(k.style.paddingTop="",k.style.paddingBottom="");let dt=(Ms=L.tooltipText)!=null?Ms:"Clear chat",Rt=(Ls=L.showTooltip)!=null?Ls:!0;if(k.setAttribute("aria-label",dt),q&&(q._cleanupTooltip&&(q._cleanupTooltip(),delete q._cleanupTooltip),Rt&&dt)){let Ae=null,le=()=>{if(Ae||!k)return;Ae=c("div","tvw-clear-chat-tooltip"),Ae.textContent=dt;let Qe=c("div");Qe.className="tvw-clear-chat-tooltip-arrow",Ae.appendChild(Qe);let _t=k.getBoundingClientRect();Ae.style.position="fixed",Ae.style.left=`${_t.left+_t.width/2}px`,Ae.style.top=`${_t.top-8}px`,Ae.style.transform="translate(-50%, -100%)",document.body.appendChild(Ae)},Ze=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};q.addEventListener("mouseenter",le),q.addEventListener("mouseleave",Ze),k.addEventListener("focus",le),k.addEventListener("blur",Ze),q._cleanupTooltip=()=>{Ze(),q&&(q.removeEventListener("mouseenter",le),q.removeEventListener("mouseleave",Ze)),k&&(k.removeEventListener("focus",le),k.removeEventListener("blur",Ze))}}}}let ee=t.actionParsers&&t.actionParsers.length?t.actionParsers:[un],me=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Ut.message,Ut.messageAndClick];C=pn({parsers:ee,handlers:me,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),I=yo(t,C),N.updateConfig(t),Pt(ne,N.getMessages(),I),tt.render(t.suggestionChips,N,se,void 0,t.suggestionChipsConfig),Yt(),jt(N.isStreaming());let _e=((Bs=t.voiceRecognition)==null?void 0:Bs.enabled)===!0,He=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ot=_e&&He;if(Je.classList.remove("tvw-gap-1","tvw-gap-3"),Je.classList.add(ot?"tvw-gap-1":"tvw-gap-3"),_e&&He)if(!B||!ke){let L=Le(t.voiceRecognition,t.sendButton);L&&(B=L.micButton,ke=L.micButtonWrapper,Je.insertBefore(ke,qe),B.addEventListener("click",W),B.disabled=N.isStreaming())}else{let L=(Hs=t.voiceRecognition)!=null?Hs:{},ce=(ks=t.sendButton)!=null?ks:{},Z=(Rs=L.iconName)!=null?Rs:"mic",Te=(Is=ce.size)!=null?Is:"40px",fe=($s=L.iconSize)!=null?$s:Te,Ge=parseFloat(fe)||24;B.style.width=fe,B.style.height=fe,B.style.minWidth=fe,B.style.minHeight=fe;let Ne=(Os=(Ps=L.iconColor)!=null?Ps:ce.textColor)!=null?Os:"currentColor";B.innerHTML="";let dt=ge(Z,Ge,Ne,2);dt?B.appendChild(dt):B.textContent="\u{1F3A4}";let Rt=(Ns=L.backgroundColor)!=null?Ns:ce.backgroundColor;Rt?(B.style.backgroundColor=Rt,B.classList.remove("tvw-bg-cw-primary")):(B.style.backgroundColor="",B.classList.add("tvw-bg-cw-primary")),Ne?(B.style.color=Ne,B.classList.remove("tvw-text-white")):!Ne&&!ce.textColor&&(B.style.color="",B.classList.add("tvw-text-white")),L.borderWidth?(B.style.borderWidth=L.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),L.borderColor?B.style.borderColor=L.borderColor:B.style.borderColor="",L.paddingX?(B.style.paddingLeft=L.paddingX,B.style.paddingRight=L.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),L.paddingY?(B.style.paddingTop=L.paddingY,B.style.paddingBottom=L.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Ae=ke==null?void 0:ke.querySelector(".tvw-send-button-tooltip"),le=(Fs=L.tooltipText)!=null?Fs:"Start voice recognition";if(((Ds=L.showTooltip)!=null?Ds:!1)&&le)if(Ae)Ae.textContent=le,Ae.style.display="";else{let Qe=document.createElement("div");Qe.className="tvw-send-button-tooltip",Qe.textContent=le,ke==null||ke.insertBefore(Qe,B)}else Ae&&(Ae.style.display="none");ke.style.display="",B.disabled=N.isStreaming()}else B&&ke&&(ke.style.display="none",v&&ve());let pe=(js=t.sendButton)!=null?js:{},Tt=(_s=pe.useIcon)!=null?_s:!1,Ht=(qs=pe.iconText)!=null?qs:"\u2191",kt=pe.iconName,Et=(Us=pe.tooltipText)!=null?Us:"Send message",Nt=(zs=pe.showTooltip)!=null?zs:!1,Ft=(Ys=pe.size)!=null?Ys:"40px",an=pe.backgroundColor,Ct=pe.textColor;if(Tt){if($.style.width=Ft,$.style.height=Ft,$.style.minWidth=Ft,$.style.minHeight=Ft,$.style.fontSize="18px",$.style.lineHeight="1",$.innerHTML="",kt){let L=parseFloat(Ft)||24,ce=Ct&&typeof Ct=="string"&&Ct.trim()?Ct.trim():"currentColor",Z=ge(kt,L,ce,2);Z?($.appendChild(Z),$.style.color=ce):($.textContent=Ht,Ct?$.style.color=Ct:$.classList.add("tvw-text-white"))}else $.textContent=Ht,Ct?$.style.color=Ct:$.classList.add("tvw-text-white");$.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",an?($.style.backgroundColor=an,$.classList.remove("tvw-bg-cw-primary")):$.classList.add("tvw-bg-cw-primary")}else $.textContent=(Ks=(Js=t.copy)==null?void 0:Js.sendButtonLabel)!=null?Ks:"Send",$.style.width="",$.style.height="",$.style.minWidth="",$.style.minHeight="",$.style.fontSize="",$.style.lineHeight="",$.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",an?($.style.backgroundColor=an,$.classList.remove("tvw-bg-cw-accent")):$.classList.add("tvw-bg-cw-accent"),Ct?$.style.color=Ct:$.classList.add("tvw-text-white");pe.borderWidth?($.style.borderWidth=pe.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),pe.borderColor?$.style.borderColor=pe.borderColor:$.style.borderColor="",pe.paddingX?($.style.paddingLeft=pe.paddingX,$.style.paddingRight=pe.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),pe.paddingY?($.style.paddingTop=pe.paddingY,$.style.paddingBottom=pe.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let Xt=qe==null?void 0:qe.querySelector(".tvw-send-button-tooltip");if(Nt&&Et)if(Xt)Xt.textContent=Et,Xt.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=Et,qe==null||qe.insertBefore(L,$)}else Xt&&(Xt.style.display="none");let Vt=(Xs=t.statusIndicator)!=null?Xs:{},xo=(Vs=Vt.visible)!=null?Vs:!0;if(et.style.display=xo?"":"none",N){let L=N.getStatus(),ce=Z=>{var Te,fe,Ge,Ne;return Z==="idle"?(Te=Vt.idleText)!=null?Te:Ye.idle:Z==="connecting"?(fe=Vt.connectingText)!=null?fe:Ye.connecting:Z==="connected"?(Ge=Vt.connectedText)!=null?Ge:Ye.connected:Z==="error"?(Ne=Vt.errorText)!=null?Ne:Ye.error:Ye[Z]};et.textContent=ce(L)}},open(){y&&st(!0,"api")},close(){y&&st(!1,"api")},toggle(){y&&st(!S,"api")},clearChat(){N.clearMessages();try{localStorage.removeItem(zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zt}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",M)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},C.syncFromMetadata()},setMessage(a){return!se||N.isStreaming()?!1:(!S&&y&&st(!0,"system"),se.value=a,se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(N.isStreaming())return!1;let p=(a==null?void 0:a.trim())||se.value.trim();return p?(!S&&y&&st(!0,"system"),se.value="",N.sendMessage(p),!0):!1},startVoiceRecognition(){return v||N.isStreaming()||!We()?!1:(!S&&y&&st(!0,"system"),ie.manuallyDeactivated=!1,he(),Me("user"),!0)},stopVoiceRecognition(){return v?(ie.manuallyDeactivated=!0,he(),ve("user"),!0):!1},injectTestMessage(a){!S&&y&&st(!0,"system"),N.injectTestEvent(a)},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,p){return s.on(a,p)},off(a,p){s.off(a,p)},isOpen(){return y&&S},isVoiceActive(){return ie.active},getState(){return{open:y&&S,launcherEnabled:y,voiceActive:ie.active,streaming:N.isStreaming()}},destroy(){Pe.forEach(a=>a()),te.remove(),w==null||w.destroy(),g==null||g.remove(),Ue&&O.removeEventListener("click",Ue)}};if((((Jn=r==null?void 0:r.debugTools)!=null?Jn:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:Ce,getMessages:Ce.getMessages,getStatus:Ce.getStatus,getMetadata:Ce.getPersistentMetadata,updateMetadata:Ce.updatePersistentMetadata,clearHistory:()=>Ce.clearChat(),setVoiceActive:M=>M?Ce.startVoiceRecognition():Ce.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Pe.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return Ce};var Dn={},Xo=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},Vo=()=>{try{if(typeof Dn!="undefined"&&Dn.url)return new URL("../widget.css",Dn.url).href}catch{}return null},vo=n=>{let e=Vo(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let o=t.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else r();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-vanilla-agent","true"),document.head.appendChild(o)}},bo=n=>{var h,d,E,f;let e=Xo(n.target),r=document.createElement("div");r.className="vanilla-agent-host";let t=(E=(d=(h=n.config)==null?void 0:h.launcher)==null?void 0:d.enabled)!=null?E:!0;t||(r.style.height="100%",r.style.display="flex",r.style.flexDirection="column"),e.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let C=r.attachShadow({mode:"open"});i=C,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),C.appendChild(s),vo(C)}else i=r,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),vo(r);let l=Fn(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let u={...l,host:r,destroy(){l.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=u),u};function Go(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function gn(n){var e,r;return(r=(e=n.parserType)!=null?e:Go(n.streamParser))!=null?r:"plain"}function Zo(n,e="esm"){let r={...n};return delete r.postprocessMessage,delete r.initialMessages,e==="esm"?Qo(r):e==="script-installer"?nr(r):e==="script-advanced"?or(r):e==="react-component"?er(r):e==="react-advanced"?tr(r):sr(r)}function Qo(n){let e=gn(n),r=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
55
+ `)}function er(n){let e=gn(n),r=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
56
+ `)}function tr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"?e.push(` ${r}: ${t},`):typeof t=="number"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,t])=>{e.push(` ${r}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
57
+ `)}function nr(n){let e=gn(n),r=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
58
+ `)}function sr(n){let e=gn(n),r=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),r&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
59
+ `)}function or(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,t])=>{e.push(` ${r}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"?e.push(` ${r}: ${t},`):typeof t=="number"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,t])=>{typeof t=="string"?e.push(` ${r}: "${t}",`):typeof t=="boolean"&&e.push(` ${r}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,t])=>{e.push(` ${r}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{e.push(` "${r}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" })"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
60
+ `)}var _i=bo;export{qt as AgentWidgetClient,Gt as AgentWidgetSession,Oe as DEFAULT_WIDGET_CONFIG,Qt as attachHeaderToContainer,en as buildComposer,ro as buildDefaultHeader,ao as buildExpandedHeader,Dt as buildHeader,Sn as buildHeaderWithLayout,io as buildMinimalHeader,nn as componentRegistry,pn as createActionManager,Fn as createAgentExperience,Po as createBubbleWithLayout,Jo as createComponentMiddleware,In as createComponentStreamParser,Mo as createFlexibleJsonStreamParser,vn as createJsonStreamParser,kn as createLocalStorageAdapter,wn as createPlainTextParser,yn as createRegexJsonParser,tn as createStandardBubble,dn as createTypingIndicator,bn as createXmlParser,_i as default,Ut as defaultActionHandlers,un as defaultJsonActionParser,Ao as directivePostprocessor,mn as escapeHtml,On as extractComponentDirectiveFromMessage,Zo as generateCodeSnippet,lo as getHeaderLayout,Pn as hasComponentDirective,Cn as headerLayouts,bo as initAgentWidget,Yo as isComponentDirectiveType,Qs as markdownPostprocessor,Bn as mergeWithDefaults,cn as pluginRegistry,$n as renderComponentDirective};
16
61
  //# sourceMappingURL=index.js.map