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