vanilla-agent 1.21.0 → 1.22.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/README.md +87 -0
- package/dist/index.cjs +24 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +247 -3
- package/dist/index.d.ts +247 -3
- package/dist/index.global.js +43 -43
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +23 -23
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/widget.css +185 -0
- package/package.json +1 -1
- package/src/client.ts +215 -1
- package/src/components/message-bubble.ts +208 -4
- package/src/components/messages.ts +10 -3
- package/src/defaults.ts +15 -0
- package/src/index.ts +11 -3
- package/src/install.ts +69 -7
- package/src/session.ts +77 -1
- package/src/styles/widget.css +185 -0
- package/src/types.ts +184 -0
- package/src/ui.ts +27 -4
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{Marked as
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),An=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)}},
|
|
1
|
+
import{Marked as Lo}from"marked";var ko=n=>{if(n)return n},un=n=>{var r,s;let e=n==null?void 0:n.markedOptions,o=new Lo({gfm:(r=e==null?void 0:e.gfm)!=null?r:!0,breaks:(s=e==null?void 0:e.breaks)!=null?s:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),t=ko(n==null?void 0:n.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},gn=n=>n?un({markedOptions:n.options,renderer:n.renderer}):un(),Bo=un(),oo=n=>Bo(n),Sn=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ro=n=>n.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),so=n=>`%%FORM_PLACEHOLDER_${n}%%`,io=(n,e)=>{let o=n;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=so(e.length);return e.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let s=so(e.length);return e.push({token:s,type:r}),s}),o},Ho=n=>{let e=gn(n);return o=>{let t=[],r=io(o,t),s=e(r);return t.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="tvw-form-directive" data-tv-form="${ro(l)}"></div>`;s=s.replace(d,c)}),s}},Ro=n=>{let e=[],o=io(n,e),t=oo(o);return e.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${ro(s)}"></div>`;t=t.replace(i,d)}),t};import{parse as ao,STR as lo,OBJ as co}from"partial-json";var hn=n=>n.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),An=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)}},Io=n=>{var i,l;let e=(i=n.completedAt)!=null?i:Date.now(),o=(l=n.startedAt)!=null?l:e,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},po=n=>n.status==="complete"?Io(n):n.status==="pending"?"Waiting":"",Po=n=>{var r,s,i;let o=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((r=n.completedAt)!=null?r:Date.now())-((i=(s=n.startedAt)!=null?s:n.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 uo=n=>n.status==="complete"?Po(n):"Using tool...",$o=()=>{let n=null,e=0,o=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
3
3
|
`).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,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let 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()=>{}}},mn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Tn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},En=()=>{var e;let n=Io();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)}},Wn=()=>{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=io(r,ao|lo);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?hn(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=hn(o.text)))}catch{}return e=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},$o=n=>{let e=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?hn(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?hn(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(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=io(s,ao|lo),c=o(l);c!==null&&(e=c)}catch{}return r=s.length,{text:e||"",raw:s}},close:()=>{}}},Mn=()=>{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 Po="https://api.travrse.ai/v1/dispatch";function Oo(n){switch(n){case"json":return Wn;case"regex-json":return En;case"xml":return Mn;case"plain":default:return Tn}}var Kt=class{constructor(e={}){this.config=e;var r,t,o;this.apiUrl=(r=e.apiUrl)!=null?r:Po,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:Oo(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 c=l instanceof Error?l:new Error(String(l));throw r({type:"error",error:c}),c}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 c={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=c,o(c),c};if(i.text!==void 0){let c=l();c.content+=i.text,o(c)}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 Z,$,Ne,Ye,Qe,xt,Ct,D,me,mt,ft,Je,et,M,Le,it,at,Et,wt,$e,tt,qe,j,lt,Ke,We,_e,J,Se,Be,Ue,nt,St,Lt,gt,At,de,Nt,Bt,be,yt,Tt,kt,vt,Wt,ln,dn,cn,xn,Ft,Dt,st,zt,Gt,Zt,Qt;let t=e.getReader(),o=new TextDecoder,s="",i=Date.now(),l=0,c=()=>i+l++,g=y=>{let K=y.reasoning?{...y.reasoning,chunks:[...y.reasoning.chunks]}:void 0,oe=y.toolCall?{...y.toolCall,chunks:y.toolCall.chunks?[...y.toolCall.chunks]:void 0}:void 0,we=y.tools?y.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...y,reasoning:K,toolCall:oe,tools:we}},d=y=>{r({type:"message",message:g(y)})},A=null,f={current:null},b=new Map,w=new Map,q={lastId:null,byStep:new Map},F={lastId:null,byCall:new Map},m=y=>{if(y==null)return null;try{return String(y)}catch{return null}},x=y=>{var K,oe,we,Pe,Oe;return m((Oe=(Pe=(we=(oe=(K=y.stepId)!=null?K:y.step_id)!=null?oe:y.step)!=null?we:y.parentId)!=null?Pe:y.flowStepId)!=null?Oe:y.flow_step_id)},I=y=>{var K,oe,we,Pe,Oe,ce,L;return m((L=(ce=(Oe=(Pe=(we=(oe=(K=y.callId)!=null?K:y.call_id)!=null?oe:y.requestId)!=null?we:y.request_id)!=null?Pe:y.toolCallId)!=null?Oe:y.tool_call_id)!=null?ce:y.stepId)!=null?L:y.step_id)},S=()=>A||(A={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(A),A),Y=(y,K)=>{q.lastId=K,y&&q.byStep.set(y,K)},P=(y,K)=>{var Oe;let oe=(Oe=y.reasoningId)!=null?Oe:y.id,we=x(y);if(oe){let ce=String(oe);return Y(we,ce),ce}if(we){let ce=q.byStep.get(we);if(ce)return q.lastId=ce,ce}if(q.lastId&&!K)return q.lastId;if(!K)return null;let Pe=`reason-${c()}`;return Y(we,Pe),Pe},V=y=>{let K=b.get(y);if(K)return K;let oe={id:`reason-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:y,status:"streaming",chunks:[]}};return b.set(y,oe),d(oe),oe},Q=(y,K)=>{F.lastId=K,y&&F.byCall.set(y,K)},W=(y,K)=>{var Oe;let oe=(Oe=y.toolId)!=null?Oe:y.id,we=I(y);if(oe){let ce=String(oe);return Q(we,ce),ce}if(we){let ce=F.byCall.get(we);if(ce)return F.lastId=ce,ce}if(F.lastId&&!K)return F.lastId;if(!K)return null;let Pe=`tool-${c()}`;return Q(we,Pe),Pe},le=y=>{let K=w.get(y);if(K)return K;let oe={id:`tool-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:y,status:"pending"}};return w.set(y,oe),d(oe),oe},G=y=>{if(typeof y=="number"&&Number.isFinite(y))return y;if(typeof y=="string"){let K=Number(y);if(!Number.isNaN(K)&&Number.isFinite(K))return K;let oe=Date.parse(y);if(!Number.isNaN(oe))return oe}return Date.now()},U=y=>{if(typeof y=="string")return y;if(y==null)return"";try{return JSON.stringify(y)}catch{return String(y)}},z=new Map,ne=new Map;for(;;){let{done:y,value:K}=await t.read();if(y)break;s+=o.decode(K,{stream:!0});let oe=s.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},mn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Tn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},En=()=>{var e;let n=$o();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(o)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Wn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=e)return n!==null||n===""?{text:n||"",raw:o}:null;try{let r=ao(o,lo|co);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?hn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=hn(r.text)))}catch{}return e=o.length,n!==null?{text:n,raw:o}:null},close:()=>{}}},Oo=n=>{let e=null,o=0,r=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?hn(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?hn(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=o)return e!==null?{text:e,raw:s}:null;try{let l=ao(s,lo|co),d=r(l);d!==null&&(e=d)}catch{}return o=s.length,{text:e||"",raw:s}},close:()=>{}}},Mn=()=>{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 Fo="https://api.travrse.ai/v1/dispatch",Do="https://api.travrse.ai";function No(n){switch(n){case"json":return Wn;case"regex-json":return En;case"xml":return Mn;case"plain":default:return Tn}}var Xt=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=e.apiUrl)!=null?o:Fo,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:No(e.parserType),this.contextProviders=(r=e.contextProviders)!=null?r:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(e){var t;let o=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Do;return e==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var e,o;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(o=(e=this.config).onSessionInit)==null||o.call(e,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.clientToken,flow_id:this.config.flowId})});if(!e.ok){let t=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${t.hint||t.error}`):e.status===403?new Error(`Origin not allowed: ${t.hint||t.error}`):new Error(t.error||"Failed to initialize session")}let o=await e.json();return{sessionId:o.session_id,expiresAt:new Date(o.expires_at),flow:o.flow,config:{welcomeMessage:o.config.welcome_message,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}async dispatch(e,o){return this.isClientTokenMode()?this.dispatchClientToken(e,o):this.dispatchProxy(e,o)}async dispatchClientToken(e,o){var r,s,i,l;let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let y=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:y}),y}let u={session_id:d.sessionId,messages:e.messages.map(y=>({role:y.role,content:y.rawContent||y.content}))};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let c=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:t.signal});if(!c.ok){let y=await c.json().catch(()=>({error:"Chat request failed"}));if(c.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let b=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:b}),b}if(c.status===429){let b=new Error(y.hint||"Message limit reached for this session.");throw o({type:"error",error:b}),b}let m=new Error(y.error||"Failed to send message");throw o({type:"error",error:m}),m}if(!c.body){let y=new Error("No response body received");throw o({type:"error",error:y}),y}o({type:"status",status:"connected"});try{await this.streamResponse(c.body,o)}finally{o({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&o({type:"error",error:u}),u}}async dispatchProxy(e,o){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(e.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:t.signal},r)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw 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(e){let t={messages:e.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:e,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(e,o,t,r,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 d={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=d,r(d),d};if(i.text!==void 0){let d=l();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),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(e,o){var De,oe,$,qe,Xe,tt,bt,Ct,q,he,mt,ft,Ve,nt,L,Re,it,at,Tt,wt,$e,st,Ue,U,lt,Ae,Oe,Z,Te,Ee,ze,Je,xt,kt,yt,Et,St,we,Bt,ke,Ye,At,Ft,Wt,Dt,Mt,ln,dn,cn,Cn,Nt,jt,ot,Jt,Zt,Qt;let t=e.getReader(),r=new TextDecoder,s="",i=Date.now(),l=0,d=()=>i+l++,u=S=>{let X=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,te=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,be=S.tools?S.tools.map(xe=>({...xe,chunks:xe.chunks?[...xe.chunks]:void 0})):void 0;return{...S,reasoning:X,toolCall:te,tools:be}},c=S=>{o({type:"message",message:u(S)})},y=null,m={current:null},b=new Map,f=new Map,D={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},h=S=>{if(S==null)return null;try{return String(S)}catch{return null}},x=S=>{var X,te,be,xe,Ne;return h((Ne=(xe=(be=(te=(X=S.stepId)!=null?X:S.step_id)!=null?te:S.step)!=null?be:S.parentId)!=null?xe:S.flowStepId)!=null?Ne:S.flow_step_id)},R=S=>{var X,te,be,xe,Ne,Se,A;return h((A=(Se=(Ne=(xe=(be=(te=(X=S.callId)!=null?X:S.call_id)!=null?te:S.requestId)!=null?be:S.request_id)!=null?xe:S.toolCallId)!=null?Ne:S.tool_call_id)!=null?Se:S.stepId)!=null?A:S.step_id)},w=()=>y||(y={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},c(y),y),K=(S,X)=>{D.lastId=X,S&&D.byStep.set(S,X)},T=(S,X)=>{var Ne;let te=(Ne=S.reasoningId)!=null?Ne:S.id,be=x(S);if(te){let Se=String(te);return K(be,Se),Se}if(be){let Se=D.byStep.get(be);if(Se)return D.lastId=Se,Se}if(D.lastId&&!X)return D.lastId;if(!X)return null;let xe=`reason-${d()}`;return K(be,xe),xe},O=S=>{let X=b.get(S);if(X)return X;let te={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:S,status:"streaming",chunks:[]}};return b.set(S,te),c(te),te},ee=(S,X)=>{j.lastId=X,S&&j.byCall.set(S,X)},P=(S,X)=>{var Ne;let te=(Ne=S.toolId)!=null?Ne:S.id,be=R(S);if(te){let Se=String(te);return ee(be,Se),Se}if(be){let Se=j.byCall.get(be);if(Se)return j.lastId=Se,Se}if(j.lastId&&!X)return j.lastId;if(!X)return null;let xe=`tool-${d()}`;return ee(be,xe),xe},Y=S=>{let X=f.get(S);if(X)return X;let te={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:S,status:"pending"}};return f.set(S,te),c(te),te},fe=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let X=Number(S);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let te=Date.parse(S);if(!Number.isNaN(te))return te}return Date.now()},J=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},F=new Map,ne=new Map;for(;;){let{done:S,value:X}=await t.read();if(S)break;s+=r.decode(X,{stream:!0});let te=s.split(`
|
|
5
5
|
|
|
6
|
-
`);s=(
|
|
7
|
-
`),Oe="message",ce="";for(let ee of Pe)ee.startsWith("event:")?Oe=ee.replace("event:","").trim():ee.startsWith("data:")&&(ce+=ee.replace("data:","").trim());if(!ce)continue;let L;try{L=JSON.parse(ce)}catch(ee){r({type:"error",error:ee instanceof Error?ee:new Error("Failed to parse chat stream payload")});continue}let ot=Oe!=="message"?Oe:($=L.type)!=null?$:"message";if(this.parseSSEEvent){f.current=A;let ee=await this.handleCustomSSEEvent(L,r,f,d,c);if(f.current&&!A&&(A=f.current),ee)continue}if(ot==="reason_start"){let ee=(Ne=P(L,!0))!=null?Ne:`reason-${c()}`,C=V(ee);C.reasoning=(Ye=C.reasoning)!=null?Ye:{id:ee,status:"streaming",chunks:[]},C.reasoning.startedAt=(xt=C.reasoning.startedAt)!=null?xt:G((Qe=L.startedAt)!=null?Qe:L.timestamp),C.reasoning.completedAt=void 0,C.reasoning.durationMs=void 0,C.streaming=!0,C.reasoning.status="streaming",d(C)}else if(ot==="reason_chunk"){let ee=(D=(Ct=P(L,!1))!=null?Ct:P(L,!0))!=null?D:`reason-${c()}`,C=V(ee);C.reasoning=(me=C.reasoning)!=null?me:{id:ee,status:"streaming",chunks:[]},C.reasoning.startedAt=(ft=C.reasoning.startedAt)!=null?ft:G((mt=L.startedAt)!=null?mt:L.timestamp);let h=(M=(et=(Je=L.reasoningText)!=null?Je:L.text)!=null?et:L.delta)!=null?M:"";if(h&&L.hidden!==!0&&C.reasoning.chunks.push(String(h)),C.reasoning.status=L.done?"complete":"streaming",L.done){C.reasoning.completedAt=G((Le=L.completedAt)!=null?Le:L.timestamp);let k=(it=C.reasoning.startedAt)!=null?it:Date.now();C.reasoning.durationMs=Math.max(0,((at=C.reasoning.completedAt)!=null?at:Date.now())-k)}C.streaming=C.reasoning.status!=="complete",d(C)}else if(ot==="reason_complete"){let ee=(wt=(Et=P(L,!1))!=null?Et:P(L,!0))!=null?wt:`reason-${c()}`,C=b.get(ee);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=G(($e=L.completedAt)!=null?$e:L.timestamp);let k=(tt=C.reasoning.startedAt)!=null?tt:Date.now();C.reasoning.durationMs=Math.max(0,((qe=C.reasoning.completedAt)!=null?qe:Date.now())-k),C.streaming=!1,d(C)}let h=x(L);h&&q.byStep.delete(h)}else if(ot==="tool_start"){let ee=(j=W(L,!0))!=null?j:`tool-${c()}`,C=le(ee),h=(lt=C.toolCall)!=null?lt:{id:ee,status:"pending"};h.name=(Ke=L.toolName)!=null?Ke:h.name,h.status="running",L.args!==void 0&&(h.args=L.args),h.startedAt=(_e=h.startedAt)!=null?_e:G((We=L.startedAt)!=null?We:L.timestamp),h.completedAt=void 0,h.durationMs=void 0,C.toolCall=h,C.streaming=!0,d(C)}else if(ot==="tool_chunk"){let ee=(Se=(J=W(L,!1))!=null?J:W(L,!0))!=null?Se:`tool-${c()}`,C=le(ee),h=(Be=C.toolCall)!=null?Be:{id:ee,status:"running"};h.startedAt=(nt=h.startedAt)!=null?nt:G((Ue=L.startedAt)!=null?Ue:L.timestamp);let k=(gt=(Lt=(St=L.text)!=null?St:L.delta)!=null?Lt:L.message)!=null?gt:"";k&&(h.chunks=(At=h.chunks)!=null?At:[],h.chunks.push(String(k))),h.status="running",C.toolCall=h,C.streaming=!0,d(C)}else if(ot==="tool_complete"){let ee=(Nt=(de=W(L,!1))!=null?de:W(L,!0))!=null?Nt:`tool-${c()}`,C=le(ee),h=(Bt=C.toolCall)!=null?Bt:{id:ee,status:"running"};if(h.status="complete",L.result!==void 0&&(h.result=L.result),typeof L.duration=="number"&&(h.duration=L.duration),h.completedAt=G((be=L.completedAt)!=null?be:L.timestamp),typeof L.duration=="number")h.durationMs=L.duration;else{let ye=(yt=h.startedAt)!=null?yt:Date.now();h.durationMs=Math.max(0,((Tt=h.completedAt)!=null?Tt:Date.now())-ye)}C.toolCall=h,C.streaming=!1,d(C);let k=I(L);k&&F.byCall.delete(k)}else if(ot==="step_chunk"){let ee=L.stepType,C=L.executionType;if(ee==="tool"||C==="context")continue;let h=S(),k=(ln=(Wt=(vt=(kt=L.text)!=null?kt:L.delta)!=null?vt:L.content)!=null?Wt:L.chunk)!=null?ln:"";if(k){let Ae=((dn=ne.get(h.id))!=null?dn:"")+k;h.rawContent=Ae,z.has(h.id)||z.set(h.id,this.createStreamParser());let Xe=z.get(h.id),ke=Ae.trim().startsWith("{")||Ae.trim().startsWith("[");if(ke&&ne.set(h.id,Ae),Xe.__isPlainTextParser===!0){h.content+=k,ne.delete(h.id),z.delete(h.id),h.rawContent=void 0,d(h);continue}let De=Xe.processChunk(Ae);if(De instanceof Promise)De.then(ae=>{var He;let pe=typeof ae=="string"?ae:(He=ae==null?void 0:ae.text)!=null?He:null;if(pe!==null&&pe.trim()!==""){let ue=A;ue&&ue.id===h.id&&(ue.content=pe,d(ue))}else if(!ke&&!Ae.trim().startsWith("<")){let ue=A;ue&&ue.id===h.id&&(ue.content+=k,ne.delete(ue.id),z.delete(ue.id),ue.rawContent=void 0,d(ue))}}).catch(()=>{h.content+=k,ne.delete(h.id),z.delete(h.id),h.rawContent=void 0,d(h)});else{let ae=typeof De=="string"?De:(cn=De==null?void 0:De.text)!=null?cn:null;ae!==null&&ae.trim()!==""?(h.content=ae,d(h)):!ke&&!Ae.trim().startsWith("<")&&(h.content+=k,ne.delete(h.id),z.delete(h.id),h.rawContent=void 0,d(h))}}if(L.isComplete){let ye=(Ft=(xn=L.result)==null?void 0:xn.response)!=null?Ft:h.content;if(ye){let Ae=ne.get(h.id),Xe=Ae!=null?Ae:U(ye);h.rawContent=Xe;let ke=z.get(h.id),xe=null,De=!1;if(ke&&(xe=ke.getExtractedText(),xe===null&&(xe=mn(Xe)),xe===null)){let ae=ke.processChunk(Xe);ae instanceof Promise?(De=!0,ae.then(pe=>{var ue;let He=typeof pe=="string"?pe:(ue=pe==null?void 0:pe.text)!=null?ue:null;if(He!==null){let Fe=A;Fe&&Fe.id===h.id&&(Fe.content=He,Fe.streaming=!1,z.delete(Fe.id),ne.delete(Fe.id),d(Fe))}})):xe=typeof ae=="string"?ae:(Dt=ae==null?void 0:ae.text)!=null?Dt:null}if(!De){xe!==null&&xe.trim()!==""?h.content=xe:ne.has(h.id)||(h.content=U(ye));let ae=z.get(h.id);if(ae){let pe=(st=ae.close)==null?void 0:st.call(ae);pe instanceof Promise&&pe.catch(()=>{}),z.delete(h.id)}ne.delete(h.id),h.streaming=!1,d(h)}}}}else if(ot==="step_complete"){let ee=L.stepType,C=L.executionType;if(ee==="tool"||C==="context")continue;let h=(zt=L.result)==null?void 0:zt.response,k=S();if(h!=null){let ye=z.get(k.id),Ae=!1,Xe=!1;if(ye){let ke=ye.getExtractedText(),xe=ne.get(k.id),De=xe!=null?xe:U(h);if(k.rawContent=De,ke!==null&&ke.trim()!=="")k.content=ke,Ae=!0;else{let ae=mn(De);if(ae!==null)k.content=ae,Ae=!0;else{let pe=ye.processChunk(De);if(pe instanceof Promise)Xe=!0,pe.then(He=>{var Fe;let ue=typeof He=="string"?He:(Fe=He==null?void 0:He.text)!=null?Fe:null;if(ue!==null&&ue.trim()!==""){let rt=A;rt&&rt.id===k.id&&(rt.content=ue,rt.streaming=!1,z.delete(rt.id),ne.delete(rt.id),d(rt))}else{let rt=ye.getExtractedText(),ht=A;ht&&ht.id===k.id&&(rt!==null&&rt.trim()!==""?ht.content=rt:ne.has(ht.id)||(ht.content=U(h)),ht.streaming=!1,z.delete(ht.id),ne.delete(ht.id),d(ht))}});else{let He=typeof pe=="string"?pe:(Gt=pe==null?void 0:pe.text)!=null?Gt:null;if(He!==null&&He.trim()!=="")k.content=He,Ae=!0;else{let ue=ye.getExtractedText();ue!==null&&ue.trim()!==""&&(k.content=ue,Ae=!0)}}}}}if(!Xe){if(!k.rawContent){let ke=ne.get(k.id);k.rawContent=ke!=null?ke:U(h)}if(!Ae&&!ne.has(k.id)&&(k.content=U(h)),ye){let ke=(Zt=ye.close)==null?void 0:Zt.call(ye);ke instanceof Promise&&ke.catch(()=>{})}z.delete(k.id),ne.delete(k.id),k.streaming=!1,d(k)}}else z.delete(k.id),ne.delete(k.id),k.streaming=!1,d(k)}else if(ot==="flow_complete"){let ee=(Qt=L.result)==null?void 0:Qt.response;if(ee!=null){let C=S(),h=ne.get(C.id),k=h!=null?h:U(ee);C.rawContent=k;let ye=U(ee),Ae=z.get(C.id);if(Ae){let xe=mn(k);if(xe!==null)ye=xe;else{let De=Ae.processChunk(k);De instanceof Promise&&De.then(pe=>{var ue;let He=typeof pe=="string"?pe:(ue=pe==null?void 0:pe.text)!=null?ue:null;if(He!==null){let Fe=A;Fe&&Fe.id===C.id&&(Fe.content=He,Fe.streaming=!1,d(Fe))}});let ae=Ae.getExtractedText();ae!==null&&(ye=ae)}}z.delete(C.id),ne.delete(C.id);let Xe=ye!==C.content,ke=C.streaming!==!1;Xe&&(C.content=ye),C.streaming=!1,(Xe||ke)&&d(C)}else if(A!==null){let C=A;z.delete(C.id),ne.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}r({type:"status",status:"idle"})}else ot==="error"&&L.error&&r({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};var tn=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 Kt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(e){this.config={...this.config,...e},this.client=new Kt(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,c,g,d,A;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 b={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f instanceof Error?(g=(c=this.callbacks).onError)==null||g.call(c,f):(A=(d=this.callbacks).onError)==null||A.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 c,g;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=(c=r.sequence)!=null?c:0,l=(g=t.sequence)!=null?g:0;return i!==l?i-l:r.id.localeCompare(t.id)})}};var Ln=(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 No from"lucide";var ve=(n,e=24,r="currentColor",t=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=No[o];return s?Fo(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 Fo(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 c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([g,d])=>{g!=="stroke"&&c.setAttribute(g,String(d))}),o.appendChild(c)}}}),o}var p=(n,e)=>{let r=document.createElement(n);return e&&(r.className=e),r};var ze={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var bt={"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 nn=(n,e)=>{let r=p("button");r.type="button",r.innerHTML=`
|
|
6
|
+
`);s=(De=te.pop())!=null?De:"";for(let be of te){let xe=be.split(`
|
|
7
|
+
`),Ne="message",Se="";for(let Q of xe)Q.startsWith("event:")?Ne=Q.replace("event:","").trim():Q.startsWith("data:")&&(Se+=Q.replace("data:","").trim());if(!Se)continue;let A;try{A=JSON.parse(Se)}catch(Q){o({type:"error",error:Q instanceof Error?Q:new Error("Failed to parse chat stream payload")});continue}let gt=Ne!=="message"?Ne:(oe=A.type)!=null?oe:"message";if(this.parseSSEEvent){m.current=y;let Q=await this.handleCustomSSEEvent(A,o,m,c,d);if(m.current&&!y&&(y=m.current),Q)continue}if(gt==="reason_start"){let Q=($=T(A,!0))!=null?$:`reason-${d()}`,E=O(Q);E.reasoning=(qe=E.reasoning)!=null?qe:{id:Q,status:"streaming",chunks:[]},E.reasoning.startedAt=(tt=E.reasoning.startedAt)!=null?tt:fe((Xe=A.startedAt)!=null?Xe:A.timestamp),E.reasoning.completedAt=void 0,E.reasoning.durationMs=void 0,E.streaming=!0,E.reasoning.status="streaming",c(E)}else if(gt==="reason_chunk"){let Q=(Ct=(bt=T(A,!1))!=null?bt:T(A,!0))!=null?Ct:`reason-${d()}`,E=O(Q);E.reasoning=(q=E.reasoning)!=null?q:{id:Q,status:"streaming",chunks:[]},E.reasoning.startedAt=(mt=E.reasoning.startedAt)!=null?mt:fe((he=A.startedAt)!=null?he:A.timestamp);let v=(nt=(Ve=(ft=A.reasoningText)!=null?ft:A.text)!=null?Ve:A.delta)!=null?nt:"";if(v&&A.hidden!==!0&&E.reasoning.chunks.push(String(v)),E.reasoning.status=A.done?"complete":"streaming",A.done){E.reasoning.completedAt=fe((L=A.completedAt)!=null?L:A.timestamp);let B=(Re=E.reasoning.startedAt)!=null?Re:Date.now();E.reasoning.durationMs=Math.max(0,((it=E.reasoning.completedAt)!=null?it:Date.now())-B)}E.streaming=E.reasoning.status!=="complete",c(E)}else if(gt==="reason_complete"){let Q=(Tt=(at=T(A,!1))!=null?at:T(A,!0))!=null?Tt:`reason-${d()}`,E=b.get(Q);if(E!=null&&E.reasoning){E.reasoning.status="complete",E.reasoning.completedAt=fe((wt=A.completedAt)!=null?wt:A.timestamp);let B=($e=E.reasoning.startedAt)!=null?$e:Date.now();E.reasoning.durationMs=Math.max(0,((st=E.reasoning.completedAt)!=null?st:Date.now())-B),E.streaming=!1,c(E)}let v=x(A);v&&D.byStep.delete(v)}else if(gt==="tool_start"){let Q=(Ue=P(A,!0))!=null?Ue:`tool-${d()}`,E=Y(Q),v=(U=E.toolCall)!=null?U:{id:Q,status:"pending"};v.name=(lt=A.toolName)!=null?lt:v.name,v.status="running",A.args!==void 0&&(v.args=A.args),v.startedAt=(Oe=v.startedAt)!=null?Oe:fe((Ae=A.startedAt)!=null?Ae:A.timestamp),v.completedAt=void 0,v.durationMs=void 0,E.toolCall=v,E.streaming=!0,c(E)}else if(gt==="tool_chunk"){let Q=(Te=(Z=P(A,!1))!=null?Z:P(A,!0))!=null?Te:`tool-${d()}`,E=Y(Q),v=(Ee=E.toolCall)!=null?Ee:{id:Q,status:"running"};v.startedAt=(Je=v.startedAt)!=null?Je:fe((ze=A.startedAt)!=null?ze:A.timestamp);let B=(yt=(kt=(xt=A.text)!=null?xt:A.delta)!=null?kt:A.message)!=null?yt:"";B&&(v.chunks=(Et=v.chunks)!=null?Et:[],v.chunks.push(String(B))),v.status="running",E.toolCall=v,E.streaming=!0,c(E)}else if(gt==="tool_complete"){let Q=(we=(St=P(A,!1))!=null?St:P(A,!0))!=null?we:`tool-${d()}`,E=Y(Q),v=(Bt=E.toolCall)!=null?Bt:{id:Q,status:"running"};if(v.status="complete",A.result!==void 0&&(v.result=A.result),typeof A.duration=="number"&&(v.duration=A.duration),v.completedAt=fe((ke=A.completedAt)!=null?ke:A.timestamp),typeof A.duration=="number")v.durationMs=A.duration;else{let V=(Ye=v.startedAt)!=null?Ye:Date.now();v.durationMs=Math.max(0,((At=v.completedAt)!=null?At:Date.now())-V)}E.toolCall=v,E.streaming=!1,c(E);let B=R(A);B&&j.byCall.delete(B)}else if(gt==="step_chunk"){let Q=A.stepType,E=A.executionType;if(Q==="tool"||E==="context")continue;let v=w(),B=(Mt=(Dt=(Wt=(Ft=A.text)!=null?Ft:A.delta)!=null?Wt:A.content)!=null?Dt:A.chunk)!=null?Mt:"";if(B){let ye=((ln=ne.get(v.id))!=null?ln:"")+B;v.rawContent=ye,F.has(v.id)||F.set(v.id,this.createStreamParser());let Ge=F.get(v.id),Me=ye.trim().startsWith("{")||ye.trim().startsWith("[");if(Me&&ne.set(v.id,ye),Ge.__isPlainTextParser===!0){v.content+=B,ne.delete(v.id),F.delete(v.id),v.rawContent=void 0,c(v);continue}let ve=Ge.processChunk(ye);if(ve instanceof Promise)ve.then(de=>{var Ie;let ce=typeof de=="string"?de:(Ie=de==null?void 0:de.text)!=null?Ie:null;if(ce!==null&&ce.trim()!==""){let pe=y;pe&&pe.id===v.id&&(pe.content=ce,c(pe))}else if(!Me&&!ye.trim().startsWith("<")){let pe=y;pe&&pe.id===v.id&&(pe.content+=B,ne.delete(pe.id),F.delete(pe.id),pe.rawContent=void 0,c(pe))}}).catch(()=>{v.content+=B,ne.delete(v.id),F.delete(v.id),v.rawContent=void 0,c(v)});else{let de=typeof ve=="string"?ve:(dn=ve==null?void 0:ve.text)!=null?dn:null;de!==null&&de.trim()!==""?(v.content=de,c(v)):!Me&&!ye.trim().startsWith("<")&&(v.content+=B,ne.delete(v.id),F.delete(v.id),v.rawContent=void 0,c(v))}}if(A.isComplete){let V=(Cn=(cn=A.result)==null?void 0:cn.response)!=null?Cn:v.content;if(V){let ye=ne.get(v.id),Ge=ye!=null?ye:J(V);v.rawContent=Ge;let Me=F.get(v.id),_e=null,ve=!1;if(Me&&(_e=Me.getExtractedText(),_e===null&&(_e=mn(Ge)),_e===null)){let de=Me.processChunk(Ge);de instanceof Promise?(ve=!0,de.then(ce=>{var pe;let Ie=typeof ce=="string"?ce:(pe=ce==null?void 0:ce.text)!=null?pe:null;if(Ie!==null){let Fe=y;Fe&&Fe.id===v.id&&(Fe.content=Ie,Fe.streaming=!1,F.delete(Fe.id),ne.delete(Fe.id),c(Fe))}})):_e=typeof de=="string"?de:(Nt=de==null?void 0:de.text)!=null?Nt:null}if(!ve){_e!==null&&_e.trim()!==""?v.content=_e:ne.has(v.id)||(v.content=J(V));let de=F.get(v.id);if(de){let ce=(jt=de.close)==null?void 0:jt.call(de);ce instanceof Promise&&ce.catch(()=>{}),F.delete(v.id)}ne.delete(v.id),v.streaming=!1,c(v)}}}}else if(gt==="step_complete"){let Q=A.stepType,E=A.executionType;if(Q==="tool"||E==="context")continue;let v=(ot=A.result)==null?void 0:ot.response,B=w();if(v!=null){let V=F.get(B.id),ye=!1,Ge=!1;if(V){let Me=V.getExtractedText(),_e=ne.get(B.id),ve=_e!=null?_e:J(v);if(B.rawContent=ve,Me!==null&&Me.trim()!=="")B.content=Me,ye=!0;else{let de=mn(ve);if(de!==null)B.content=de,ye=!0;else{let ce=V.processChunk(ve);if(ce instanceof Promise)Ge=!0,ce.then(Ie=>{var Fe;let pe=typeof Ie=="string"?Ie:(Fe=Ie==null?void 0:Ie.text)!=null?Fe:null;if(pe!==null&&pe.trim()!==""){let rt=y;rt&&rt.id===B.id&&(rt.content=pe,rt.streaming=!1,F.delete(rt.id),ne.delete(rt.id),c(rt))}else{let rt=V.getExtractedText(),ht=y;ht&&ht.id===B.id&&(rt!==null&&rt.trim()!==""?ht.content=rt:ne.has(ht.id)||(ht.content=J(v)),ht.streaming=!1,F.delete(ht.id),ne.delete(ht.id),c(ht))}});else{let Ie=typeof ce=="string"?ce:(Jt=ce==null?void 0:ce.text)!=null?Jt:null;if(Ie!==null&&Ie.trim()!=="")B.content=Ie,ye=!0;else{let pe=V.getExtractedText();pe!==null&&pe.trim()!==""&&(B.content=pe,ye=!0)}}}}}if(!Ge){if(!B.rawContent){let Me=ne.get(B.id);B.rawContent=Me!=null?Me:J(v)}if(!ye&&!ne.has(B.id)&&(B.content=J(v)),V){let Me=(Zt=V.close)==null?void 0:Zt.call(V);Me instanceof Promise&&Me.catch(()=>{})}F.delete(B.id),ne.delete(B.id),B.streaming=!1,c(B)}}else F.delete(B.id),ne.delete(B.id),B.streaming=!1,c(B)}else if(gt==="flow_complete"){let Q=(Qt=A.result)==null?void 0:Qt.response;if(Q!=null){let E=w(),v=ne.get(E.id),B=v!=null?v:J(Q);E.rawContent=B;let V=J(Q),ye=F.get(E.id);if(ye){let _e=mn(B);if(_e!==null)V=_e;else{let ve=ye.processChunk(B);ve instanceof Promise&&ve.then(ce=>{var pe;let Ie=typeof ce=="string"?ce:(pe=ce==null?void 0:ce.text)!=null?pe:null;if(Ie!==null){let Fe=y;Fe&&Fe.id===E.id&&(Fe.content=Ie,Fe.streaming=!1,c(Fe))}});let de=ye.getExtractedText();de!==null&&(V=de)}}F.delete(E.id),ne.delete(E.id);let Ge=V!==E.content,Me=E.streaming!==!1;Ge&&(E.content=V),E.streaming=!1,(Ge||Me)&&c(E)}else if(y!==null){let E=y;F.delete(E.id),ne.delete(E.id),E.streaming!==!1&&(E.streaming=!1,c(E))}o({type:"status",status:"idle"})}else gt==="error"&&A.error&&o({type:"error",error:A.error instanceof Error?A.error:new Error(String(A.error))})}}}};var tn=class{constructor(e={},o){this.config=e;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=e=>{var o,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=(o=this.callbacks).onError)==null||t.call(o,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Xt(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var e,o;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(o=(e=this.callbacks).onError)==null||o.call(e,t instanceof Error?t:new Error(String(t))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}updateConfig(e){this.config={...this.config,...e},this.client=new Xt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,o){var l,d,u,c,y;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let r={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(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(m){let b={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m instanceof Error?(u=(d=this.callbacks).onError)==null||u.call(d,m):(y=(c=this.callbacks).onError)==null||y.call(c,new Error(String(m)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let o=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let o=this.ensureSequence(e),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((o,t)=>{var d,u;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,l=(u=t.sequence)!=null?u:0;return i!==l?i-l:o.id.localeCompare(t.id)})}};var Ln=(n,e)=>{var t;let o=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(o).forEach(([r,s])=>{if(s==null||s==="")return;let i=r.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(s))})};import*as jo from"lucide";var le=(n,e=24,o="currentColor",t=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=jo[r];return s?_o(s,e,o,t):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function _o(n,e,o,t){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([u,c])=>{u!=="stroke"&&d.setAttribute(u,String(c))}),r.appendChild(d)}}}),r}var p=(n,e)=>{let o=document.createElement(n);return e&&(o.className=e),o};var Ke={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var vt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var nn=(n,e)=>{let o=p("button");o.type="button",o.innerHTML=`
|
|
8
8
|
<span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
9
9
|
<img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
|
|
@@ -12,20 +12,20 @@ import{Marked as Wo}from"marked";var Mo=n=>{if(n)return n},un=n=>{var o,s;let e=
|
|
|
12
12
|
<span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
15
|
-
`,r.addEventListener("click",e);let t=s=>{var m,x,I,S,Y,P,V,Q,W,le,G,U;let i=(m=s.launcher)!=null?m:{},l=r.querySelector("[data-role='launcher-title']");l&&(l.textContent=(x=i.title)!=null?x:"Chat Assistant");let c=r.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(I=i.subtitle)!=null?I:"Get answers fast");let g=r.querySelector(".tvw-flex-col");g&&(i.textHidden?g.style.display="none":g.style.display="");let d=r.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let z=(S=i.agentIconSize)!=null?S:"40px";if(d.style.height=z,d.style.width=z,d.innerHTML="",i.agentIconName){let ne=parseFloat(z)||24,Z=ve(i.agentIconName,ne*.6,"#ffffff",2);Z?(d.appendChild(Z),d.style.display=""):(d.textContent=(Y=i.agentIconText)!=null?Y:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(P=i.agentIconText)!=null?P:"\u{1F4AC}",d.style.display="")}let A=r.querySelector("[data-role='launcher-image']");if(A){let z=(V=i.agentIconSize)!=null?V:"40px";A.style.height=z,A.style.width=z,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(A.src=i.iconUrl,A.style.display="block"):A.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let z=(Q=i.callToActionIconSize)!=null?Q:"32px";f.style.height=z,f.style.width=z,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 ne=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,ne=(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 Z=parseFloat(z)||24,$=Math.max(Z-ne,8),Ne=ve(i.callToActionIconName,$,"currentColor",2);Ne?f.appendChild(Ne):f.textContent=(W=i.callToActionIconText)!=null?W:"\u2197"}else f.textContent=(le=i.callToActionIconText)!=null?le:"\u2197"}let b=i.position&&bt[i.position]?bt[i.position]:bt["bottom-right"],w="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${w} ${b}`;let q="1px solid #e5e7eb",F="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(G=i.border)!=null?G:q,r.style.boxShadow=(U=i.shadow)!=null?U:F},o=()=>{r.removeEventListener("click",e),r.remove()};return n&&t(n),{element:r,update:t,destroy:o}};var Ut=n=>{var le,G,U,z,ne,Z,$,Ne,Ye,Qe,xt,Ct,D,me,mt,ft,Je,et,M,Le,it,at,Et,wt,$e,tt,qe,j,lt,Ke,We,_e;let{config:e,showClose:r=!0}=n,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(le=e==null?void 0:e.launcher)!=null?le:{},s=(G=o.headerIconSize)!=null?G:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",l=(z=o.closeButtonPlacement)!=null?z:"inline",c=(ne=o.headerIconHidden)!=null?ne:!1,g=o.headerIconName,d=p("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,!c)if(g){let J=parseFloat(s)||24,Se=ve(g,J*.6,"#ffffff",2);Se?d.replaceChildren(Se):d.textContent=($=(Z=e==null?void 0:e.launcher)==null?void 0:Z.agentIconText)!=null?$:"\u{1F4AC}"}else if((Ne=e==null?void 0:e.launcher)!=null&&Ne.iconUrl){let J=p("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=(Qe=(Ye=e==null?void 0:e.launcher)==null?void 0:Ye.agentIconText)!=null?Qe:"\u{1F4AC}";let A=p("div","tvw-flex tvw-flex-col"),f=p("span","tvw-text-base tvw-font-semibold");f.textContent=(Ct=(xt=e==null?void 0:e.launcher)==null?void 0:xt.title)!=null?Ct:"Chat Assistant";let b=p("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(me=(D=e==null?void 0:e.launcher)==null?void 0:D.subtitle)!=null?me:"Here to help you get answers fast",A.append(f,b),c?t.append(A):t.append(d,A);let w=(mt=o.clearChat)!=null?mt:{},q=(ft=w.enabled)!=null?ft:!0,F=(Je=w.placement)!=null?Je:"inline",m=null,x=null;if(q){let J=(et=w.size)!=null?et:"32px",Se=(M=w.iconName)!=null?M:"refresh-cw",Be=(Le=w.iconColor)!=null?Le:"",Ue=(it=w.backgroundColor)!=null?it:"",nt=(at=w.borderWidth)!=null?at:"",St=(Et=w.borderColor)!=null?Et:"",Lt=(wt=w.borderRadius)!=null?wt:"",gt=($e=w.paddingX)!=null?$e:"",At=(tt=w.paddingY)!=null?tt:"",de=(qe=w.tooltipText)!=null?qe:"Clear chat",Nt=(j=w.showTooltip)!=null?j:!0;x=p("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"&&(x.style.right="48px"),m=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),m.style.height=J,m.style.width=J,m.type="button",m.setAttribute("aria-label",de);let Bt=ve(Se,"20px",Be||"",2);if(Bt&&m.appendChild(Bt),Be&&(m.style.color=Be,m.classList.remove("tvw-text-cw-muted")),Ue&&(m.style.backgroundColor=Ue,m.classList.remove("hover:tvw-bg-gray-100")),nt||St){let be=nt||"0px",yt=St||"transparent";m.style.border=`${be} solid ${yt}`,m.classList.remove("tvw-border-none")}if(Lt&&(m.style.borderRadius=Lt,m.classList.remove("tvw-rounded-full")),gt?(m.style.paddingLeft=gt,m.style.paddingRight=gt):(m.style.paddingLeft="",m.style.paddingRight=""),At?(m.style.paddingTop=At,m.style.paddingBottom=At):(m.style.paddingTop="",m.style.paddingBottom=""),x.appendChild(m),Nt&&de&&m&&x){let be=null,yt=()=>{if(be||!m)return;be=p("div","tvw-clear-chat-tooltip"),be.textContent=de;let kt=p("div");kt.className="tvw-clear-chat-tooltip-arrow",be.appendChild(kt);let vt=m.getBoundingClientRect();be.style.position="fixed",be.style.left=`${vt.left+vt.width/2}px`,be.style.top=`${vt.top-8}px`,be.style.transform="translate(-50%, -100%)",document.body.appendChild(be)},Tt=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};x.addEventListener("mouseenter",yt),x.addEventListener("mouseleave",Tt),m.addEventListener("focus",yt),m.addEventListener("blur",Tt),x._cleanupTooltip=()=>{Tt(),x&&(x.removeEventListener("mouseenter",yt),x.removeEventListener("mouseleave",Tt)),m&&(m.removeEventListener("focus",yt),m.removeEventListener("blur",Tt))}}F==="inline"&&t.appendChild(x)}let I=p("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":q&&F==="inline"?"":"tvw-ml-auto"),S=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");S.style.height=i,S.style.width=i,S.type="button";let Y=(lt=o.closeButtonTooltipText)!=null?lt:"Close chat",P=(Ke=o.closeButtonShowTooltip)!=null?Ke:!0;S.setAttribute("aria-label",Y),S.style.display=r?"":"none";let V=(We=o.closeButtonIconName)!=null?We:"x",Q=(_e=o.closeButtonIconText)!=null?_e:"\xD7",W=ve(V,"20px",o.closeButtonColor||"",2);if(W?S.appendChild(W):S.textContent=Q,o.closeButtonColor?(S.style.color=o.closeButtonColor,S.classList.remove("tvw-text-cw-muted")):(S.style.color="",S.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(S.style.backgroundColor=o.closeButtonBackgroundColor,S.classList.remove("hover:tvw-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let J=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";S.style.border=`${J} solid ${Se}`,S.classList.remove("tvw-border-none")}else S.style.border="",S.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(S.style.borderRadius=o.closeButtonBorderRadius,S.classList.remove("tvw-rounded-full")):(S.style.borderRadius="",S.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(S.style.paddingLeft=o.closeButtonPaddingX,S.style.paddingRight=o.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),o.closeButtonPaddingY?(S.style.paddingTop=o.closeButtonPaddingY,S.style.paddingBottom=o.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom=""),I.appendChild(S),P&&Y){let J=null,Se=()=>{if(J)return;J=p("div","tvw-clear-chat-tooltip"),J.textContent=Y;let Ue=p("div");Ue.className="tvw-clear-chat-tooltip-arrow",J.appendChild(Ue);let nt=S.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)},Be=()=>{J&&J.parentNode&&(J.parentNode.removeChild(J),J=null)};I.addEventListener("mouseenter",Se),I.addEventListener("mouseleave",Be),S.addEventListener("focus",Se),S.addEventListener("blur",Be),I._cleanupTooltip=()=>{Be(),I.removeEventListener("mouseenter",Se),I.removeEventListener("mouseleave",Be),S.removeEventListener("focus",Se),S.removeEventListener("blur",Be)}}return l!=="top-right"&&t.appendChild(I),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:b,closeButton:S,closeButtonWrapper:I,clearChatButton:m,clearChatButtonWrapper:x}},sn=(n,e,r)=>{var i,l,c,g;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(l=t.closeButtonPlacement)!=null?l:"inline",s=(g=(c=t.clearChat)==null?void 0:c.placement)!=null?g:"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 uo=n=>Ut({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),go=n=>{var w,q,F,m;let{config:e,showClose:r=!0,onClose:t}=n,o=(w=e==null?void 0:e.launcher)!=null?w:{},s=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(q=o.title)!=null?q:"Chat Assistant",s.appendChild(i);let l=(F=o.closeButtonSize)!=null?F:"32px",c=p("div",""),g=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");g.style.height=l,g.style.width=l,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=r?"":"none";let d=(m=o.closeButtonIconName)!=null?m:"x",A=ve(d,"20px",o.closeButtonColor||"",2);A?g.appendChild(A):g.textContent="\xD7",t&&g.addEventListener("click",t),c.appendChild(g),s.appendChild(c);let f=p("div");f.style.display="none";let b=p("span");return b.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:b,closeButton:g,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}},ho=n=>{var S,Y,P,V,Q,W,le,G;let{config:e,showClose:r=!0,onClose:t,onClearChat:o}=n,s=(S=e==null?void 0:e.launcher)!=null?S:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=p("div","tvw-flex tvw-items-center tvw-gap-3"),c=(Y=s.headerIconSize)!=null?Y:"56px",g=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");g.style.height=c,g.style.width=c;let d=s.headerIconName;if(d){let U=parseFloat(c)||24,z=ve(d,U*.5,"#ffffff",2);z?g.replaceChildren(z):g.textContent=(P=s.agentIconText)!=null?P:"\u{1F4AC}"}else if(s.iconUrl){let U=p("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=c,U.style.width=c,g.replaceChildren(U)}else g.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let A=p("div","tvw-flex tvw-flex-col tvw-flex-1"),f=p("span","tvw-text-lg tvw-font-semibold");f.textContent=(Q=s.title)!=null?Q:"Chat Assistant";let b=p("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(W=s.subtitle)!=null?W:"Here to help you get answers fast",A.append(f,b),l.append(g,A);let w=(le=s.closeButtonSize)!=null?le:"32px",q=p("div",""),F=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");F.style.height=w,F.style.width=w,F.type="button",F.setAttribute("aria-label","Close chat"),F.style.display=r?"":"none";let m=(G=s.closeButtonIconName)!=null?G:"x",x=ve(m,"20px",s.closeButtonColor||"",2);x?F.appendChild(x):F.textContent="\xD7",t&&F.addEventListener("click",t),q.appendChild(F),l.appendChild(q),i.appendChild(l);let I=p("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:g,headerTitle:f,headerSubtitle:b,closeButton:F,closeButtonWrapper:q,clearChatButton:null,clearChatButtonWrapper:null}},Bn={default:uo,minimal:go,expanded:ho},mo=n=>{var e;return(e=Bn[n])!=null?e:Bn.default},kn=(n,e,r)=>{var i,l,c;if(e!=null&&e.render){let g=e.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),d=p("div");d.style.display="none";let A=p("span"),f=p("span"),b=p("button");b.style.display="none";let w=p("div");return w.style.display="none",{header:g,iconHolder:d,headerTitle:A,headerSubtitle:f,closeButton:b,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=mo(t)({config:n,showClose:(c=(l=e==null?void 0:e.showCloseButton)!=null?l:r==null?void 0:r.showClose)!=null?c:!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 Do=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'}},on=n=>{var Z,$,Ne,Ye,Qe,xt,Ct,D,me,mt,ft,Je,et,M,Le,it,at,Et,wt,$e,tt,qe,j,lt,Ke;let{config:e}=n,r=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=((Z=e==null?void 0:e.voiceRecognition)==null?void 0:Z.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),c=p("form",`tvw-widget-composer 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`);c.style.outline="none";let g=p("textarea");g.placeholder=(Ne=($=e==null?void 0:e.copy)==null?void 0:$.inputPlaceholder)!=null?Ne:"Type your message\u2026",g.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",g.rows=1;let d=(Qe=(Ye=e==null?void 0:e.theme)==null?void 0:Ye.inputFontFamily)!=null?Qe:"sans-serif",A=(Ct=(xt=e==null?void 0:e.theme)==null?void 0:xt.inputFontWeight)!=null?Ct:"400";g.style.fontFamily=Do(d),g.style.fontWeight=A,g.style.border="none",g.style.outline="none",g.style.borderWidth="0",g.style.borderStyle="none",g.style.borderColor="transparent",g.addEventListener("focus",()=>{g.style.border="none",g.style.outline="none",g.style.borderWidth="0",g.style.borderStyle="none",g.style.borderColor="transparent",g.style.boxShadow="none"}),g.addEventListener("blur",()=>{g.style.border="none",g.style.outline="none"});let f=(D=e==null?void 0:e.sendButton)!=null?D:{},b=(me=f.useIcon)!=null?me:!1,w=(mt=f.iconText)!=null?mt:"\u2191",q=f.iconName,F=(ft=f.tooltipText)!=null?ft:"Send message",m=(Je=f.showTooltip)!=null?Je:!1,x=(et=f.size)!=null?et:"40px",I=f.backgroundColor,S=f.textColor,Y=p("div","tvw-send-button-wrapper"),P=p("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(P.type="submit",b){if(P.style.width=x,P.style.height=x,P.style.minWidth=x,P.style.minHeight=x,P.style.fontSize="18px",P.style.lineHeight="1",P.innerHTML="",q){let We=parseFloat(x)||24,_e=S&&typeof S=="string"&&S.trim()?S.trim():"currentColor",J=ve(q,We,_e,2);J?(P.appendChild(J),P.style.color=_e):(P.textContent=w,S?P.style.color=S:P.classList.add("tvw-text-white"))}else P.textContent=w,S?P.style.color=S:P.classList.add("tvw-text-white");I?P.style.backgroundColor=I:P.classList.add("tvw-bg-cw-primary")}else P.textContent=(Le=(M=e==null?void 0:e.copy)==null?void 0:M.sendButtonLabel)!=null?Le:"Send",S?P.style.color=S:P.classList.add("tvw-text-white");if(f.borderWidth&&(P.style.borderWidth=f.borderWidth,P.style.borderStyle="solid"),f.borderColor&&(P.style.borderColor=f.borderColor),f.paddingX?(P.style.paddingLeft=f.paddingX,P.style.paddingRight=f.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),f.paddingY?(P.style.paddingTop=f.paddingY,P.style.paddingBottom=f.paddingY):(P.style.paddingTop="",P.style.paddingBottom=""),m&&F){let We=p("div","tvw-send-button-tooltip");We.textContent=F,Y.appendChild(We)}Y.appendChild(P);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},Q=V.enabled===!0,W=null,le=null,G=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Q&&G){le=p("div","tvw-send-button-wrapper"),W=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),W.type="button",W.setAttribute("aria-label","Start voice recognition");let We=(at=V.iconName)!=null?at:"mic",_e=(Et=V.iconSize)!=null?Et:x,J=parseFloat(_e)||24,Se=(wt=V.backgroundColor)!=null?wt:I,Be=($e=V.iconColor)!=null?$e:S;W.style.width=_e,W.style.height=_e,W.style.minWidth=_e,W.style.minHeight=_e,W.style.fontSize="18px",W.style.lineHeight="1";let Ue=Be||"currentColor",nt=ve(We,J,Ue,1.5);nt?(W.appendChild(nt),W.style.color=Ue):(W.textContent="\u{1F3A4}",W.style.color=Ue),Se?W.style.backgroundColor=Se:W.classList.add("tvw-bg-cw-primary"),Be?W.style.color=Be:!Be&&!S&&W.classList.add("tvw-text-white"),V.borderWidth&&(W.style.borderWidth=V.borderWidth,W.style.borderStyle="solid"),V.borderColor&&(W.style.borderColor=V.borderColor),V.paddingX&&(W.style.paddingLeft=V.paddingX,W.style.paddingRight=V.paddingX),V.paddingY&&(W.style.paddingTop=V.paddingY,W.style.paddingBottom=V.paddingY),le.appendChild(W);let St=(tt=V.tooltipText)!=null?tt:"Start voice recognition";if(((qe=V.showTooltip)!=null?qe:!1)&&St){let gt=p("div","tvw-send-button-tooltip");gt.textContent=St,le.appendChild(gt)}}c.addEventListener("click",We=>{We.target!==P&&We.target!==Y&&We.target!==W&&We.target!==le&&g.focus()}),c.append(g),le&&c.append(le),c.append(Y);let U=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),z=(j=e==null?void 0:e.statusIndicator)!=null?j:{},ne=(lt=z.visible)!=null?lt:!0;return U.style.display=ne?"":"none",U.textContent=(Ke=z.idleText)!=null?Ke:"Online",r.append(t,c,U),{footer:r,suggestions:t,composerForm:c,textarea:g,sendButton:P,sendButtonWrapper:Y,micButton:W,micButtonWrapper:le,statusText:U}};var fo=n=>{var c,g,d,A,f,b,w;if(!((g=(c=n==null?void 0:n.launcher)==null?void 0:c.enabled)!=null?g:!0)){let q=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),F=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),m=(A=(d=n==null?void 0:n.launcher)==null?void 0:d.width)!=null?A:"100%";return q.style.width=m,F.style.width="100%",q.appendChild(F),{wrapper:q,panel:F}}let r=(f=n==null?void 0:n.launcher)!=null?f:{},t=r.position&&bt[r.position]?bt[r.position]:bt["bottom-right"],o=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(w=(b=n==null?void 0:n.launcher)==null?void 0:b.width)!=null?w: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}},wo=(n,e=!0)=>{var A,f,b,w,q;let r=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(A=n==null?void 0:n.layout)==null?void 0:A.header,o=t?kn(n,t,{showClose:e}):Ut({config:n,showClose:e}),s=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");s.id="vanilla-agent-scroll-container";let i=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}";let c=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(q=(w=n==null?void 0:n.copy)==null?void 0:w.welcomeSubtitle)!=null?q:"Ask anything about your account or products.",i.append(l,c);let g=p("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,g);let d=on({config:n});return sn(r,o,n),r.append(s,d.footer),{container:r,body:s,messagesWrapper:g,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:c,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 fn=()=>{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},jo=(n,e)=>{let r=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=p("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},yo=(n,e)=>{let r=p("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},rn=(n,e,r)=>{var F,m,x,I,S;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,c=(x=i==null?void 0:i.show)!=null?x:!1,g=(I=s==null?void 0:s.position)!=null?I:"left",d=(S=i==null?void 0:i.position)!=null?S:"below",A=_o(n.role,o),f=p("div",A.join(" ")),b=document.createElement("div");if(b.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),c&&d==="inline"&&n.createdAt){let Y=yo(n,i);Y.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(Y)}if(f.appendChild(b),c&&d==="below"&&n.createdAt){let Y=yo(n,i);Y.classList.add("tvw-mt-1"),f.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=fn();f.appendChild(Y)}if(!l||n.role==="system")return f;let w=p("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),q=jo(s,n.role);return g==="right"||g==="left"&&n.role==="user"?w.append(f,q):w.append(q,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),w},qo=(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}):rn(n,e,r)};var Hn=new Set,Rn=n=>{let e=n.reasoning,r=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return r;let t=Hn.has(n.id),o=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=p("span","tvw-text-xs tvw-text-cw-primary");l.textContent=co(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let c=p("div","tvw-flex tvw-items-center"),d=ve(t?"chevron-up":"chevron-down",16,"currentColor",2);d?c.appendChild(d):c.textContent=t?"Hide":"Show";let A=p("div","tvw-flex tvw-items-center tvw-ml-auto");A.append(c),o.append(s,A);let f=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let b=e.chunks.join(""),w=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");w.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(w);let q=()=>{o.setAttribute("aria-expanded",t?"true":"false"),c.innerHTML="";let x=ve(t?"chevron-up":"chevron-down",16,"currentColor",2);x?c.appendChild(x):c.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},F=()=>{t=!t,t?Hn.add(n.id):Hn.delete(n.id),q()};return o.addEventListener("pointerdown",m=>{m.preventDefault(),F()}),o.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),F())}),q(),r.append(o,f),r};var In=new Set,$n=(n,e)=>{var F;let r=n.toolCall,t=(F=e==null?void 0:e.toolCall)!=null?F:{},o=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(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=In.has(n.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",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=p("div","tvw-flex tvw-flex-col tvw-text-left"),c=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(c.style.color=t.headerTextColor),c.textContent=po(r),l.appendChild(c);let g=p("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",A=ve(s?"chevron-up":"chevron-down",16,d,2);A?g.appendChild(A):g.textContent=s?"Hide":"Show";let f=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(g),i.append(l,f);let b=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=s?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),r.name){let m=p("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,b.appendChild(m)}if(r.args!==void 0){let m=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Arguments";let I=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");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=An(r.args),m.append(x,I),b.appendChild(m)}if(r.chunks&&r.chunks.length){let m=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Activity";let I=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");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(`
|
|
16
|
-
`),m.append(x,I),b.appendChild(m)}if(r.status==="complete"&&r.result!==void 0){let m=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Result";let I=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");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=An(r.result),m.append(x,I),b.appendChild(m)}if(r.status==="complete"&&typeof r.duration=="number"){let m=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${r.duration}ms`,b.appendChild(m)}let w=()=>{i.setAttribute("aria-expanded",s?"true":"false"),g.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",x=ve(s?"chevron-up":"chevron-down",16,m,2);x?g.appendChild(x):g.textContent=s?"Hide":"Show",b.style.display=s?"":"none"},q=()=>{s=!s,s?In.add(n.id):In.delete(n.id),w()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),q()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),q())}),w(),o.append(i,b),o};var vo=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(b=>b.role==="user"))return;let d=document.createDocumentFragment(),A=o?o.isStreaming():!1,f=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let w=p("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");w.type="button",w.textContent=b,w.disabled=A,l!=null&&l.fontFamily&&(w.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(w.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(w.style.paddingLeft=l.paddingX,w.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(w.style.paddingTop=l.paddingY,w.style.paddingBottom=l.paddingY),w.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(b))}),d.appendChild(w),e.push(w)}),n.appendChild(d)}}};var bo={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"}},Pn=(n,e,r,t)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,q,F;if(s.dataset.enhanced==="true")return;let i=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let l=(q=bo[i])!=null?q:bo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let c=p("div","tvw-space-y-1"),g=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(g.textContent=l.title,c.appendChild(g),l.description){let m=p("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,c.appendChild(m)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var P,V;let x=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");x.htmlFor=`${e.id}-${i}-${m.name}`;let I=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=m.label,x.appendChild(I);let S=(P=m.type)!=null?P:"text",Y;S==="textarea"?(Y=document.createElement("textarea"),Y.rows=3):(Y=document.createElement("input"),Y.type=S),Y.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",Y.id=`${e.id}-${i}-${m.name}`,Y.name=m.name,Y.placeholder=(V=m.placeholder)!=null?V:"",m.required&&(Y.required=!0),x.appendChild(Y),d.appendChild(x)});let A=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(F=l.submitLabel)!=null?F:"Submit",A.appendChild(f),A.appendChild(b),d.appendChild(A),s.replaceChildren(c,d),d.addEventListener("submit",async m=>{var Y,P;m.preventDefault();let x=(Y=r.formEndpoint)!=null?Y:"/form",I=new FormData(d),S={};I.forEach((V,Q)=>{S[Q]=V}),S.type=i,b.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let Q=await V.json();f.textContent=(P=Q.message)!=null?P:"Thanks! We'll be in touch soon.",Q.success&&Q.nextPrompt&&await t.sendMessage(String(Q.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var On=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,c;return((l=i.priority)!=null?l:0)-((c=s.priority)!=null?c:0)})}clear(){this.plugins.forEach(e=>{var r;return(r=e.onUnregister)==null?void 0:r.call(e)}),this.plugins.clear()}},wn=new On;var Ie={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))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},debug:!1};function Nn(n){var e,r,t,o,s,i,l,c,g,d,A,f,b,w,q,F,m,x,I;return n?{...Ie,...n,theme:{...Ie.theme,...n.theme},launcher:{...Ie.launcher,...n.launcher,clearChat:{...(e=Ie.launcher)==null?void 0:e.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...Ie.copy,...n.copy},sendButton:{...Ie.sendButton,...n.sendButton},statusIndicator:{...Ie.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ie.voiceRecognition,...n.voiceRecognition},features:{...Ie.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Ie.suggestionChips,suggestionChipsConfig:{...Ie.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ie.layout,...n.layout,header:{...(o=Ie.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Ie.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(g=(c=Ie.layout)==null?void 0:c.messages)==null?void 0:g.avatar,...(A=(d=n.layout)==null?void 0:d.messages)==null?void 0:A.avatar},timestamp:{...(b=(f=Ie.layout)==null?void 0:f.messages)==null?void 0:b.timestamp,...(q=(w=n.layout)==null?void 0:w.messages)==null?void 0:q.timestamp}},slots:{...(F=Ie.layout)==null?void 0:F.slots,...(m=n.layout)==null?void 0:m.slots}},markdown:{...Ie.markdown,...n.markdown,options:{...(x=Ie.markdown)==null?void 0:x.options,...(I=n.markdown)==null?void 0:I.options}}}:Ie}var xo=()=>{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(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var Uo=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},zo=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},yn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Uo(n),r=zo(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}},Fn=n=>typeof n=="string"?n:n==null?"":String(n),Xt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Fn(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,t=Fn(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:Fn(r.text)}}},Co=n=>Array.isArray(n)?n.map(e=>String(e)):[],vn=n=>{let e=new Set(Co(n.getMetadata().processedActionMessageIds)),r=()=>{e=new Set(Co(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((g,d)=>g||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let c={action:l,message:s.message};n.emit("action:detected",c);for(let g of n.handlers)if(g)try{let d=g(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let A=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:A}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:r}};var Yo=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}},Jo=n=>n.map(e=>({...e,streaming:!1})),Dn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=e();return r?Yo(r.getItem(n)):null},save:r=>{let t=e();if(t)try{let o={...r,messages:r.messages?Jo(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 jn=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)})}},an=new jn;import{parse as Ko,STR as Xo,OBJ as Vo}from"partial-json";function Go(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(!Go(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 _n(){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=Ko(r,Xo|Vo),s=Zo(o,r);s&&(n=s)}catch{}return e=r.length,n},reset:()=>{n=null,e=0}}}function Qo(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function qn(n,e){let{config:r,message:t,onPropsUpdate:o}=e,s=an.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 er(){let n=_n();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Un(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 zn(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 Vt="vanilla-agent-chat-history",tr=30*1e3,Yn=n=>!n||typeof n!="object"?{}:{...n},So=n=>n.map(e=>({...e,streaming:!1})),Ao=(n,e)=>{let r=n!=null&&n.markdown?gn(n.markdown):null;return t=>{var i,l,c;let o=(i=t.text)!=null?i:"",s=(l=t.message.rawContent)!=null?l:null;if(e){let g=e.process({text:o,raw:s!=null?s:o,message:t.message,streaming:t.streaming});g!==null&&(o=g.text,g.persist||(t.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...t,text:o,raw:(c=s!=null?s:t.text)!=null?c:""}):r?r(o):Sn(o)}},Jn=(n,e,r)=>{var ae,pe,He,ue,Fe,rt,ht,Xn,Vn,Gn,Zn,Qn,es,ts;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Nn(e),o=wn.getForInstance(t.plugins);t.components&&an.registerAll(t.components);let s=xo(),i=(ae=t.storageAdapter)!=null?ae:Dn(),l={},c=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")c=a;else if(a){let u=a;u.metadata&&(l=Yn(u.metadata)),(pe=u.messages)!=null&&pe.length&&(t={...t,initialMessages:u.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let g=()=>l,d=a=>{var T;l=(T=a({...l}))!=null?T:{},kt()},A=t.actionParsers&&t.actionParsers.length?t.actionParsers:[yn],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Xt.message,Xt.messageAndClick],b=vn({parsers:A,handlers:f,getMetadata:g,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let w=(ue=(He=t.launcher)==null?void 0:He.enabled)!=null?ue:!0,q=(rt=(Fe=t.launcher)==null?void 0:Fe.autoExpand)!=null?rt:!1,F=q,m=w,x=w?q:!0,I=Ao(t,b),S=(Xn=(ht=t.features)==null?void 0:ht.showReasoning)!=null?Xn:!0,Y=(Gn=(Vn=t.features)==null?void 0:Vn.showToolCalls)!=null?Gn:!0,P=(Zn=t.statusIndicator)!=null?Zn:{},V=a=>{var u,T,O,R;return a==="idle"?(u=P.idleText)!=null?u:ze.idle:a==="connecting"?(T=P.connectingText)!=null?T:ze.connecting:a==="connected"?(O=P.connectedText)!=null?O:ze.connected:a==="error"?(R=P.errorText)!=null?R:ze.error:ze[a]},{wrapper:Q,panel:W}=fo(t),le=wo(t,w),{container:G,body:U,messagesWrapper:z,suggestions:ne,textarea:Z,sendButton:$,sendButtonWrapper:Ne,composerForm:Ye,statusText:Qe,introTitle:xt,introSubtitle:Ct,closeButton:D,iconHolder:me,headerTitle:mt,headerSubtitle:ft,header:Je,footer:et}=le,M=le.micButton,Le=le.micButtonWrapper,it=o.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let u=Ut({config:t,showClose:w});return sn(G,u,t),u.header},onClose:()=>st(!1,"user")});if(a){let u=G.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(a),Je=a)}}let at=o.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>on({config:t}).footer,onSubmit:u=>{j&&!j.isStreaming()&&j.sendMessage(u)},disabled:!1});a&&(et.replaceWith(a),et=a)}(()=>{var O,R;let a=(R=(O=t.layout)==null?void 0:O.slots)!=null?R:{},u=se=>{switch(se){case"body-top":return G.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return z;case"footer-top":return ne;case"composer":return Ye;case"footer-bottom":return Qe;default:return null}},T=(se,H)=>{var v;switch(se){case"header-left":case"header-center":case"header-right":if(se==="header-left")Je.insertBefore(H,Je.firstChild);else if(se==="header-right")Je.appendChild(H);else{let N=Je.querySelector(".tvw-flex-col");N?(v=N.parentNode)==null||v.insertBefore(H,N.nextSibling):Je.appendChild(H)}break;case"body-top":let X=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");X?X.replaceWith(H):U.insertBefore(H,U.firstChild);break;case"body-bottom":U.appendChild(H);break;case"footer-top":ne.replaceWith(H);break;case"footer-bottom":Qe.replaceWith(H);break;default:break}};for(let[se,H]of Object.entries(a))if(H)try{let v=H({config:t,defaultContent:()=>u(se)});v&&T(se,v)}catch(v){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${se}":`,v)}})(),W.appendChild(G),n.appendChild(Q);let wt=()=>{var re,Re,dt,ie,ct,Ht,Rt,Mt,jt,It,_t,pt,$t,Pt,pn,en;let a=(Re=(re=t.launcher)==null?void 0:re.sidebarMode)!=null?Re:!1,u=a||((ie=(dt=t.launcher)==null?void 0:dt.fullHeight)!=null?ie:!1),T=(ct=t.theme)!=null?ct:{},O=(Rt=(Ht=t.launcher)==null?void 0:Ht.position)!=null?Rt:"bottom-left",R=O==="bottom-left"||O==="top-left",se=a?"none":"1px solid var(--tvw-cw-border)",H=a?R?"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)",v=a?"0":"16px",X=(Mt=T.panelBorder)!=null?Mt:se,N=(jt=T.panelShadow)!=null?jt:H,B=(It=T.panelBorderRadius)!=null?It:v;n.style.cssText="",Q.style.cssText="",W.style.cssText="",G.style.cssText="",U.style.cssText="",et.style.cssText="";let _=(pt=(_t=t==null?void 0:t.launcher)==null?void 0:_t.width)!=null?pt:t==null?void 0:t.launcherWidth,Me=_!=null?_:"min(400px, calc(100vw - 24px))";a||(W.style.width=Me,W.style.maxWidth=Me),W.style.boxShadow=N,W.style.borderRadius=B,G.style.border=X,G.style.borderRadius=B;let ge=(($t=t.launcher)==null?void 0:$t.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",Q.style.display="flex",Q.style.flexDirection="column",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.maxHeight="100%",Q.style.height="100%",ge&&(Q.style.overflow="hidden"),W.style.display="flex",W.style.flexDirection="column",W.style.flex="1 1 0%",W.style.minHeight="0",W.style.maxHeight="100%",W.style.height="100%",W.style.overflow="hidden",G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",et.style.flexShrink="0"),Q.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!a&&!ge&&((Pt=bt[O])!=null?Pt:bt["bottom-right"]).split(" ").forEach(Yt=>Q.classList.add(Yt)),a){let qt=(en=(pn=t.launcher)==null?void 0:pn.sidebarWidth)!=null?en:"420px";Q.style.cssText=`
|
|
15
|
+
`,o.addEventListener("click",e);let t=s=>{var h,x,R,w,K,T,O,ee,P,Y,fe,J;let i=(h=s.launcher)!=null?h:{},l=o.querySelector("[data-role='launcher-title']");l&&(l.textContent=(x=i.title)!=null?x:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(R=i.subtitle)!=null?R:"Get answers fast");let u=o.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let c=o.querySelector("[data-role='launcher-icon']");if(c)if(i.agentIconHidden)c.style.display="none";else{let F=(w=i.agentIconSize)!=null?w:"40px";if(c.style.height=F,c.style.width=F,c.innerHTML="",i.agentIconName){let ne=parseFloat(F)||24,De=le(i.agentIconName,ne*.6,"#ffffff",2);De?(c.appendChild(De),c.style.display=""):(c.textContent=(K=i.agentIconText)!=null?K:"\u{1F4AC}",c.style.display="")}else i.iconUrl?c.style.display="none":(c.textContent=(T=i.agentIconText)!=null?T:"\u{1F4AC}",c.style.display="")}let y=o.querySelector("[data-role='launcher-image']");if(y){let F=(O=i.agentIconSize)!=null?O:"40px";y.style.height=F,y.style.width=F,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let m=o.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let F=(ee=i.callToActionIconSize)!=null?ee:"32px";m.style.height=F,m.style.width=F,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("tvw-bg-cw-primary")):(m.style.backgroundColor="",m.classList.add("tvw-bg-cw-primary"));let ne=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,ne=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display="",m.innerHTML="",i.callToActionIconName){let De=parseFloat(F)||24,oe=Math.max(De-ne,8),$=le(i.callToActionIconName,oe,"currentColor",2);$?m.appendChild($):m.textContent=(P=i.callToActionIconText)!=null?P:"\u2197"}else m.textContent=(Y=i.callToActionIconText)!=null?Y:"\u2197"}let b=i.position&&vt[i.position]?vt[i.position]:vt["bottom-right"],f="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${f} ${b}`;let D="1px solid #e5e7eb",j="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(fe=i.border)!=null?fe:D,o.style.boxShadow=(J=i.shadow)!=null?J:j},r=()=>{o.removeEventListener("click",e),o.remove()};return n&&t(n),{element:o,update:t,destroy:r}};var zt=n=>{var Y,fe,J,F,ne,De,oe,$,qe,Xe,tt,bt,Ct,q,he,mt,ft,Ve,nt,L,Re,it,at,Tt,wt,$e,st,Ue,U,lt,Ae,Oe;let{config:e,showClose:o=!0}=n,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(Y=e==null?void 0:e.launcher)!=null?Y:{},s=(fe=r.headerIconSize)!=null?fe:"48px",i=(J=r.closeButtonSize)!=null?J:"32px",l=(F=r.closeButtonPlacement)!=null?F:"inline",d=(ne=r.headerIconHidden)!=null?ne:!1,u=r.headerIconName,c=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(c.style.height=s,c.style.width=s,!d)if(u){let Z=parseFloat(s)||24,Te=le(u,Z*.6,"#ffffff",2);Te?c.replaceChildren(Te):c.textContent=(oe=(De=e==null?void 0:e.launcher)==null?void 0:De.agentIconText)!=null?oe:"\u{1F4AC}"}else if(($=e==null?void 0:e.launcher)!=null&&$.iconUrl){let Z=p("img");Z.src=e.launcher.iconUrl,Z.alt="",Z.className="tvw-rounded-xl tvw-object-cover",Z.style.height=s,Z.style.width=s,c.replaceChildren(Z)}else c.textContent=(Xe=(qe=e==null?void 0:e.launcher)==null?void 0:qe.agentIconText)!=null?Xe:"\u{1F4AC}";let y=p("div","tvw-flex tvw-flex-col"),m=p("span","tvw-text-base tvw-font-semibold");m.textContent=(bt=(tt=e==null?void 0:e.launcher)==null?void 0:tt.title)!=null?bt:"Chat Assistant";let b=p("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(q=(Ct=e==null?void 0:e.launcher)==null?void 0:Ct.subtitle)!=null?q:"Here to help you get answers fast",y.append(m,b),d?t.append(y):t.append(c,y);let f=(he=r.clearChat)!=null?he:{},D=(mt=f.enabled)!=null?mt:!0,j=(ft=f.placement)!=null?ft:"inline",h=null,x=null;if(D){let Z=(Ve=f.size)!=null?Ve:"32px",Te=(nt=f.iconName)!=null?nt:"refresh-cw",Ee=(L=f.iconColor)!=null?L:"",ze=(Re=f.backgroundColor)!=null?Re:"",Je=(it=f.borderWidth)!=null?it:"",xt=(at=f.borderColor)!=null?at:"",kt=(Tt=f.borderRadius)!=null?Tt:"",yt=(wt=f.paddingX)!=null?wt:"",Et=($e=f.paddingY)!=null?$e:"",St=(st=f.tooltipText)!=null?st:"Clear chat",we=(Ue=f.showTooltip)!=null?Ue:!0;x=p("div",j==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),j==="top-right"&&(x.style.right="48px"),h=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),h.style.height=Z,h.style.width=Z,h.type="button",h.setAttribute("aria-label",St);let Bt=le(Te,"20px",Ee||"",2);if(Bt&&h.appendChild(Bt),Ee&&(h.style.color=Ee,h.classList.remove("tvw-text-cw-muted")),ze&&(h.style.backgroundColor=ze,h.classList.remove("hover:tvw-bg-gray-100")),Je||xt){let ke=Je||"0px",Ye=xt||"transparent";h.style.border=`${ke} solid ${Ye}`,h.classList.remove("tvw-border-none")}if(kt&&(h.style.borderRadius=kt,h.classList.remove("tvw-rounded-full")),yt?(h.style.paddingLeft=yt,h.style.paddingRight=yt):(h.style.paddingLeft="",h.style.paddingRight=""),Et?(h.style.paddingTop=Et,h.style.paddingBottom=Et):(h.style.paddingTop="",h.style.paddingBottom=""),x.appendChild(h),we&&St&&h&&x){let ke=null,Ye=()=>{if(ke||!h)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=St;let Ft=p("div");Ft.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(Ft);let Wt=h.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${Wt.left+Wt.width/2}px`,ke.style.top=`${Wt.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},At=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};x.addEventListener("mouseenter",Ye),x.addEventListener("mouseleave",At),h.addEventListener("focus",Ye),h.addEventListener("blur",At),x._cleanupTooltip=()=>{At(),x&&(x.removeEventListener("mouseenter",Ye),x.removeEventListener("mouseleave",At)),h&&(h.removeEventListener("focus",Ye),h.removeEventListener("blur",At))}}j==="inline"&&t.appendChild(x)}let R=p("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":D&&j==="inline"?"":"tvw-ml-auto"),w=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");w.style.height=i,w.style.width=i,w.type="button";let K=(U=r.closeButtonTooltipText)!=null?U:"Close chat",T=(lt=r.closeButtonShowTooltip)!=null?lt:!0;w.setAttribute("aria-label",K),w.style.display=o?"":"none";let O=(Ae=r.closeButtonIconName)!=null?Ae:"x",ee=(Oe=r.closeButtonIconText)!=null?Oe:"\xD7",P=le(O,"20px",r.closeButtonColor||"",2);if(P?w.appendChild(P):w.textContent=ee,r.closeButtonColor?(w.style.color=r.closeButtonColor,w.classList.remove("tvw-text-cw-muted")):(w.style.color="",w.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(w.style.backgroundColor=r.closeButtonBackgroundColor,w.classList.remove("hover:tvw-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let Z=r.closeButtonBorderWidth||"0px",Te=r.closeButtonBorderColor||"transparent";w.style.border=`${Z} solid ${Te}`,w.classList.remove("tvw-border-none")}else w.style.border="",w.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(w.style.borderRadius=r.closeButtonBorderRadius,w.classList.remove("tvw-rounded-full")):(w.style.borderRadius="",w.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(w.style.paddingLeft=r.closeButtonPaddingX,w.style.paddingRight=r.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),r.closeButtonPaddingY?(w.style.paddingTop=r.closeButtonPaddingY,w.style.paddingBottom=r.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),R.appendChild(w),T&&K){let Z=null,Te=()=>{if(Z)return;Z=p("div","tvw-clear-chat-tooltip"),Z.textContent=K;let ze=p("div");ze.className="tvw-clear-chat-tooltip-arrow",Z.appendChild(ze);let Je=w.getBoundingClientRect();Z.style.position="fixed",Z.style.left=`${Je.left+Je.width/2}px`,Z.style.top=`${Je.top-8}px`,Z.style.transform="translate(-50%, -100%)",document.body.appendChild(Z)},Ee=()=>{Z&&Z.parentNode&&(Z.parentNode.removeChild(Z),Z=null)};R.addEventListener("mouseenter",Te),R.addEventListener("mouseleave",Ee),w.addEventListener("focus",Te),w.addEventListener("blur",Ee),R._cleanupTooltip=()=>{Ee(),R.removeEventListener("mouseenter",Te),R.removeEventListener("mouseleave",Ee),w.removeEventListener("focus",Te),w.removeEventListener("blur",Ee)}}return l!=="top-right"&&t.appendChild(R),{header:t,iconHolder:c,headerTitle:m,headerSubtitle:b,closeButton:w,closeButtonWrapper:R,clearChatButton:h,clearChatButtonWrapper:x}},sn=(n,e,o)=>{var i,l,d,u;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(l=t.closeButtonPlacement)!=null?l:"inline",s=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"inline";n.appendChild(e.header),r==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var go=n=>zt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),ho=n=>{var f,D,j,h;let{config:e,showClose:o=!0,onClose:t}=n,r=(f=e==null?void 0:e.launcher)!=null?f:{},s=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(D=r.title)!=null?D:"Chat Assistant",s.appendChild(i);let l=(j=r.closeButtonSize)!=null?j:"32px",d=p("div",""),u=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");u.style.height=l,u.style.width=l,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=o?"":"none";let c=(h=r.closeButtonIconName)!=null?h:"x",y=le(c,"20px",r.closeButtonColor||"",2);y?u.appendChild(y):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),s.appendChild(d);let m=p("div");m.style.display="none";let b=p("span");return b.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:b,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},mo=n=>{var w,K,T,O,ee,P,Y,fe;let{config:e,showClose:o=!0,onClose:t,onClearChat:r}=n,s=(w=e==null?void 0:e.launcher)!=null?w:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=p("div","tvw-flex tvw-items-center tvw-gap-3"),d=(K=s.headerIconSize)!=null?K:"56px",u=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");u.style.height=d,u.style.width=d;let c=s.headerIconName;if(c){let J=parseFloat(d)||24,F=le(c,J*.5,"#ffffff",2);F?u.replaceChildren(F):u.textContent=(T=s.agentIconText)!=null?T:"\u{1F4AC}"}else if(s.iconUrl){let J=p("img");J.src=s.iconUrl,J.alt="",J.className="tvw-rounded-xl tvw-object-cover",J.style.height=d,J.style.width=d,u.replaceChildren(J)}else u.textContent=(O=s.agentIconText)!=null?O:"\u{1F4AC}";let y=p("div","tvw-flex tvw-flex-col tvw-flex-1"),m=p("span","tvw-text-lg tvw-font-semibold");m.textContent=(ee=s.title)!=null?ee:"Chat Assistant";let b=p("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(P=s.subtitle)!=null?P:"Here to help you get answers fast",y.append(m,b),l.append(u,y);let f=(Y=s.closeButtonSize)!=null?Y:"32px",D=p("div",""),j=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");j.style.height=f,j.style.width=f,j.type="button",j.setAttribute("aria-label","Close chat"),j.style.display=o?"":"none";let h=(fe=s.closeButtonIconName)!=null?fe:"x",x=le(h,"20px",s.closeButtonColor||"",2);x?j.appendChild(x):j.textContent="\xD7",t&&j.addEventListener("click",t),D.appendChild(j),l.appendChild(D),i.appendChild(l);let R=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return R.textContent="Online and ready to help",i.appendChild(R),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:b,closeButton:j,closeButtonWrapper:D,clearChatButton:null,clearChatButtonWrapper:null}},kn={default:go,minimal:ho,expanded:mo},fo=n=>{var e;return(e=kn[n])!=null?e:kn.default},Bn=(n,e,o)=>{var i,l,d;if(e!=null&&e.render){let u=e.render({config:n,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),c=p("div");c.style.display="none";let y=p("span"),m=p("span"),b=p("button");b.style.display="none";let f=p("div");return f.style.display="none",{header:u,iconHolder:c,headerTitle:y,headerSubtitle:m,closeButton:b,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=fo(t)({config:n,showClose:(d=(l=e==null?void 0:e.showCloseButton)!=null?l:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.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 qo=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'}},on=n=>{var De,oe,$,qe,Xe,tt,bt,Ct,q,he,mt,ft,Ve,nt,L,Re,it,at,Tt,wt,$e,st,Ue,U,lt;let{config:e}=n,o=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((De=e==null?void 0:e.voiceRecognition)==null?void 0:De.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=p("form",`tvw-widget-composer 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`);d.style.outline="none";let u=p("textarea");u.placeholder=($=(oe=e==null?void 0:e.copy)==null?void 0:oe.inputPlaceholder)!=null?$:"Type your message\u2026",u.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",u.rows=1;let c=(Xe=(qe=e==null?void 0:e.theme)==null?void 0:qe.inputFontFamily)!=null?Xe:"sans-serif",y=(bt=(tt=e==null?void 0:e.theme)==null?void 0:tt.inputFontWeight)!=null?bt:"400";u.style.fontFamily=qo(c),u.style.fontWeight=y,u.style.border="none",u.style.outline="none",u.style.borderWidth="0",u.style.borderStyle="none",u.style.borderColor="transparent",u.addEventListener("focus",()=>{u.style.border="none",u.style.outline="none",u.style.borderWidth="0",u.style.borderStyle="none",u.style.borderColor="transparent",u.style.boxShadow="none"}),u.addEventListener("blur",()=>{u.style.border="none",u.style.outline="none"});let m=(Ct=e==null?void 0:e.sendButton)!=null?Ct:{},b=(q=m.useIcon)!=null?q:!1,f=(he=m.iconText)!=null?he:"\u2191",D=m.iconName,j=(mt=m.tooltipText)!=null?mt:"Send message",h=(ft=m.showTooltip)!=null?ft:!1,x=(Ve=m.size)!=null?Ve:"40px",R=m.backgroundColor,w=m.textColor,K=p("div","tvw-send-button-wrapper"),T=p("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(T.type="submit",b){if(T.style.width=x,T.style.height=x,T.style.minWidth=x,T.style.minHeight=x,T.style.fontSize="18px",T.style.lineHeight="1",T.innerHTML="",D){let Ae=parseFloat(x)||24,Oe=w&&typeof w=="string"&&w.trim()?w.trim():"currentColor",Z=le(D,Ae,Oe,2);Z?(T.appendChild(Z),T.style.color=Oe):(T.textContent=f,w?T.style.color=w:T.classList.add("tvw-text-white"))}else T.textContent=f,w?T.style.color=w:T.classList.add("tvw-text-white");R?T.style.backgroundColor=R:T.classList.add("tvw-bg-cw-primary")}else T.textContent=(L=(nt=e==null?void 0:e.copy)==null?void 0:nt.sendButtonLabel)!=null?L:"Send",w?T.style.color=w:T.classList.add("tvw-text-white");if(m.borderWidth&&(T.style.borderWidth=m.borderWidth,T.style.borderStyle="solid"),m.borderColor&&(T.style.borderColor=m.borderColor),m.paddingX?(T.style.paddingLeft=m.paddingX,T.style.paddingRight=m.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),m.paddingY?(T.style.paddingTop=m.paddingY,T.style.paddingBottom=m.paddingY):(T.style.paddingTop="",T.style.paddingBottom=""),h&&j){let Ae=p("div","tvw-send-button-tooltip");Ae.textContent=j,K.appendChild(Ae)}K.appendChild(T);let O=(Re=e==null?void 0:e.voiceRecognition)!=null?Re:{},ee=O.enabled===!0,P=null,Y=null,fe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(ee&&fe){Y=p("div","tvw-send-button-wrapper"),P=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),P.type="button",P.setAttribute("aria-label","Start voice recognition");let Ae=(it=O.iconName)!=null?it:"mic",Oe=(at=O.iconSize)!=null?at:x,Z=parseFloat(Oe)||24,Te=(Tt=O.backgroundColor)!=null?Tt:R,Ee=(wt=O.iconColor)!=null?wt:w;P.style.width=Oe,P.style.height=Oe,P.style.minWidth=Oe,P.style.minHeight=Oe,P.style.fontSize="18px",P.style.lineHeight="1";let ze=Ee||"currentColor",Je=le(Ae,Z,ze,1.5);Je?(P.appendChild(Je),P.style.color=ze):(P.textContent="\u{1F3A4}",P.style.color=ze),Te?P.style.backgroundColor=Te:P.classList.add("tvw-bg-cw-primary"),Ee?P.style.color=Ee:!Ee&&!w&&P.classList.add("tvw-text-white"),O.borderWidth&&(P.style.borderWidth=O.borderWidth,P.style.borderStyle="solid"),O.borderColor&&(P.style.borderColor=O.borderColor),O.paddingX&&(P.style.paddingLeft=O.paddingX,P.style.paddingRight=O.paddingX),O.paddingY&&(P.style.paddingTop=O.paddingY,P.style.paddingBottom=O.paddingY),Y.appendChild(P);let xt=($e=O.tooltipText)!=null?$e:"Start voice recognition";if(((st=O.showTooltip)!=null?st:!1)&&xt){let yt=p("div","tvw-send-button-tooltip");yt.textContent=xt,Y.appendChild(yt)}}d.addEventListener("click",Ae=>{Ae.target!==T&&Ae.target!==K&&Ae.target!==P&&Ae.target!==Y&&u.focus()}),d.append(u),Y&&d.append(Y),d.append(K);let J=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),F=(Ue=e==null?void 0:e.statusIndicator)!=null?Ue:{},ne=(U=F.visible)!=null?U:!0;return J.style.display=ne?"":"none",J.textContent=(lt=F.idleText)!=null?lt:"Online",o.append(t,d,J),{footer:o,suggestions:t,composerForm:d,textarea:u,sendButton:T,sendButtonWrapper:K,micButton:P,micButtonWrapper:Y,statusText:J}};var wo=n=>{var d,u,c,y,m,b,f;if(!((u=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?u:!0)){let D=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),j=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),h=(y=(c=n==null?void 0:n.launcher)==null?void 0:c.width)!=null?y:"100%";return D.style.width=h,j.style.width="100%",D.appendChild(j),{wrapper:D,panel:j}}let o=(m=n==null?void 0:n.launcher)!=null?m:{},t=o.position&&vt[o.position]?vt[o.position]:vt["bottom-right"],r=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(f=(b=n==null?void 0:n.launcher)==null?void 0:b.width)!=null?f:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,r.appendChild(s),{wrapper:r,panel:s}},yo=(n,e=!0)=>{var y,m,b,f,D;let o=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(y=n==null?void 0:n.layout)==null?void 0:y.header,r=t?Bn(n,t,{showClose:e}):zt({config:n,showClose:e}),s=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");s.id="vanilla-agent-scroll-container";let i=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(m=n==null?void 0:n.copy)==null?void 0:m.welcomeTitle)!=null?b:"Hello \u{1F44B}";let d=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");d.textContent=(D=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",i.append(l,d);let u=p("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,u);let c=on({config:n});return sn(o,r,n),o.append(s,c.footer),{container:o,body:s,messagesWrapper:u,suggestions:c.suggestions,textarea:c.textarea,sendButton:c.sendButton,sendButtonWrapper:c.sendButtonWrapper,micButton:c.micButton,micButtonWrapper:c.micButtonWrapper,composerForm:c.composerForm,statusText:c.statusText,introTitle:l,introSubtitle:d,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:c.footer}};var fn=()=>{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 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 t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(e),n.appendChild(o),n.appendChild(t),n.appendChild(r),n},Uo=(n,e)=>{let o=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=p("img");r.src=t,r.alt=e==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=e==="user"?"U":"A",o.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},vo=(n,e)=>{let o=p("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?o.textContent=e.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},zo=(n,e="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="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"),n==="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"),n==="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},bo=(n,e,o)=>{var f,D,j,h,x,R;let t=(f=e.showCopy)!=null?f:!0,r=(D=e.showUpvote)!=null?D:!0,s=(j=e.showDownvote)!=null?j:!0,i=(h=e.visibility)!=null?h:"hover",l=(x=e.align)!=null?x:"right",d=(R=e.layout)!=null?R:"pill-inside",u={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],c={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],y=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${c} ${i==="hover"?"tvw-message-actions-hover":""}`),m=null,b=(w,K,T,O)=>{let ee=document.createElement("button");ee.className="tvw-message-action-btn",ee.setAttribute("aria-label",K),ee.setAttribute("title",K),O&&ee.setAttribute("data-action",O);let P=le(w,14,"currentColor",2);return P&&ee.appendChild(P),ee.addEventListener("click",Y=>{Y.preventDefault(),Y.stopPropagation(),T()}),ee};if(t){let w=b("copy","Copy message",()=>{let K=n.content||"";navigator.clipboard.writeText(K).then(()=>{w.classList.add("tvw-message-action-success");let T=le("check",14,"currentColor",2);T&&(w.innerHTML="",w.appendChild(T)),setTimeout(()=>{w.classList.remove("tvw-message-action-success");let O=le("copy",14,"currentColor",2);O&&(w.innerHTML="",w.appendChild(O))},2e3)}).catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",T)}),o!=null&&o.onCopy&&o.onCopy(n),e.onCopy&&e.onCopy(n)},"copy");y.appendChild(w)}if(r){let w=b("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,w.classList.remove("tvw-message-action-active");else{let T=y.querySelector('[data-action="downvote"]');T&&T.classList.remove("tvw-message-action-active"),m="upvote",w.classList.add("tvw-message-action-active");let O={type:"upvote",messageId:n.id,message:n};o!=null&&o.onFeedback&&o.onFeedback(O),e.onFeedback&&e.onFeedback(O)}},"upvote");y.appendChild(w)}if(s){let w=b("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,w.classList.remove("tvw-message-action-active");else{let T=y.querySelector('[data-action="upvote"]');T&&T.classList.remove("tvw-message-action-active"),m="downvote",w.classList.add("tvw-message-action-active");let O={type:"downvote",messageId:n.id,message:n};o!=null&&o.onFeedback&&o.onFeedback(O),e.onFeedback&&e.onFeedback(O)}},"downvote");y.appendChild(w)}return y},rn=(n,e,o,t,r)=>{var R,w,K,T,O;let s=o!=null?o:{},i=(R=s.layout)!=null?R:"bubble",l=s.avatar,d=s.timestamp,u=(w=l==null?void 0:l.show)!=null?w:!1,c=(K=d==null?void 0:d.show)!=null?K:!1,y=(T=l==null?void 0:l.position)!=null?T:"left",m=(O=d==null?void 0:d.position)!=null?O:"below",b=zo(n.role,i),f=p("div",b.join(" ")),D=document.createElement("div");if(D.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),c&&m==="inline"&&n.createdAt){let ee=vo(n,d);ee.classList.add("tvw-ml-2","tvw-inline"),D.appendChild(ee)}if(f.appendChild(D),c&&m==="below"&&n.createdAt){let ee=vo(n,d);ee.classList.add("tvw-mt-1"),f.appendChild(ee)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let ee=fn();f.appendChild(ee)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let ee=bo(n,t,r);f.appendChild(ee)}if(!u||n.role==="system")return f;let h=p("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),x=Uo(l,n.role);return y==="right"||y==="left"&&n.role==="user"?h.append(f,x):h.append(x,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),h},Jo=(n,e,o,t,r)=>{let s=o!=null?o:{};return n.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):rn(n,e,o,t,r)};var Hn=new Set,Rn=n=>{let e=n.reasoning,o=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return o;let t=Hn.has(n.id),r=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=p("span","tvw-text-xs tvw-text-cw-primary");l.textContent=po(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),c=le(t?"chevron-up":"chevron-down",16,"currentColor",2);c?d.appendChild(c):d.textContent=t?"Hide":"Show";let y=p("div","tvw-flex tvw-items-center tvw-ml-auto");y.append(d),r.append(s,y);let m=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let b=e.chunks.join(""),f=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");f.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(f);let D=()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let x=le(t?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"},j=()=>{t=!t,t?Hn.add(n.id):Hn.delete(n.id),D()};return r.addEventListener("pointerdown",h=>{h.preventDefault(),j()}),r.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),j())}),D(),o.append(r,m),o};var In=new Set,Pn=(n,e)=>{var j;let o=n.toolCall,t=(j=e==null?void 0:e.toolCall)!=null?j:{},r=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!o)return r;let s=In.has(n.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",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=p("div","tvw-flex tvw-flex-col tvw-text-left"),d=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=uo(o),l.appendChild(d);let u=p("div","tvw-flex tvw-items-center"),c=t.toggleTextColor||t.headerTextColor||"currentColor",y=le(s?"chevron-up":"chevron-down",16,c,2);y?u.appendChild(y):u.textContent=s?"Hide":"Show";let m=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(l,m);let b=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=s?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),o.name){let h=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?h.style.color=t.contentTextColor:t.headerTextColor&&(h.style.color=t.headerTextColor),h.textContent=o.name,b.appendChild(h)}if(o.args!==void 0){let h=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Arguments";let R=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(R.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(R.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(R.style.color=t.codeBlockTextColor),R.textContent=An(o.args),h.append(x,R),b.appendChild(h)}if(o.chunks&&o.chunks.length){let h=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Activity";let R=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(R.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(R.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(R.style.color=t.codeBlockTextColor),R.textContent=o.chunks.join(`
|
|
16
|
+
`),h.append(x,R),b.appendChild(h)}if(o.status==="complete"&&o.result!==void 0){let h=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Result";let R=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(R.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(R.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(R.style.color=t.codeBlockTextColor),R.textContent=An(o.result),h.append(x,R),b.appendChild(h)}if(o.status==="complete"&&typeof o.duration=="number"){let h=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(h.style.color=t.contentTextColor),h.textContent=`Duration: ${o.duration}ms`,b.appendChild(h)}let f=()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let h=t.toggleTextColor||t.headerTextColor||"currentColor",x=le(s?"chevron-up":"chevron-down",16,h,2);x?u.appendChild(x):u.textContent=s?"Hide":"Show",b.style.display=s?"":"none"},D=()=>{s=!s,s?In.add(n.id):In.delete(n.id),f()};return i.addEventListener("pointerdown",h=>{h.preventDefault(),D()}),i.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),D())}),f(),r.append(i,b),r};var Co=n=>{let e=[];return{buttons:e,render:(t,r,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(b=>b.role==="user"))return;let c=document.createDocumentFragment(),y=r?r.isStreaming():!1,m=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let f=p("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");f.type="button",f.textContent=b,f.disabled=y,l!=null&&l.fontFamily&&(f.style.fontFamily=m(l.fontFamily)),l!=null&&l.fontWeight&&(f.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(f.style.paddingLeft=l.paddingX,f.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(f.style.paddingTop=l.paddingY,f.style.paddingBottom=l.paddingY),f.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(b))}),c.appendChild(f),e.push(f)}),n.appendChild(c)}}};var xo={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"}},$n=(n,e,o,t)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var f,D,j;if(s.dataset.enhanced==="true")return;let i=(f=s.dataset.tvForm)!=null?f:"init";s.dataset.enhanced="true";let l=(D=xo[i])!=null?D:xo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),u=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=l.title,d.appendChild(u),l.description){let h=p("p","tvw-text-sm tvw-text-cw-muted");h.textContent=l.description,d.appendChild(h)}let c=document.createElement("form");c.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(h=>{var T,O;let x=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");x.htmlFor=`${e.id}-${i}-${h.name}`;let R=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");R.textContent=h.label,x.appendChild(R);let w=(T=h.type)!=null?T:"text",K;w==="textarea"?(K=document.createElement("textarea"),K.rows=3):(K=document.createElement("input"),K.type=w),K.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",K.id=`${e.id}-${i}-${h.name}`,K.name=h.name,K.placeholder=(O=h.placeholder)!=null?O:"",h.required&&(K.required=!0),x.appendChild(K),c.appendChild(x)});let y=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(j=l.submitLabel)!=null?j:"Submit",y.appendChild(m),y.appendChild(b),c.appendChild(y),s.replaceChildren(d,c),c.addEventListener("submit",async h=>{var K,T;h.preventDefault();let x=(K=o.formEndpoint)!=null?K:"/form",R=new FormData(c),w={};R.forEach((O,ee)=>{w[ee]=O}),w.type=i,b.disabled=!0,m.textContent="Submitting\u2026";try{let O=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!O.ok)throw new Error(`Form submission failed (${O.status})`);let ee=await O.json();m.textContent=(T=ee.message)!=null?T:"Thanks! We'll be in touch soon.",ee.success&&ee.nextPrompt&&await t.sendMessage(String(ee.nextPrompt))}catch(O){m.textContent=O instanceof Error?O.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var On=class{constructor(){this.plugins=new Map}register(e){var o;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(o=e.onRegister)==null||o.call(e)}unregister(e){var t;let o=this.plugins.get(e);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=e.priority)!=null?r:0)})}getForInstance(e){let o=this.getAll();if(!e||e.length===0)return o;let t=new Set(e.map(s=>s.id));return[...o.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,d;return((l=i.priority)!=null?l:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var o;return(o=e.onUnregister)==null?void 0:o.call(e)}),this.plugins.clear()}},wn=new On;var He={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Fn(n){var e,o,t,r,s,i,l,d,u,c,y,m,b,f,D,j,h,x,R;return n?{...He,...n,theme:{...He.theme,...n.theme},launcher:{...He.launcher,...n.launcher,clearChat:{...(e=He.launcher)==null?void 0:e.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...He.copy,...n.copy},sendButton:{...He.sendButton,...n.sendButton},statusIndicator:{...He.statusIndicator,...n.statusIndicator},voiceRecognition:{...He.voiceRecognition,...n.voiceRecognition},features:{...He.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:He.suggestionChips,suggestionChipsConfig:{...He.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...He.layout,...n.layout,header:{...(r=He.layout)==null?void 0:r.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=He.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(u=(d=He.layout)==null?void 0:d.messages)==null?void 0:u.avatar,...(y=(c=n.layout)==null?void 0:c.messages)==null?void 0:y.avatar},timestamp:{...(b=(m=He.layout)==null?void 0:m.messages)==null?void 0:b.timestamp,...(D=(f=n.layout)==null?void 0:f.messages)==null?void 0:D.timestamp}},slots:{...(j=He.layout)==null?void 0:j.slots,...(h=n.layout)==null?void 0:h.slots}},markdown:{...He.markdown,...n.markdown,options:{...(x=He.markdown)==null?void 0:x.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...He.messageActions,...n.messageActions}}:He}var So=()=>{let n=new Map,e=(r,s)=>(n.has(r)||n.set(r,new Set),n.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=n.get(r))==null||i.delete(s)};return{on:e,off:o,emit:(r,s)=>{var i;(i=n.get(r))==null||i.forEach(l=>{try{l(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Yo=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Ko=n=>{let e=n.trim(),o=e.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<e.length;r+=1){let s=e[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(o,r+1)}return null},yn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Yo(n),o=Ko(e);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Dn=n=>typeof n=="string"?n:n==null?"":String(n),Vt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Dn(n.payload.text)},messageAndClick:(n,e)=>{var r;if(n.type!=="message_and_click")return;let o=n.payload,t=Dn(o.element);if(t&&((r=e.document)!=null&&r.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:Dn(o.text)}}},Ao=n=>Array.isArray(n)?n.map(e=>String(e)):[],vn=n=>{let e=new Set(Ao(n.getMetadata().processedActionMessageIds)),o=()=>{e=new Set(Ao(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((u,c)=>u||(c==null?void 0:c({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let d={action:l,message:s.message};n.emit("action:detected",d);for(let u of n.handlers)if(u)try{let c=u(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!c)continue;if(c.handled){let y=c.persistMessage!==!1;return{text:c.displayText!==void 0?c.displayText:"",persist:y}}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:o}};var Xo=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}},Vo=n=>n.map(e=>({...e,streaming:!1})),Nn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=e();return o?Xo(o.getItem(n)):null},save:o=>{let t=e();if(t)try{let r={...o,messages:o.messages?Vo(o.messages):void 0};t.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=e();if(o)try{o.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var jn=class{constructor(){this.components=new Map}register(e,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,o)}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(([o,t])=>{this.register(o,t)})}},an=new jn;import{parse as Go,STR as Zo,OBJ as Qo}from"partial-json";function er(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function tr(n,e){if(!er(n))return null;let o=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:o,raw:e}}function _n(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=e)return n;try{let r=Go(o,Zo|Qo),s=tr(r,o);s&&(n=s)}catch{}return e=o.length,n},reset:()=>{n=null,e=0}}}function nr(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function qn(n,e){let{config:o,message:t,onPropsUpdate:r}=e,s=an.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:o,updateProps:l=>{r&&r(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function sr(){let n=_n();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Un(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 zn(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 Gt="vanilla-agent-chat-history",or=30*1e3,Jn=n=>!n||typeof n!="object"?{}:{...n},To=n=>n.map(e=>({...e,streaming:!1})),Eo=(n,e)=>{let o=n!=null&&n.markdown?gn(n.markdown):null;return t=>{var i,l,d;let r=(i=t.text)!=null?i:"",s=(l=t.message.rawContent)!=null?l:null;if(e){let u=e.process({text:r,raw:s!=null?s:r,message:t.message,streaming:t.streaming});u!==null&&(r=u.text,u.persist||(t.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...t,text:r,raw:(d=s!=null?s:t.text)!=null?d:""}):o?o(r):Sn(r)}},Yn=(n,e,o)=>{var ce,Ie,pe,Fe,rt,ht,Xn,Vn,Gn,Zn,Qn,es,ts,ns;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Fn(e),r=wn.getForInstance(t.plugins);t.components&&an.registerAll(t.components);let s=So(),i=(ce=t.storageAdapter)!=null?ce:Nn(),l={},d=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")d=a;else if(a){let g=a;g.metadata&&(l=Jn(g.metadata)),(Ie=g.messages)!=null&&Ie.length&&(t={...t,initialMessages:g.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let u=()=>l,c=a=>{var W;l=(W=a({...l}))!=null?W:{},Wt()},y=t.actionParsers&&t.actionParsers.length?t.actionParsers:[yn],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Vt.message,Vt.messageAndClick],b=vn({parsers:y,handlers:m,getMetadata:u,updateMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let f=(Fe=(pe=t.launcher)==null?void 0:pe.enabled)!=null?Fe:!0,D=(ht=(rt=t.launcher)==null?void 0:rt.autoExpand)!=null?ht:!1,j=D,h=f,x=f?D:!0,R=Eo(t,b),w=(Vn=(Xn=t.features)==null?void 0:Xn.showReasoning)!=null?Vn:!0,K=(Zn=(Gn=t.features)==null?void 0:Gn.showToolCalls)!=null?Zn:!0,T={onCopy:a=>{s.emit("message:copy",a)},onFeedback:a=>{s.emit("message:feedback",a)}},O=(Qn=t.statusIndicator)!=null?Qn:{},ee=a=>{var g,W,N,I;return a==="idle"?(g=O.idleText)!=null?g:Ke.idle:a==="connecting"?(W=O.connectingText)!=null?W:Ke.connecting:a==="connected"?(N=O.connectedText)!=null?N:Ke.connected:a==="error"?(I=O.errorText)!=null?I:Ke.error:Ke[a]},{wrapper:P,panel:Y}=wo(t),fe=yo(t,f),{container:J,body:F,messagesWrapper:ne,suggestions:De,textarea:oe,sendButton:$,sendButtonWrapper:qe,composerForm:Xe,statusText:tt,introTitle:bt,introSubtitle:Ct,closeButton:q,iconHolder:he,headerTitle:mt,headerSubtitle:ft,header:Ve,footer:nt}=fe,L=fe.micButton,Re=fe.micButtonWrapper,it=r.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let g=zt({config:t,showClose:f});return sn(J,g,t),g.header},onClose:()=>ot(!1,"user")});if(a){let g=J.querySelector(".tvw-border-b-cw-divider");g&&(g.replaceWith(a),Ve=a)}}let at=r.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>on({config:t}).footer,onSubmit:g=>{U&&!U.isStreaming()&&U.sendMessage(g)},disabled:!1});a&&(nt.replaceWith(a),nt=a)}(()=>{var N,I;let a=(I=(N=t.layout)==null?void 0:N.slots)!=null?I:{},g=re=>{switch(re){case"body-top":return J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return ne;case"footer-top":return De;case"composer":return Xe;case"footer-bottom":return tt;default:return null}},W=(re,H)=>{var C;switch(re){case"header-left":case"header-center":case"header-right":if(re==="header-left")Ve.insertBefore(H,Ve.firstChild);else if(re==="header-right")Ve.appendChild(H);else{let _=Ve.querySelector(".tvw-flex-col");_?(C=_.parentNode)==null||C.insertBefore(H,_.nextSibling):Ve.appendChild(H)}break;case"body-top":let G=F.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(H):F.insertBefore(H,F.firstChild);break;case"body-bottom":F.appendChild(H);break;case"footer-top":De.replaceWith(H);break;case"footer-bottom":tt.replaceWith(H);break;default:break}};for(let[re,H]of Object.entries(a))if(H)try{let C=H({config:t,defaultContent:()=>g(re)});C&&W(re,C)}catch(C){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${re}":`,C)}})(),Y.appendChild(J),n.appendChild(P);let wt=()=>{var ie,Pe,dt,ae,ct,Ht,Rt,Lt,_t,It,qt,pt,Pt,$t,pn,en;let a=(Pe=(ie=t.launcher)==null?void 0:ie.sidebarMode)!=null?Pe:!1,g=a||((ae=(dt=t.launcher)==null?void 0:dt.fullHeight)!=null?ae:!1),W=(ct=t.theme)!=null?ct:{},N=(Rt=(Ht=t.launcher)==null?void 0:Ht.position)!=null?Rt:"bottom-left",I=N==="bottom-left"||N==="top-left",re=a?"none":"1px solid var(--tvw-cw-border)",H=a?I?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",C=a?"0":"16px",G=(Lt=W.panelBorder)!=null?Lt:re,_=(_t=W.panelShadow)!=null?_t:H,k=(It=W.panelBorderRadius)!=null?It:C;n.style.cssText="",P.style.cssText="",Y.style.cssText="",J.style.cssText="",F.style.cssText="",nt.style.cssText="";let z=(pt=(qt=t==null?void 0:t.launcher)==null?void 0:qt.width)!=null?pt:t==null?void 0:t.launcherWidth,Be=z!=null?z:"min(400px, calc(100vw - 24px))";a||(Y.style.width=Be,Y.style.maxWidth=Be),Y.style.boxShadow=_,Y.style.borderRadius=k,J.style.border=G,J.style.borderRadius=k;let ue=((Pt=t.launcher)==null?void 0:Pt.enabled)===!1;if(g&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1 1 0%",P.style.minHeight="0",P.style.maxHeight="100%",P.style.height="100%",ue&&(P.style.overflow="hidden"),Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.height="100%",Y.style.overflow="hidden",J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.overflow="hidden",F.style.flex="1 1 0%",F.style.minHeight="0",F.style.overflowY="auto",nt.style.flexShrink="0"),P.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!a&&!ue&&(($t=vt[N])!=null?$t:vt["bottom-right"]).split(" ").forEach(Yt=>P.classList.add(Yt)),a){let Ut=(en=(pn=t.launcher)==null?void 0:pn.sidebarWidth)!=null?en:"420px";P.style.cssText=`
|
|
17
17
|
position: fixed !important;
|
|
18
18
|
top: 0 !important;
|
|
19
19
|
bottom: 0 !important;
|
|
20
|
-
width: ${
|
|
20
|
+
width: ${Ut} !important;
|
|
21
21
|
height: 100vh !important;
|
|
22
22
|
max-height: 100vh !important;
|
|
23
23
|
margin: 0 !important;
|
|
24
24
|
padding: 0 !important;
|
|
25
25
|
display: flex !important;
|
|
26
26
|
flex-direction: column !important;
|
|
27
|
-
${
|
|
28
|
-
`,
|
|
27
|
+
${I?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
28
|
+
`,Y.style.cssText=`
|
|
29
29
|
position: relative !important;
|
|
30
30
|
display: flex !important;
|
|
31
31
|
flex-direction: column !important;
|
|
@@ -36,9 +36,9 @@ import{Marked as Wo}from"marked";var Mo=n=>{if(n)return n},un=n=>{var o,s;let e=
|
|
|
36
36
|
min-height: 0 !important;
|
|
37
37
|
margin: 0 !important;
|
|
38
38
|
padding: 0 !important;
|
|
39
|
-
box-shadow: ${
|
|
40
|
-
border-radius: ${
|
|
41
|
-
`,
|
|
39
|
+
box-shadow: ${_} !important;
|
|
40
|
+
border-radius: ${k} !important;
|
|
41
|
+
`,Y.style.setProperty("width","100%","important"),Y.style.setProperty("max-width","100%","important"),J.style.cssText=`
|
|
42
42
|
display: flex !important;
|
|
43
43
|
flex-direction: column !important;
|
|
44
44
|
flex: 1 1 0% !important;
|
|
@@ -47,17 +47,17 @@ import{Marked as Wo}from"marked";var Mo=n=>{if(n)return n},un=n=>{var o,s;let e=
|
|
|
47
47
|
min-height: 0 !important;
|
|
48
48
|
max-height: 100% !important;
|
|
49
49
|
overflow: hidden !important;
|
|
50
|
-
border-radius: ${
|
|
51
|
-
border: ${
|
|
52
|
-
`,
|
|
50
|
+
border-radius: ${k} !important;
|
|
51
|
+
border: ${G} !important;
|
|
52
|
+
`,nt.style.cssText=`
|
|
53
53
|
flex-shrink: 0 !important;
|
|
54
54
|
border-top: none !important;
|
|
55
55
|
padding: 8px 16px 12px 16px !important;
|
|
56
|
-
`}if(!ge){let qt="max-height: -moz-available !important; max-height: stretch !important;",Yt=a?"":"padding-top: 1.25em !important;";Q.style.cssText+=qt+Yt}};wt(),Ln(n,t);let $e=[],tt=vo(ne),qe=null,j,lt=!1,Ke=!0,We=0,_e=0,J=null,Se=!1,Be=0,Ue=!1,nt=125,St=2e3,Lt=5,gt=50,At=new Map,de={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Nt=(es=(Qn=t.voiceRecognition)==null?void 0:Qn.autoResume)!=null?es:!1,Bt=a=>{s.emit("voice:state",{active:de.active,source:a,timestamp:Date.now()})},be=()=>{d(a=>({...a,voiceState:{active:de.active,timestamp:Date.now(),manuallyDeactivated:de.manuallyDeactivated}}))},yt=()=>{var O,R;if(((O=t.voiceRecognition)==null?void 0:O.enabled)===!1)return;let a=Yn(l.voiceState),u=!!a.active,T=Number((R=a.timestamp)!=null?R:0);de.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-T<tr&&setTimeout(()=>{de.active||(de.manuallyDeactivated=!1,Oe("restore"))},1e3)},Tt=()=>j?So(j.getMessages()).filter(a=>!a.__skipPersist):[];function kt(a){if(!(i!=null&&i.save))return;let T={messages:a?So(a):j?Tt():[],metadata:l};try{let O=i.save(T);O instanceof Promise&&O.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(O){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",O)}}let vt=(a=!1)=>{if(!Ke)return;let u=Date.now();Se&&u<Be&&!a||(Se&&u>=Be&&(Se=!1),!(!a&&!lt)&&(u-_e<nt||(_e=u,J&&cancelAnimationFrame(J),J=requestAnimationFrame(()=>{Se||!Ke||(Ue=!0,U.scrollTop=U.scrollHeight,We=U.scrollTop,requestAnimationFrame(()=>{Ue=!1}),J=null)}))))},Wt=null,ln=()=>Q.querySelector("#vanilla-agent-scroll-container")||U,dn=(a,u=500)=>{let T=a.scrollTop,O=a.clientHeight,R=a.scrollHeight,se=R-T;if(T+O>=R-2||Math.abs(se)<5)return;Wt!==null&&(cancelAnimationFrame(Wt),Wt=null);let v=performance.now(),X=B=>1-Math.pow(1-B,3),N=B=>{let _=a.scrollHeight;_!==R&&(R=_,se=R-T);let Me=B-v,ge=Math.min(Me/u,1),re=X(ge),Re=T+se*re;a.scrollTop=Re,ge<1?Wt=requestAnimationFrame(N):(a.scrollTop=a.scrollHeight,Wt=null)};Wt=requestAnimationFrame(N)},cn=a=>{let u=new Map;a.forEach(T=>{let O=At.get(T.id);u.set(T.id,{streaming:T.streaming,role:T.role}),!O&&T.role==="assistant"&&s.emit("assistant:message",T),T.role==="assistant"&&(O!=null&&O.streaming)&&T.streaming===!1&&s.emit("assistant:complete",T)}),At.clear(),u.forEach((T,O)=>{At.set(O,T)})},Ft=(a,u,T)=>{a.innerHTML="";let O=document.createDocumentFragment();u.forEach(v=>{var Me,ge;let X=null,N=o.find(re=>!!(v.variant==="reasoning"&&re.renderReasoning||v.variant==="tool"&&re.renderToolCall||!v.variant&&re.renderMessage)),B=(Me=t.layout)==null?void 0:Me.messages;if(N)if(v.variant==="reasoning"&&v.reasoning&&N.renderReasoning){if(!S)return;X=N.renderReasoning({message:v,defaultRenderer:()=>Rn(v),config:t})}else if(v.variant==="tool"&&v.toolCall&&N.renderToolCall){if(!Y)return;X=N.renderToolCall({message:v,defaultRenderer:()=>$n(v,t),config:t})}else N.renderMessage&&(X=N.renderMessage({message:v,defaultRenderer:()=>{let re=rn(v,T,B);return v.role!=="user"&&Pn(re,v,t,j),re},config:t}));if(!X&&v.role==="assistant"&&!v.variant&&t.enableComponentStreaming!==!1&&Un(v)){let Re=zn(v);if(Re){let dt=qn(Re,{config:t,message:v,transform:T});if(dt){let ie=document.createElement("div");if(ie.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(" "),ie.setAttribute("data-message-id",v.id),v.content&&v.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=T({text:v.content,message:v,streaming:!!v.streaming,raw:v.rawContent}),ie.appendChild(ct)}ie.appendChild(dt),X=ie}}}if(!X)if(v.variant==="reasoning"&&v.reasoning){if(!S)return;X=Rn(v)}else if(v.variant==="tool"&&v.toolCall){if(!Y)return;X=$n(v,t)}else{let re=(ge=t.layout)==null?void 0:ge.messages;re!=null&&re.renderUserMessage&&v.role==="user"?X=re.renderUserMessage({message:v,config:t,streaming:!!v.streaming}):re!=null&&re.renderAssistantMessage&&v.role==="assistant"?X=re.renderAssistantMessage({message:v,config:t,streaming:!!v.streaming}):X=rn(v,T,re),v.role!=="user"&&X&&Pn(X,v,t,j)}let _=document.createElement("div");_.className="tvw-flex",v.role==="user"&&_.classList.add("tvw-justify-end"),_.appendChild(X),O.appendChild(_)});let R=u.some(v=>v.role==="assistant"&&v.streaming),se=u[u.length-1],H=(se==null?void 0:se.role)==="assistant"&&!se.streaming;if(lt&&u.some(v=>v.role==="user")&&!R&&!H){let v=fn(),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(v);let N=document.createElement("div");N.className="tvw-flex",N.appendChild(X),O.appendChild(N)}a.appendChild(O),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let v=ln();dn(v)})})},Dt=()=>{w&&(x?(Q.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),W.classList.remove("tvw-scale-95","tvw-opacity-0"),W.classList.add("tvw-scale-100","tvw-opacity-100"),h?h.element.style.display="none":k&&(k.style.display="none")):(Q.classList.add("tvw-pointer-events-none","tvw-opacity-0"),W.classList.remove("tvw-scale-100","tvw-opacity-100"),W.classList.add("tvw-scale-95","tvw-opacity-0"),h?h.element.style.display="":k&&(k.style.display="")))},st=(a,u="user")=>{if(!w||x===a)return;let T=x;x=a,Dt(),x&&(ye(),vt(!0));let O={open:x,source:u,timestamp:Date.now()};x&&!T?s.emit("widget:opened",O):!x&&T&&s.emit("widget:closed",O),s.emit("widget:state",{open:x,launcherEnabled:w,voiceActive:de.active,streaming:j.isStreaming()})},zt=a=>{$.disabled=a,M&&(M.disabled=a),tt.buttons.forEach(u=>{u.disabled=a})},Gt=()=>{var R,se,H,v,X,N,B,_,Me,ge,re,Re,dt,ie;xt.textContent=(se=(R=t.copy)==null?void 0:R.welcomeTitle)!=null?se:"Hello \u{1F44B}",Ct.textContent=(v=(H=t.copy)==null?void 0:H.welcomeSubtitle)!=null?v:"Ask anything about your account or products.",Z.placeholder=(N=(X=t.copy)==null?void 0:X.inputPlaceholder)!=null?N:"How can I help...",((_=(B=t.sendButton)==null?void 0:B.useIcon)!=null?_:!1)||($.textContent=(ge=(Me=t.copy)==null?void 0:Me.sendButtonLabel)!=null?ge:"Send");let u=(Re=(re=t.theme)==null?void 0:re.inputFontFamily)!=null?Re:"sans-serif",T=(ie=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?ie:"400",O=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};Z.style.fontFamily=O(u),Z.style.fontWeight=T};j=new tn(t,{onMessagesChanged(a){Ft(z,a,I),j&&(a.some(O=>O.role==="user")?tt.render([],j,Z,a):tt.render(t.suggestionChips,j,Z,a,t.suggestionChipsConfig)),vt(!lt),cn(a);let u=[...a].reverse().find(T=>T.role==="user");de.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),kt(a)},onStatusChanged(a){var O;let u=(O=t.statusIndicator)!=null?O:{},T=R=>{var se,H,v,X;return R==="idle"?(se=u.idleText)!=null?se:ze.idle:R==="connecting"?(H=u.connectingText)!=null?H:ze.connecting:R==="connected"?(v=u.connectedText)!=null?v:ze.connected:R==="error"?(X=u.errorText)!=null?X:ze.error:ze[R]};Qe.textContent=T(a)},onStreamingChanged(a){lt=a,zt(a),j&&Ft(z,j.getMessages(),I),a||vt(!0)}}),c&&c.then(a=>{var u;a&&(a.metadata&&(l=Yn(a.metadata),b.syncFromMetadata()),(u=a.messages)!=null&&u.length&&j.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let Zt=a=>{a.preventDefault();let u=Z.value.trim();u&&(Z.value="",j.sendMessage(u))},Qt=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),$.click())},y=null,K=!1,oe=null,we=null,Pe=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Oe=(a="user")=>{var se,H,v,X;if(K||j.isStreaming())return;let u=Pe();if(!u)return;y=new u;let O=(H=((se=t.voiceRecognition)!=null?se:{}).pauseDuration)!=null?H:2e3;y.continuous=!0,y.interimResults=!0,y.lang="en-US";let R=Z.value;y.onresult=N=>{let B="",_="";for(let ge=0;ge<N.results.length;ge++){let re=N.results[ge],Re=re[0].transcript;re.isFinal?B+=Re+" ":_=Re}let Me=R+B+_;Z.value=Me,oe&&clearTimeout(oe),(B||_)&&(oe=window.setTimeout(()=>{let ge=Z.value.trim();ge&&y&&K&&(ce(),Z.value="",j.sendMessage(ge,{viaVoice:!0}))},O))},y.onerror=N=>{N.error!=="no-speech"&&ce()},y.onend=()=>{if(K){let N=Z.value.trim();N&&N!==R.trim()&&(Z.value="",j.sendMessage(N,{viaVoice:!0})),ce()}};try{if(y.start(),K=!0,de.active=!0,a!=="system"&&(de.manuallyDeactivated=!1),Bt(a),be(),M){we={backgroundColor:M.style.backgroundColor,color:M.style.color,borderColor:M.style.borderColor};let N=(v=t.voiceRecognition)!=null?v:{},B=(X=N.recordingBackgroundColor)!=null?X:"#ef4444",_=N.recordingIconColor,Me=N.recordingBorderColor;if(M.classList.add("tvw-voice-recording"),M.style.backgroundColor=B,_){M.style.color=_;let ge=M.querySelector("svg");ge&&ge.setAttribute("stroke",_)}Me&&(M.style.borderColor=Me),M.setAttribute("aria-label","Stop voice recognition")}}catch{ce("system")}},ce=(a="user")=>{if(K){if(K=!1,oe&&(clearTimeout(oe),oe=null),y){try{y.stop()}catch{}y=null}if(de.active=!1,Bt(a),be(),M){if(M.classList.remove("tvw-voice-recording"),we){M.style.backgroundColor=we.backgroundColor,M.style.color=we.color,M.style.borderColor=we.borderColor;let u=M.querySelector("svg");u&&u.setAttribute("stroke",we.color||"currentColor"),we=null}M.setAttribute("aria-label","Start voice recognition")}}},L=(a,u)=>{var Re,dt,ie,ct,Ht,Rt,Mt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let O=p("div","tvw-send-button-wrapper"),R=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");R.type="button",R.setAttribute("aria-label","Start voice recognition");let se=(Re=a==null?void 0:a.iconName)!=null?Re:"mic",H=(dt=u==null?void 0:u.size)!=null?dt:"40px",v=(ie=a==null?void 0:a.iconSize)!=null?ie:H,X=parseFloat(v)||24,N=(ct=a==null?void 0:a.backgroundColor)!=null?ct:u==null?void 0:u.backgroundColor,B=(Ht=a==null?void 0:a.iconColor)!=null?Ht:u==null?void 0:u.textColor;R.style.width=v,R.style.height=v,R.style.minWidth=v,R.style.minHeight=v,R.style.fontSize="18px",R.style.lineHeight="1";let _=B||"currentColor",Me=ve(se,X,_,1.5);Me?(R.appendChild(Me),R.style.color=_):(R.textContent="\u{1F3A4}",R.style.color=_),N?R.style.backgroundColor=N:R.classList.add("tvw-bg-cw-primary"),B?R.style.color=B:!B&&!(u!=null&&u.textColor)&&R.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(R.style.borderWidth=a.borderWidth,R.style.borderStyle="solid"),a!=null&&a.borderColor&&(R.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(R.style.paddingLeft=a.paddingX,R.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(R.style.paddingTop=a.paddingY,R.style.paddingBottom=a.paddingY),O.appendChild(R);let ge=(Rt=a==null?void 0:a.tooltipText)!=null?Rt:"Start voice recognition";if(((Mt=a==null?void 0:a.showTooltip)!=null?Mt:!1)&&ge){let jt=p("div","tvw-send-button-tooltip");jt.textContent=ge,O.appendChild(jt)}return{micButton:R,micButtonWrapper:O}},ot=()=>{if(K){let a=Z.value.trim();de.manuallyDeactivated=!0,be(),ce("user"),a&&(Z.value="",j.sendMessage(a))}else de.manuallyDeactivated=!1,be(),Oe("user")};M&&(M.addEventListener("click",ot),$e.push(()=>{ce("system"),M&&M.removeEventListener("click",ot)}));let ee=s.on("assistant:complete",()=>{Nt&&(de.active||de.manuallyDeactivated||Nt==="assistant"&&!de.lastUserMessageWasVoice||setTimeout(()=>{!de.active&&!de.manuallyDeactivated&&Oe("auto")},600))});$e.push(ee);let C=()=>{st(!x,"user")},h=null,k=null;if(w){let a=o.find(u=>u.renderLauncher);if(a!=null&&a.renderLauncher){let u=a.renderLauncher({config:t,defaultRenderer:()=>nn(t,C).element,onToggle:C});u&&(k=u)}k||(h=nn(t,C))}h?n.appendChild(h.element):k&&n.appendChild(k),Dt(),tt.render(t.suggestionChips,j,Z,void 0,t.suggestionChipsConfig),Gt(),zt(j.isStreaming()),vt(!0),yt();let ye=()=>{var T,O,R,se,H,v,X,N;let a=(O=(T=t.launcher)==null?void 0:T.sidebarMode)!=null?O:!1,u=a||((se=(R=t.launcher)==null?void 0:R.fullHeight)!=null?se:!1);if(!w){W.style.height="",W.style.width="";return}if(!a){let B=(v=(H=t==null?void 0:t.launcher)==null?void 0:H.width)!=null?v:t==null?void 0:t.launcherWidth,_=B!=null?B:"min(400px, calc(100vw - 24px))";W.style.width=_,W.style.maxWidth=_}if(!u){let B=window.innerHeight,_=64,Me=(N=(X=t.launcher)==null?void 0:X.heightOffset)!=null?N:0,ge=Math.max(200,B-_),re=Math.min(640,ge),Re=Math.max(200,re-Me);W.style.height=`${Re}px`}};ye(),window.addEventListener("resize",ye),$e.push(()=>window.removeEventListener("resize",ye)),We=U.scrollTop;let Ae=()=>{let a=U.scrollTop,u=U.scrollHeight,T=U.clientHeight,O=u-a-T,R=Math.abs(a-We);if(We=a,!Ue&&!(R<=Lt)){if(!Ke&&O<gt){Se=!1,Ke=!0;return}Ke&&O>gt&&(Se=!0,Be=Date.now()+St,Ke=!1)}};U.addEventListener("scroll",Ae,{passive:!0}),$e.push(()=>U.removeEventListener("scroll",Ae)),$e.push(()=>{J&&cancelAnimationFrame(J)});let Xe=()=>{D&&(qe&&(D.removeEventListener("click",qe),qe=null),w?(D.style.display="",qe=()=>{x=!1,Dt()},D.addEventListener("click",qe)):D.style.display="none")};Xe(),(()=>{let{clearChatButton:a}=le;a&&a.addEventListener("click",()=>{j.clearMessages();try{localStorage.removeItem(Vt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vt}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Vt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let u=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(O=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",O)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}l={},b.syncFromMetadata()})})(),Ye.addEventListener("submit",Zt),Z.addEventListener("keydown",Qt),$e.push(()=>{Ye.removeEventListener("submit",Zt),Z.removeEventListener("keydown",Qt)}),$e.push(()=>{j.cancel()}),h?$e.push(()=>{h==null||h.destroy()}):k&&$e.push(()=>{k==null||k.remove()});let xe={update(a){var en,qt,Yt,ns,ss,os,rs,is,as,ls,ds,cs,ps,us,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,ks,Hs,Rs,Is,$s,Ps,Os,Ns,Fs,Ds,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs,Qs,eo,to;let u=t.toolCall;t={...t,...a},wt(),Ln(n,t);let T=wn.getForInstance(t.plugins);if(o.length=0,o.push(...T),w=(qt=(en=t.launcher)==null?void 0:en.enabled)!=null?qt:!0,q=(ns=(Yt=t.launcher)==null?void 0:Yt.autoExpand)!=null?ns:!1,S=(os=(ss=t.features)==null?void 0:ss.showReasoning)!=null?os:!0,Y=(is=(rs=t.features)==null?void 0:rs.showToolCalls)!=null?is:!0,((as=t.launcher)==null?void 0:as.enabled)===!1&&h&&(h.destroy(),h=null),((ls=t.launcher)==null?void 0:ls.enabled)===!1&&k&&(k.remove(),k=null),((ds=t.launcher)==null?void 0:ds.enabled)!==!1&&!h&&!k){let E=o.find(fe=>fe.renderLauncher);if(E!=null&&E.renderLauncher){let fe=E.renderLauncher({config:t,defaultRenderer:()=>nn(t,C).element,onToggle:C});fe&&(k=fe,n.appendChild(k))}k||(h=nn(t,C),n.appendChild(h.element))}h&&h.update(t),mt&&((cs=t.launcher)==null?void 0:cs.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((ps=t.launcher)==null?void 0:ps.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),w!==m?w?st(q,"auto"):(x=!0,Dt()):q!==F&&st(q,"auto"),F=q,m=w,ye(),Xe(),JSON.stringify(a.toolCall)!==JSON.stringify(u)&&j&&Ft(z,j.getMessages(),I);let H=(us=t.launcher)!=null?us:{},v=(gs=H.headerIconHidden)!=null?gs:!1,X=H.headerIconName,N=(hs=H.headerIconSize)!=null?hs:"48px";if(me){let E=G.querySelector(".tvw-border-b-cw-divider"),fe=E==null?void 0:E.querySelector(".tvw-flex-col");if(v)me.style.display="none",E&&fe&&!E.contains(fe)&&E.insertBefore(fe,E.firstChild);else{if(me.style.display="",me.style.height=N,me.style.width=N,E&&fe&&(E.contains(me)?me.nextSibling!==fe&&(me.remove(),E.insertBefore(me,fe)):E.insertBefore(me,fe)),X){let Ee=parseFloat(N)||24,Ce=ve(X,Ee*.6,"#ffffff",2);Ce?me.replaceChildren(Ce):me.textContent=(ms=H.agentIconText)!=null?ms:"\u{1F4AC}"}else if(H.iconUrl){let Ee=me.querySelector("img");if(Ee)Ee.src=H.iconUrl,Ee.style.height=N,Ee.style.width=N;else{let Ce=document.createElement("img");Ce.src=H.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=N,Ce.style.width=N,me.replaceChildren(Ce)}}else{let Ee=me.querySelector("svg"),Ce=me.querySelector("img");(Ee||Ce)&&me.replaceChildren(),me.textContent=(fs=H.agentIconText)!=null?fs:"\u{1F4AC}"}let te=me.querySelector("img");te&&(te.style.height=N,te.style.width=N)}}if(D){let E=(ws=H.closeButtonSize)!=null?ws:"32px",fe=(ys=H.closeButtonPlacement)!=null?ys:"inline";D.style.height=E,D.style.width=E;let{closeButtonWrapper:te}=le,Ee=fe==="top-right",Ce=te==null?void 0:te.classList.contains("tvw-absolute");if(te&&Ee!==Ce)if(te.remove(),Ee)te.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",G.style.position="relative",G.appendChild(te);else{let he=(bs=(vs=H.clearChat)==null?void 0:vs.placement)!=null?bs:"inline",Ge=(Cs=(xs=H.clearChat)==null?void 0:xs.enabled)!=null?Cs:!0;te.className=Ge&&he==="inline"?"":"tvw-ml-auto";let Ze=G.querySelector(".tvw-border-b-cw-divider");Ze&&Ze.appendChild(te)}if(H.closeButtonColor?(D.style.color=H.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),H.closeButtonBackgroundColor?(D.style.backgroundColor=H.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),H.closeButtonBorderWidth||H.closeButtonBorderColor){let he=H.closeButtonBorderWidth||"0px",Ge=H.closeButtonBorderColor||"transparent";D.style.border=`${he} solid ${Ge}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");H.closeButtonBorderRadius?(D.style.borderRadius=H.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),H.closeButtonPaddingX?(D.style.paddingLeft=H.closeButtonPaddingX,D.style.paddingRight=H.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),H.closeButtonPaddingY?(D.style.paddingTop=H.closeButtonPaddingY,D.style.paddingBottom=H.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Ve=(Ss=H.closeButtonIconName)!=null?Ss:"x",je=(As=H.closeButtonIconText)!=null?As:"\xD7";D.innerHTML="";let ut=ve(Ve,"20px",H.closeButtonColor||"",2);ut?D.appendChild(ut):D.textContent=je;let Ot=(Ts=H.closeButtonTooltipText)!=null?Ts:"Close chat",Te=(Es=H.closeButtonShowTooltip)!=null?Es:!0;if(D.setAttribute("aria-label",Ot),te&&(te._cleanupTooltip&&(te._cleanupTooltip(),delete te._cleanupTooltip),Te&&Ot)){let he=null,Ge=()=>{if(he||!D)return;he=p("div","tvw-clear-chat-tooltip"),he.textContent=Ot;let Jt=p("div");Jt.className="tvw-clear-chat-tooltip-arrow",he.appendChild(Jt);let Cn=D.getBoundingClientRect();he.style.position="fixed",he.style.left=`${Cn.left+Cn.width/2}px`,he.style.top=`${Cn.top-8}px`,he.style.transform="translate(-50%, -100%)",document.body.appendChild(he)},Ze=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};te.addEventListener("mouseenter",Ge),te.addEventListener("mouseleave",Ze),D.addEventListener("focus",Ge),D.addEventListener("blur",Ze),te._cleanupTooltip=()=>{Ze(),te&&(te.removeEventListener("mouseenter",Ge),te.removeEventListener("mouseleave",Ze)),D&&(D.removeEventListener("focus",Ge),D.removeEventListener("blur",Ze))}}}let{clearChatButton:B,clearChatButtonWrapper:_}=le;if(B){let E=(Ws=H.clearChat)!=null?Ws:{},fe=(Ms=E.enabled)!=null?Ms:!0,te=(Ls=E.placement)!=null?Ls:"inline";if(_){_.style.display=fe?"":"none";let Ee=te==="top-right",Ce=_.classList.contains("tvw-absolute");if(Ee!==Ce&&fe){if(_.remove(),Ee)_.className="tvw-absolute tvw-top-4 tvw-z-50",_.style.right="48px",G.style.position="relative",G.appendChild(_);else{_.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",_.style.right="";let je=G.querySelector(".tvw-border-b-cw-divider"),ut=le.closeButtonWrapper;je&&ut&&ut.parentElement===je?je.insertBefore(_,ut):je&&je.appendChild(_)}let Ve=le.closeButtonWrapper;Ve&&!Ve.classList.contains("tvw-absolute")&&(Ee?Ve.classList.add("tvw-ml-auto"):Ve.classList.remove("tvw-ml-auto"))}}if(fe){let Ee=(Bs=E.size)!=null?Bs:"32px";B.style.height=Ee,B.style.width=Ee;let Ce=(ks=E.iconName)!=null?ks:"refresh-cw",Ve=(Hs=E.iconColor)!=null?Hs:"";B.innerHTML="";let je=ve(Ce,"20px",Ve||"",2);if(je&&B.appendChild(je),Ve?(B.style.color=Ve,B.classList.remove("tvw-text-cw-muted")):(B.style.color="",B.classList.add("tvw-text-cw-muted")),E.backgroundColor?(B.style.backgroundColor=E.backgroundColor,B.classList.remove("hover:tvw-bg-gray-100")):(B.style.backgroundColor="",B.classList.add("hover:tvw-bg-gray-100")),E.borderWidth||E.borderColor){let Te=E.borderWidth||"0px",he=E.borderColor||"transparent";B.style.border=`${Te} solid ${he}`,B.classList.remove("tvw-border-none")}else B.style.border="",B.classList.add("tvw-border-none");E.borderRadius?(B.style.borderRadius=E.borderRadius,B.classList.remove("tvw-rounded-full")):(B.style.borderRadius="",B.classList.add("tvw-rounded-full")),E.paddingX?(B.style.paddingLeft=E.paddingX,B.style.paddingRight=E.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),E.paddingY?(B.style.paddingTop=E.paddingY,B.style.paddingBottom=E.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let ut=(Rs=E.tooltipText)!=null?Rs:"Clear chat",Ot=(Is=E.showTooltip)!=null?Is:!0;if(B.setAttribute("aria-label",ut),_&&(_._cleanupTooltip&&(_._cleanupTooltip(),delete _._cleanupTooltip),Ot&&ut)){let Te=null,he=()=>{if(Te||!B)return;Te=p("div","tvw-clear-chat-tooltip"),Te.textContent=ut;let Ze=p("div");Ze.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(Ze);let Jt=B.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${Jt.left+Jt.width/2}px`,Te.style.top=`${Jt.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},Ge=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};_.addEventListener("mouseenter",he),_.addEventListener("mouseleave",Ge),B.addEventListener("focus",he),B.addEventListener("blur",Ge),_._cleanupTooltip=()=>{Ge(),_&&(_.removeEventListener("mouseenter",he),_.removeEventListener("mouseleave",Ge)),B&&(B.removeEventListener("focus",he),B.removeEventListener("blur",Ge))}}}}let Me=t.actionParsers&&t.actionParsers.length?t.actionParsers:[yn],ge=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Xt.message,Xt.messageAndClick];b=vn({parsers:Me,handlers:ge,getMetadata:g,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),I=Ao(t,b),j.updateConfig(t),Ft(z,j.getMessages(),I),tt.render(t.suggestionChips,j,Z,void 0,t.suggestionChipsConfig),Gt(),zt(j.isStreaming());let re=(($s=t.voiceRecognition)==null?void 0:$s.enabled)===!0,Re=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=re&ℜif(Ye.classList.remove("tvw-gap-1","tvw-gap-3"),Ye.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),re&&Re)if(!M||!Le){let E=L(t.voiceRecognition,t.sendButton);E&&(M=E.micButton,Le=E.micButtonWrapper,Ye.insertBefore(Le,Ne),M.addEventListener("click",ot),M.disabled=j.isStreaming())}else{let E=(Ps=t.voiceRecognition)!=null?Ps:{},fe=(Os=t.sendButton)!=null?Os:{},te=(Ns=E.iconName)!=null?Ns:"mic",Ee=(Fs=fe.size)!=null?Fs:"40px",Ce=(Ds=E.iconSize)!=null?Ds:Ee,Ve=parseFloat(Ce)||24;M.style.width=Ce,M.style.height=Ce,M.style.minWidth=Ce,M.style.minHeight=Ce;let je=(_s=(js=E.iconColor)!=null?js:fe.textColor)!=null?_s:"currentColor";M.innerHTML="";let ut=ve(te,Ve,je,2);ut?M.appendChild(ut):M.textContent="\u{1F3A4}";let Ot=(qs=E.backgroundColor)!=null?qs:fe.backgroundColor;Ot?(M.style.backgroundColor=Ot,M.classList.remove("tvw-bg-cw-primary")):(M.style.backgroundColor="",M.classList.add("tvw-bg-cw-primary")),je?(M.style.color=je,M.classList.remove("tvw-text-white")):!je&&!fe.textColor&&(M.style.color="",M.classList.add("tvw-text-white")),E.borderWidth?(M.style.borderWidth=E.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),E.borderColor?M.style.borderColor=E.borderColor:M.style.borderColor="",E.paddingX?(M.style.paddingLeft=E.paddingX,M.style.paddingRight=E.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),E.paddingY?(M.style.paddingTop=E.paddingY,M.style.paddingBottom=E.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Te=Le==null?void 0:Le.querySelector(".tvw-send-button-tooltip"),he=(Us=E.tooltipText)!=null?Us:"Start voice recognition";if(((zs=E.showTooltip)!=null?zs:!1)&&he)if(Te)Te.textContent=he,Te.style.display="";else{let Ze=document.createElement("div");Ze.className="tvw-send-button-tooltip",Ze.textContent=he,Le==null||Le.insertBefore(Ze,M)}else Te&&(Te.style.display="none");Le.style.display="",M.disabled=j.isStreaming()}else M&&Le&&(Le.style.display="none",K&&ce());let ie=(Ys=t.sendButton)!=null?Ys:{},ct=(Js=ie.useIcon)!=null?Js:!1,Ht=(Ks=ie.iconText)!=null?Ks:"\u2191",Rt=ie.iconName,Mt=(Xs=ie.tooltipText)!=null?Xs:"Send message",jt=(Vs=ie.showTooltip)!=null?Vs:!1,It=(Gs=ie.size)!=null?Gs:"40px",_t=ie.backgroundColor,pt=ie.textColor;if(ct){if($.style.width=It,$.style.height=It,$.style.minWidth=It,$.style.minHeight=It,$.style.fontSize="18px",$.style.lineHeight="1",$.innerHTML="",Rt){let E=parseFloat(It)||24,fe=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",te=ve(Rt,E,fe,2);te?($.appendChild(te),$.style.color=fe):($.textContent=Ht,pt?$.style.color=pt:$.classList.add("tvw-text-white"))}else $.textContent=Ht,pt?$.style.color=pt:$.classList.add("tvw-text-white");$.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",_t?($.style.backgroundColor=_t,$.classList.remove("tvw-bg-cw-primary")):$.classList.add("tvw-bg-cw-primary")}else $.textContent=(Qs=(Zs=t.copy)==null?void 0:Zs.sendButtonLabel)!=null?Qs:"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",_t?($.style.backgroundColor=_t,$.classList.remove("tvw-bg-cw-accent")):$.classList.add("tvw-bg-cw-accent"),pt?$.style.color=pt:$.classList.add("tvw-text-white");ie.borderWidth?($.style.borderWidth=ie.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),ie.borderColor?$.style.borderColor=ie.borderColor:$.style.borderColor="",ie.paddingX?($.style.paddingLeft=ie.paddingX,$.style.paddingRight=ie.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),ie.paddingY?($.style.paddingTop=ie.paddingY,$.style.paddingBottom=ie.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let $t=Ne==null?void 0:Ne.querySelector(".tvw-send-button-tooltip");if(jt&&Mt)if($t)$t.textContent=Mt,$t.style.display="";else{let E=document.createElement("div");E.className="tvw-send-button-tooltip",E.textContent=Mt,Ne==null||Ne.insertBefore(E,$)}else $t&&($t.style.display="none");let Pt=(eo=t.statusIndicator)!=null?eo:{},pn=(to=Pt.visible)!=null?to:!0;if(Qe.style.display=pn?"":"none",j){let E=j.getStatus(),fe=te=>{var Ee,Ce,Ve,je;return te==="idle"?(Ee=Pt.idleText)!=null?Ee:ze.idle:te==="connecting"?(Ce=Pt.connectingText)!=null?Ce:ze.connecting:te==="connected"?(Ve=Pt.connectedText)!=null?Ve:ze.connected:te==="error"?(je=Pt.errorText)!=null?je:ze.error:ze[te]};Qe.textContent=fe(E)}},open(){w&&st(!0,"api")},close(){w&&st(!1,"api")},toggle(){w&&st(!x,"api")},clearChat(){j.clearMessages();try{localStorage.removeItem(Vt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vt}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Vt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}l={},b.syncFromMetadata()},setMessage(a){return!Z||j.isStreaming()?!1:(!x&&w&&st(!0,"system"),Z.value=a,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(j.isStreaming())return!1;let u=(a==null?void 0:a.trim())||Z.value.trim();return u?(!x&&w&&st(!0,"system"),Z.value="",j.sendMessage(u),!0):!1},startVoiceRecognition(){return K||j.isStreaming()||!Pe()?!1:(!x&&w&&st(!0,"system"),de.manuallyDeactivated=!1,be(),Oe("user"),!0)},stopVoiceRecognition(){return K?(de.manuallyDeactivated=!0,be(),ce("user"),!0):!1},injectTestMessage(a){!x&&w&&st(!0,"system"),j.injectTestEvent(a)},getMessages(){return j.getMessages()},getStatus(){return j.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,u){return s.on(a,u)},off(a,u){s.off(a,u)},isOpen(){return w&&x},isVoiceActive(){return de.active},getState(){return{open:w&&x,launcherEnabled:w,voiceActive:de.active,streaming:j.isStreaming()}},destroy(){$e.forEach(a=>a()),Q.remove(),h==null||h.destroy(),k==null||k.remove(),qe&&D.removeEventListener("click",qe)}};if((((ts=r==null?void 0:r.debugTools)!=null?ts:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,u={controller:xe,getMessages:xe.getMessages,getStatus:xe.getStatus,getMetadata:xe.getPersistentMetadata,updateMetadata:xe.updatePersistentMetadata,clearHistory:()=>xe.clearChat(),setVoiceActive:T=>T?xe.startVoiceRecognition():xe.stopVoiceRecognition()};window.AgentWidgetBrowser=u,$e.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}return xe};var Kn={},nr=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},sr=()=>{try{if(typeof Kn!="undefined"&&Kn.url)return new URL("../widget.css",Kn.url).href}catch{}return null},To=n=>{let e=sr(),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)}},Eo=n=>{var g,d,A,f;let e=nr(n.target),r=document.createElement("div");r.className="vanilla-agent-host";let t=(A=(d=(g=n.config)==null?void 0:g.launcher)==null?void 0:d.enabled)!=null?A:!0;t||(r.style.height="100%"),e.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let b=r.attachShadow({mode:"open"});i=b,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"),b.appendChild(s),To(b)}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),To(r);let l=Jn(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let c={...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]=c),c};function or(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 bn(n){var e,r;return(r=(e=n.parserType)!=null?e:or(n.streamParser))!=null?r:"plain"}function rr(n,e="esm"){let r={...n};return delete r.postprocessMessage,delete r.initialMessages,e==="esm"?ir(r):e==="script-installer"?dr(r):e==="script-advanced"?pr(r):e==="react-component"?ar(r):e==="react-advanced"?lr(r):cr(r)}function ir(n){let e=bn(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(`
|
|
57
|
-
`)}function
|
|
58
|
-
`)}function lr(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(`
|
|
59
|
-
`)}function
|
|
60
|
-
`)}function
|
|
61
|
-
`)}function pr(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(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
|
|
62
|
-
`)}var
|
|
56
|
+
`}if(!ue){let Ut="max-height: -moz-available !important; max-height: stretch !important;",Yt=a?"":"padding-top: 1.25em !important;";P.style.cssText+=Ut+Yt}};wt(),Ln(n,t);let $e=[],st=Co(De),Ue=null,U,lt=!1,Ae=!0,Oe=0,Z=0,Te=null,Ee=!1,ze=0,Je=!1,xt=125,kt=2e3,yt=5,Et=50,St=new Map,we={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Bt=(ts=(es=t.voiceRecognition)==null?void 0:es.autoResume)!=null?ts:!1,ke=a=>{s.emit("voice:state",{active:we.active,source:a,timestamp:Date.now()})},Ye=()=>{c(a=>({...a,voiceState:{active:we.active,timestamp:Date.now(),manuallyDeactivated:we.manuallyDeactivated}}))},At=()=>{var N,I;if(((N=t.voiceRecognition)==null?void 0:N.enabled)===!1)return;let a=Jn(l.voiceState),g=!!a.active,W=Number((I=a.timestamp)!=null?I:0);we.manuallyDeactivated=!!a.manuallyDeactivated,g&&Date.now()-W<or&&setTimeout(()=>{we.active||(we.manuallyDeactivated=!1,Se("restore"))},1e3)},Ft=()=>U?To(U.getMessages()).filter(a=>!a.__skipPersist):[];function Wt(a){if(!(i!=null&&i.save))return;let W={messages:a?To(a):U?Ft():[],metadata:l};try{let N=i.save(W);N instanceof Promise&&N.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)})}catch(N){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",N)}}let Dt=(a=!1)=>{if(!Ae)return;let g=Date.now();Ee&&g<ze&&!a||(Ee&&g>=ze&&(Ee=!1),!(!a&&!lt)&&(g-Z<xt||(Z=g,Te&&cancelAnimationFrame(Te),Te=requestAnimationFrame(()=>{Ee||!Ae||(Je=!0,F.scrollTop=F.scrollHeight,Oe=F.scrollTop,requestAnimationFrame(()=>{Je=!1}),Te=null)}))))},Mt=null,ln=()=>P.querySelector("#vanilla-agent-scroll-container")||F,dn=(a,g=500)=>{let W=a.scrollTop,N=a.clientHeight,I=a.scrollHeight,re=I-W;if(W+N>=I-2||Math.abs(re)<5)return;Mt!==null&&(cancelAnimationFrame(Mt),Mt=null);let C=performance.now(),G=k=>1-Math.pow(1-k,3),_=k=>{let z=a.scrollHeight;z!==I&&(I=z,re=I-W);let Be=k-C,ue=Math.min(Be/g,1),ie=G(ue),Pe=W+re*ie;a.scrollTop=Pe,ue<1?Mt=requestAnimationFrame(_):(a.scrollTop=a.scrollHeight,Mt=null)};Mt=requestAnimationFrame(_)},cn=a=>{let g=new Map;a.forEach(W=>{let N=St.get(W.id);g.set(W.id,{streaming:W.streaming,role:W.role}),!N&&W.role==="assistant"&&s.emit("assistant:message",W),W.role==="assistant"&&(N!=null&&N.streaming)&&W.streaming===!1&&s.emit("assistant:complete",W)}),St.clear(),g.forEach((W,N)=>{St.set(N,W)})},Nt=(a,g,W)=>{a.innerHTML="";let N=document.createDocumentFragment();g.forEach(C=>{var Be,ue;let G=null,_=r.find(ie=>!!(C.variant==="reasoning"&&ie.renderReasoning||C.variant==="tool"&&ie.renderToolCall||!C.variant&&ie.renderMessage)),k=(Be=t.layout)==null?void 0:Be.messages;if(_)if(C.variant==="reasoning"&&C.reasoning&&_.renderReasoning){if(!w)return;G=_.renderReasoning({message:C,defaultRenderer:()=>Rn(C),config:t})}else if(C.variant==="tool"&&C.toolCall&&_.renderToolCall){if(!K)return;G=_.renderToolCall({message:C,defaultRenderer:()=>Pn(C,t),config:t})}else _.renderMessage&&(G=_.renderMessage({message:C,defaultRenderer:()=>{let ie=rn(C,W,k,t.messageActions,T);return C.role!=="user"&&$n(ie,C,t,U),ie},config:t}));if(!G&&C.role==="assistant"&&!C.variant&&t.enableComponentStreaming!==!1&&Un(C)){let Pe=zn(C);if(Pe){let dt=qn(Pe,{config:t,message:C,transform:W});if(dt){let ae=document.createElement("div");if(ae.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),ae.setAttribute("data-message-id",C.id),C.content&&C.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=W({text:C.content,message:C,streaming:!!C.streaming,raw:C.rawContent}),ae.appendChild(ct)}ae.appendChild(dt),G=ae}}}if(!G)if(C.variant==="reasoning"&&C.reasoning){if(!w)return;G=Rn(C)}else if(C.variant==="tool"&&C.toolCall){if(!K)return;G=Pn(C,t)}else{let ie=(ue=t.layout)==null?void 0:ue.messages;ie!=null&&ie.renderUserMessage&&C.role==="user"?G=ie.renderUserMessage({message:C,config:t,streaming:!!C.streaming}):ie!=null&&ie.renderAssistantMessage&&C.role==="assistant"?G=ie.renderAssistantMessage({message:C,config:t,streaming:!!C.streaming}):G=rn(C,W,ie,t.messageActions,T),C.role!=="user"&&G&&$n(G,C,t,U)}let z=document.createElement("div");z.className="tvw-flex",C.role==="user"&&z.classList.add("tvw-justify-end"),z.appendChild(G),N.appendChild(z)});let I=g.some(C=>C.role==="assistant"&&C.streaming),re=g[g.length-1],H=(re==null?void 0:re.role)==="assistant"&&!re.streaming;if(lt&&g.some(C=>C.role==="user")&&!I&&!H){let C=fn(),G=document.createElement("div");G.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),G.appendChild(C);let _=document.createElement("div");_.className="tvw-flex",_.appendChild(G),N.appendChild(_)}a.appendChild(N),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let C=ln();dn(C)})})},jt=()=>{f&&(x?(P.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Y.classList.remove("tvw-scale-95","tvw-opacity-0"),Y.classList.add("tvw-scale-100","tvw-opacity-100"),B?B.element.style.display="none":V&&(V.style.display="none")):(P.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Y.classList.remove("tvw-scale-100","tvw-opacity-100"),Y.classList.add("tvw-scale-95","tvw-opacity-0"),B?B.element.style.display="":V&&(V.style.display="")))},ot=(a,g="user")=>{if(!f||x===a)return;let W=x;x=a,jt(),x&&(ye(),Dt(!0));let N={open:x,source:g,timestamp:Date.now()};x&&!W?s.emit("widget:opened",N):!x&&W&&s.emit("widget:closed",N),s.emit("widget:state",{open:x,launcherEnabled:f,voiceActive:we.active,streaming:U.isStreaming()})},Jt=a=>{$.disabled=a,L&&(L.disabled=a),st.buttons.forEach(g=>{g.disabled=a})},Zt=()=>{var I,re,H,C,G,_,k,z,Be,ue,ie,Pe,dt,ae;bt.textContent=(re=(I=t.copy)==null?void 0:I.welcomeTitle)!=null?re:"Hello \u{1F44B}",Ct.textContent=(C=(H=t.copy)==null?void 0:H.welcomeSubtitle)!=null?C:"Ask anything about your account or products.",oe.placeholder=(_=(G=t.copy)==null?void 0:G.inputPlaceholder)!=null?_:"How can I help...",((z=(k=t.sendButton)==null?void 0:k.useIcon)!=null?z:!1)||($.textContent=(ue=(Be=t.copy)==null?void 0:Be.sendButtonLabel)!=null?ue:"Send");let g=(Pe=(ie=t.theme)==null?void 0:ie.inputFontFamily)!=null?Pe:"sans-serif",W=(ae=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?ae:"400",N=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};oe.style.fontFamily=N(g),oe.style.fontWeight=W};U=new tn(t,{onMessagesChanged(a){Nt(ne,a,R),U&&(a.some(N=>N.role==="user")?st.render([],U,oe,a):st.render(t.suggestionChips,U,oe,a,t.suggestionChipsConfig)),Dt(!lt),cn(a);let g=[...a].reverse().find(W=>W.role==="user");we.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wt(a)},onStatusChanged(a){var N;let g=(N=t.statusIndicator)!=null?N:{},W=I=>{var re,H,C,G;return I==="idle"?(re=g.idleText)!=null?re:Ke.idle:I==="connecting"?(H=g.connectingText)!=null?H:Ke.connecting:I==="connected"?(C=g.connectedText)!=null?C:Ke.connected:I==="error"?(G=g.errorText)!=null?G:Ke.error:Ke[I]};tt.textContent=W(a)},onStreamingChanged(a){lt=a,Jt(a),U&&Nt(ne,U.getMessages(),R),a||Dt(!0)}}),d&&d.then(a=>{var g;a&&(a.metadata&&(l=Jn(a.metadata),b.syncFromMetadata()),(g=a.messages)!=null&&g.length&&U.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let Qt=a=>{a.preventDefault();let g=oe.value.trim();g&&(oe.value="",U.sendMessage(g))},S=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),$.click())},X=null,te=!1,be=null,xe=null,Ne=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Se=(a="user")=>{var re,H,C,G;if(te||U.isStreaming())return;let g=Ne();if(!g)return;X=new g;let N=(H=((re=t.voiceRecognition)!=null?re:{}).pauseDuration)!=null?H:2e3;X.continuous=!0,X.interimResults=!0,X.lang="en-US";let I=oe.value;X.onresult=_=>{let k="",z="";for(let ue=0;ue<_.results.length;ue++){let ie=_.results[ue],Pe=ie[0].transcript;ie.isFinal?k+=Pe+" ":z=Pe}let Be=I+k+z;oe.value=Be,be&&clearTimeout(be),(k||z)&&(be=window.setTimeout(()=>{let ue=oe.value.trim();ue&&X&&te&&(A(),oe.value="",U.sendMessage(ue,{viaVoice:!0}))},N))},X.onerror=_=>{_.error!=="no-speech"&&A()},X.onend=()=>{if(te){let _=oe.value.trim();_&&_!==I.trim()&&(oe.value="",U.sendMessage(_,{viaVoice:!0})),A()}};try{if(X.start(),te=!0,we.active=!0,a!=="system"&&(we.manuallyDeactivated=!1),ke(a),Ye(),L){xe={backgroundColor:L.style.backgroundColor,color:L.style.color,borderColor:L.style.borderColor};let _=(C=t.voiceRecognition)!=null?C:{},k=(G=_.recordingBackgroundColor)!=null?G:"#ef4444",z=_.recordingIconColor,Be=_.recordingBorderColor;if(L.classList.add("tvw-voice-recording"),L.style.backgroundColor=k,z){L.style.color=z;let ue=L.querySelector("svg");ue&&ue.setAttribute("stroke",z)}Be&&(L.style.borderColor=Be),L.setAttribute("aria-label","Stop voice recognition")}}catch{A("system")}},A=(a="user")=>{if(te){if(te=!1,be&&(clearTimeout(be),be=null),X){try{X.stop()}catch{}X=null}if(we.active=!1,ke(a),Ye(),L){if(L.classList.remove("tvw-voice-recording"),xe){L.style.backgroundColor=xe.backgroundColor,L.style.color=xe.color,L.style.borderColor=xe.borderColor;let g=L.querySelector("svg");g&&g.setAttribute("stroke",xe.color||"currentColor"),xe=null}L.setAttribute("aria-label","Start voice recognition")}}},gt=(a,g)=>{var Pe,dt,ae,ct,Ht,Rt,Lt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let N=p("div","tvw-send-button-wrapper"),I=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");I.type="button",I.setAttribute("aria-label","Start voice recognition");let re=(Pe=a==null?void 0:a.iconName)!=null?Pe:"mic",H=(dt=g==null?void 0:g.size)!=null?dt:"40px",C=(ae=a==null?void 0:a.iconSize)!=null?ae:H,G=parseFloat(C)||24,_=(ct=a==null?void 0:a.backgroundColor)!=null?ct:g==null?void 0:g.backgroundColor,k=(Ht=a==null?void 0:a.iconColor)!=null?Ht:g==null?void 0:g.textColor;I.style.width=C,I.style.height=C,I.style.minWidth=C,I.style.minHeight=C,I.style.fontSize="18px",I.style.lineHeight="1";let z=k||"currentColor",Be=le(re,G,z,1.5);Be?(I.appendChild(Be),I.style.color=z):(I.textContent="\u{1F3A4}",I.style.color=z),_?I.style.backgroundColor=_:I.classList.add("tvw-bg-cw-primary"),k?I.style.color=k:!k&&!(g!=null&&g.textColor)&&I.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(I.style.borderWidth=a.borderWidth,I.style.borderStyle="solid"),a!=null&&a.borderColor&&(I.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(I.style.paddingLeft=a.paddingX,I.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(I.style.paddingTop=a.paddingY,I.style.paddingBottom=a.paddingY),N.appendChild(I);let ue=(Rt=a==null?void 0:a.tooltipText)!=null?Rt:"Start voice recognition";if(((Lt=a==null?void 0:a.showTooltip)!=null?Lt:!1)&&ue){let _t=p("div","tvw-send-button-tooltip");_t.textContent=ue,N.appendChild(_t)}return{micButton:I,micButtonWrapper:N}},Q=()=>{if(te){let a=oe.value.trim();we.manuallyDeactivated=!0,Ye(),A("user"),a&&(oe.value="",U.sendMessage(a))}else we.manuallyDeactivated=!1,Ye(),Se("user")};L&&(L.addEventListener("click",Q),$e.push(()=>{A("system"),L&&L.removeEventListener("click",Q)}));let E=s.on("assistant:complete",()=>{Bt&&(we.active||we.manuallyDeactivated||Bt==="assistant"&&!we.lastUserMessageWasVoice||setTimeout(()=>{!we.active&&!we.manuallyDeactivated&&Se("auto")},600))});$e.push(E);let v=()=>{ot(!x,"user")},B=null,V=null;if(f){let a=r.find(g=>g.renderLauncher);if(a!=null&&a.renderLauncher){let g=a.renderLauncher({config:t,defaultRenderer:()=>nn(t,v).element,onToggle:v});g&&(V=g)}V||(B=nn(t,v))}B?n.appendChild(B.element):V&&n.appendChild(V),jt(),st.render(t.suggestionChips,U,oe,void 0,t.suggestionChipsConfig),Zt(),Jt(U.isStreaming()),Dt(!0),At();let ye=()=>{var W,N,I,re,H,C,G,_;let a=(N=(W=t.launcher)==null?void 0:W.sidebarMode)!=null?N:!1,g=a||((re=(I=t.launcher)==null?void 0:I.fullHeight)!=null?re:!1);if(!f){Y.style.height="",Y.style.width="";return}if(!a){let k=(C=(H=t==null?void 0:t.launcher)==null?void 0:H.width)!=null?C:t==null?void 0:t.launcherWidth,z=k!=null?k:"min(400px, calc(100vw - 24px))";Y.style.width=z,Y.style.maxWidth=z}if(!g){let k=window.innerHeight,z=64,Be=(_=(G=t.launcher)==null?void 0:G.heightOffset)!=null?_:0,ue=Math.max(200,k-z),ie=Math.min(640,ue),Pe=Math.max(200,ie-Be);Y.style.height=`${Pe}px`}};ye(),window.addEventListener("resize",ye),$e.push(()=>window.removeEventListener("resize",ye)),Oe=F.scrollTop;let Ge=()=>{let a=F.scrollTop,g=F.scrollHeight,W=F.clientHeight,N=g-a-W,I=Math.abs(a-Oe);if(Oe=a,!Je&&!(I<=yt)){if(!Ae&&N<Et){Ee=!1,Ae=!0;return}Ae&&N>Et&&(Ee=!0,ze=Date.now()+kt,Ae=!1)}};F.addEventListener("scroll",Ge,{passive:!0}),$e.push(()=>F.removeEventListener("scroll",Ge)),$e.push(()=>{Te&&cancelAnimationFrame(Te)});let Me=()=>{q&&(Ue&&(q.removeEventListener("click",Ue),Ue=null),f?(q.style.display="",Ue=()=>{x=!1,jt()},q.addEventListener("click",Ue)):q.style.display="none")};Me(),(()=>{let{clearChatButton:a}=fe;a&&a.addEventListener("click",()=>{U.clearMessages();try{localStorage.removeItem(Gt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(W){console.error("[AgentWidget] Failed to clear default localStorage:",W)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(W){console.error("[AgentWidget] Failed to clear custom localStorage:",W)}let g=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let W=i.clear();W instanceof Promise&&W.catch(N=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",N)})}catch(W){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",W)}l={},b.syncFromMetadata()})})(),Xe.addEventListener("submit",Qt),oe.addEventListener("keydown",S),$e.push(()=>{Xe.removeEventListener("submit",Qt),oe.removeEventListener("keydown",S)}),$e.push(()=>{U.cancel()}),B?$e.push(()=>{B==null||B.destroy()}):V&&$e.push(()=>{V==null||V.remove()});let ve={update(a){var en,Ut,Yt,ss,os,rs,is,as,ls,ds,cs,ps,us,gs,hs,ms,fs,ws,ys,vs,bs,Cs,xs,Ss,As,Ts,Es,Ws,Ms,Ls,ks,Bs,Hs,Rs,Is,Ps,$s,Os,Fs,Ds,Ns,js,_s,qs,Us,zs,Js,Ys,Ks,Xs,Vs,Gs,Zs,Qs,eo,to,no;let g=t.toolCall;t={...t,...a},wt(),Ln(n,t);let W=wn.getForInstance(t.plugins);if(r.length=0,r.push(...W),f=(Ut=(en=t.launcher)==null?void 0:en.enabled)!=null?Ut:!0,D=(ss=(Yt=t.launcher)==null?void 0:Yt.autoExpand)!=null?ss:!1,w=(rs=(os=t.features)==null?void 0:os.showReasoning)!=null?rs:!0,K=(as=(is=t.features)==null?void 0:is.showToolCalls)!=null?as:!0,((ls=t.launcher)==null?void 0:ls.enabled)===!1&&B&&(B.destroy(),B=null),((ds=t.launcher)==null?void 0:ds.enabled)===!1&&V&&(V.remove(),V=null),((cs=t.launcher)==null?void 0:cs.enabled)!==!1&&!B&&!V){let M=r.find(me=>me.renderLauncher);if(M!=null&&M.renderLauncher){let me=M.renderLauncher({config:t,defaultRenderer:()=>nn(t,v).element,onToggle:v});me&&(V=me,n.appendChild(V))}V||(B=nn(t,v),n.appendChild(B.element))}B&&B.update(t),mt&&((ps=t.launcher)==null?void 0:ps.title)!==void 0&&(mt.textContent=t.launcher.title),ft&&((us=t.launcher)==null?void 0:us.subtitle)!==void 0&&(ft.textContent=t.launcher.subtitle),f!==h?f?ot(D,"auto"):(x=!0,jt()):D!==j&&ot(D,"auto"),j=D,h=f,ye(),Me(),JSON.stringify(a.toolCall)!==JSON.stringify(g)&&U&&Nt(ne,U.getMessages(),R);let H=(gs=t.launcher)!=null?gs:{},C=(hs=H.headerIconHidden)!=null?hs:!1,G=H.headerIconName,_=(ms=H.headerIconSize)!=null?ms:"48px";if(he){let M=J.querySelector(".tvw-border-b-cw-divider"),me=M==null?void 0:M.querySelector(".tvw-flex-col");if(C)he.style.display="none",M&&me&&!M.contains(me)&&M.insertBefore(me,M.firstChild);else{if(he.style.display="",he.style.height=_,he.style.width=_,M&&me&&(M.contains(he)?he.nextSibling!==me&&(he.remove(),M.insertBefore(he,me)):M.insertBefore(he,me)),G){let Le=parseFloat(_)||24,Ce=le(G,Le*.6,"#ffffff",2);Ce?he.replaceChildren(Ce):he.textContent=(fs=H.agentIconText)!=null?fs:"\u{1F4AC}"}else if(H.iconUrl){let Le=he.querySelector("img");if(Le)Le.src=H.iconUrl,Le.style.height=_,Le.style.width=_;else{let Ce=document.createElement("img");Ce.src=H.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=_,Ce.style.width=_,he.replaceChildren(Ce)}}else{let Le=he.querySelector("svg"),Ce=he.querySelector("img");(Le||Ce)&&he.replaceChildren(),he.textContent=(ws=H.agentIconText)!=null?ws:"\u{1F4AC}"}let se=he.querySelector("img");se&&(se.style.height=_,se.style.width=_)}}if(q){let M=(ys=H.closeButtonSize)!=null?ys:"32px",me=(vs=H.closeButtonPlacement)!=null?vs:"inline";q.style.height=M,q.style.width=M;let{closeButtonWrapper:se}=fe,Le=me==="top-right",Ce=se==null?void 0:se.classList.contains("tvw-absolute");if(se&&Le!==Ce)if(se.remove(),Le)se.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",J.style.position="relative",J.appendChild(se);else{let ge=(Cs=(bs=H.clearChat)==null?void 0:bs.placement)!=null?Cs:"inline",Qe=(Ss=(xs=H.clearChat)==null?void 0:xs.enabled)!=null?Ss:!0;se.className=Qe&&ge==="inline"?"":"tvw-ml-auto";let et=J.querySelector(".tvw-border-b-cw-divider");et&&et.appendChild(se)}if(H.closeButtonColor?(q.style.color=H.closeButtonColor,q.classList.remove("tvw-text-cw-muted")):(q.style.color="",q.classList.add("tvw-text-cw-muted")),H.closeButtonBackgroundColor?(q.style.backgroundColor=H.closeButtonBackgroundColor,q.classList.remove("hover:tvw-bg-gray-100")):(q.style.backgroundColor="",q.classList.add("hover:tvw-bg-gray-100")),H.closeButtonBorderWidth||H.closeButtonBorderColor){let ge=H.closeButtonBorderWidth||"0px",Qe=H.closeButtonBorderColor||"transparent";q.style.border=`${ge} solid ${Qe}`,q.classList.remove("tvw-border-none")}else q.style.border="",q.classList.add("tvw-border-none");H.closeButtonBorderRadius?(q.style.borderRadius=H.closeButtonBorderRadius,q.classList.remove("tvw-rounded-full")):(q.style.borderRadius="",q.classList.add("tvw-rounded-full")),H.closeButtonPaddingX?(q.style.paddingLeft=H.closeButtonPaddingX,q.style.paddingRight=H.closeButtonPaddingX):(q.style.paddingLeft="",q.style.paddingRight=""),H.closeButtonPaddingY?(q.style.paddingTop=H.closeButtonPaddingY,q.style.paddingBottom=H.closeButtonPaddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Ze=(As=H.closeButtonIconName)!=null?As:"x",je=(Ts=H.closeButtonIconText)!=null?Ts:"\xD7";q.innerHTML="";let ut=le(Ze,"20px",H.closeButtonColor||"",2);ut?q.appendChild(ut):q.textContent=je;let Ot=(Es=H.closeButtonTooltipText)!=null?Es:"Close chat",We=(Ws=H.closeButtonShowTooltip)!=null?Ws:!0;if(q.setAttribute("aria-label",Ot),se&&(se._cleanupTooltip&&(se._cleanupTooltip(),delete se._cleanupTooltip),We&&Ot)){let ge=null,Qe=()=>{if(ge||!q)return;ge=p("div","tvw-clear-chat-tooltip"),ge.textContent=Ot;let Kt=p("div");Kt.className="tvw-clear-chat-tooltip-arrow",ge.appendChild(Kt);let xn=q.getBoundingClientRect();ge.style.position="fixed",ge.style.left=`${xn.left+xn.width/2}px`,ge.style.top=`${xn.top-8}px`,ge.style.transform="translate(-50%, -100%)",document.body.appendChild(ge)},et=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};se.addEventListener("mouseenter",Qe),se.addEventListener("mouseleave",et),q.addEventListener("focus",Qe),q.addEventListener("blur",et),se._cleanupTooltip=()=>{et(),se&&(se.removeEventListener("mouseenter",Qe),se.removeEventListener("mouseleave",et)),q&&(q.removeEventListener("focus",Qe),q.removeEventListener("blur",et))}}}let{clearChatButton:k,clearChatButtonWrapper:z}=fe;if(k){let M=(Ms=H.clearChat)!=null?Ms:{},me=(Ls=M.enabled)!=null?Ls:!0,se=(ks=M.placement)!=null?ks:"inline";if(z){z.style.display=me?"":"none";let Le=se==="top-right",Ce=z.classList.contains("tvw-absolute");if(Le!==Ce&&me){if(z.remove(),Le)z.className="tvw-absolute tvw-top-4 tvw-z-50",z.style.right="48px",J.style.position="relative",J.appendChild(z);else{z.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",z.style.right="";let je=J.querySelector(".tvw-border-b-cw-divider"),ut=fe.closeButtonWrapper;je&&ut&&ut.parentElement===je?je.insertBefore(z,ut):je&&je.appendChild(z)}let Ze=fe.closeButtonWrapper;Ze&&!Ze.classList.contains("tvw-absolute")&&(Le?Ze.classList.add("tvw-ml-auto"):Ze.classList.remove("tvw-ml-auto"))}}if(me){let Le=(Bs=M.size)!=null?Bs:"32px";k.style.height=Le,k.style.width=Le;let Ce=(Hs=M.iconName)!=null?Hs:"refresh-cw",Ze=(Rs=M.iconColor)!=null?Rs:"";k.innerHTML="";let je=le(Ce,"20px",Ze||"",2);if(je&&k.appendChild(je),Ze?(k.style.color=Ze,k.classList.remove("tvw-text-cw-muted")):(k.style.color="",k.classList.add("tvw-text-cw-muted")),M.backgroundColor?(k.style.backgroundColor=M.backgroundColor,k.classList.remove("hover:tvw-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let We=M.borderWidth||"0px",ge=M.borderColor||"transparent";k.style.border=`${We} solid ${ge}`,k.classList.remove("tvw-border-none")}else k.style.border="",k.classList.add("tvw-border-none");M.borderRadius?(k.style.borderRadius=M.borderRadius,k.classList.remove("tvw-rounded-full")):(k.style.borderRadius="",k.classList.add("tvw-rounded-full")),M.paddingX?(k.style.paddingLeft=M.paddingX,k.style.paddingRight=M.paddingX):(k.style.paddingLeft="",k.style.paddingRight=""),M.paddingY?(k.style.paddingTop=M.paddingY,k.style.paddingBottom=M.paddingY):(k.style.paddingTop="",k.style.paddingBottom="");let ut=(Is=M.tooltipText)!=null?Is:"Clear chat",Ot=(Ps=M.showTooltip)!=null?Ps:!0;if(k.setAttribute("aria-label",ut),z&&(z._cleanupTooltip&&(z._cleanupTooltip(),delete z._cleanupTooltip),Ot&&ut)){let We=null,ge=()=>{if(We||!k)return;We=p("div","tvw-clear-chat-tooltip"),We.textContent=ut;let et=p("div");et.className="tvw-clear-chat-tooltip-arrow",We.appendChild(et);let Kt=k.getBoundingClientRect();We.style.position="fixed",We.style.left=`${Kt.left+Kt.width/2}px`,We.style.top=`${Kt.top-8}px`,We.style.transform="translate(-50%, -100%)",document.body.appendChild(We)},Qe=()=>{We&&We.parentNode&&(We.parentNode.removeChild(We),We=null)};z.addEventListener("mouseenter",ge),z.addEventListener("mouseleave",Qe),k.addEventListener("focus",ge),k.addEventListener("blur",Qe),z._cleanupTooltip=()=>{Qe(),z&&(z.removeEventListener("mouseenter",ge),z.removeEventListener("mouseleave",Qe)),k&&(k.removeEventListener("focus",ge),k.removeEventListener("blur",Qe))}}}}let Be=t.actionParsers&&t.actionParsers.length?t.actionParsers:[yn],ue=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Vt.message,Vt.messageAndClick];b=vn({parsers:Be,handlers:ue,getMetadata:u,updateMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),R=Eo(t,b),U.updateConfig(t),Nt(ne,U.getMessages(),R),st.render(t.suggestionChips,U,oe,void 0,t.suggestionChipsConfig),Zt(),Jt(U.isStreaming());let ie=(($s=t.voiceRecognition)==null?void 0:$s.enabled)===!0,Pe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=ie&&Pe;if(Xe.classList.remove("tvw-gap-1","tvw-gap-3"),Xe.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),ie&&Pe)if(!L||!Re){let M=gt(t.voiceRecognition,t.sendButton);M&&(L=M.micButton,Re=M.micButtonWrapper,Xe.insertBefore(Re,qe),L.addEventListener("click",Q),L.disabled=U.isStreaming())}else{let M=(Os=t.voiceRecognition)!=null?Os:{},me=(Fs=t.sendButton)!=null?Fs:{},se=(Ds=M.iconName)!=null?Ds:"mic",Le=(Ns=me.size)!=null?Ns:"40px",Ce=(js=M.iconSize)!=null?js:Le,Ze=parseFloat(Ce)||24;L.style.width=Ce,L.style.height=Ce,L.style.minWidth=Ce,L.style.minHeight=Ce;let je=(qs=(_s=M.iconColor)!=null?_s:me.textColor)!=null?qs:"currentColor";L.innerHTML="";let ut=le(se,Ze,je,2);ut?L.appendChild(ut):L.textContent="\u{1F3A4}";let Ot=(Us=M.backgroundColor)!=null?Us:me.backgroundColor;Ot?(L.style.backgroundColor=Ot,L.classList.remove("tvw-bg-cw-primary")):(L.style.backgroundColor="",L.classList.add("tvw-bg-cw-primary")),je?(L.style.color=je,L.classList.remove("tvw-text-white")):!je&&!me.textColor&&(L.style.color="",L.classList.add("tvw-text-white")),M.borderWidth?(L.style.borderWidth=M.borderWidth,L.style.borderStyle="solid"):(L.style.borderWidth="",L.style.borderStyle=""),M.borderColor?L.style.borderColor=M.borderColor:L.style.borderColor="",M.paddingX?(L.style.paddingLeft=M.paddingX,L.style.paddingRight=M.paddingX):(L.style.paddingLeft="",L.style.paddingRight=""),M.paddingY?(L.style.paddingTop=M.paddingY,L.style.paddingBottom=M.paddingY):(L.style.paddingTop="",L.style.paddingBottom="");let We=Re==null?void 0:Re.querySelector(".tvw-send-button-tooltip"),ge=(zs=M.tooltipText)!=null?zs:"Start voice recognition";if(((Js=M.showTooltip)!=null?Js:!1)&&ge)if(We)We.textContent=ge,We.style.display="";else{let et=document.createElement("div");et.className="tvw-send-button-tooltip",et.textContent=ge,Re==null||Re.insertBefore(et,L)}else We&&(We.style.display="none");Re.style.display="",L.disabled=U.isStreaming()}else L&&Re&&(Re.style.display="none",te&&A());let ae=(Ys=t.sendButton)!=null?Ys:{},ct=(Ks=ae.useIcon)!=null?Ks:!1,Ht=(Xs=ae.iconText)!=null?Xs:"\u2191",Rt=ae.iconName,Lt=(Vs=ae.tooltipText)!=null?Vs:"Send message",_t=(Gs=ae.showTooltip)!=null?Gs:!1,It=(Zs=ae.size)!=null?Zs:"40px",qt=ae.backgroundColor,pt=ae.textColor;if(ct){if($.style.width=It,$.style.height=It,$.style.minWidth=It,$.style.minHeight=It,$.style.fontSize="18px",$.style.lineHeight="1",$.innerHTML="",Rt){let M=parseFloat(It)||24,me=pt&&typeof pt=="string"&&pt.trim()?pt.trim():"currentColor",se=le(Rt,M,me,2);se?($.appendChild(se),$.style.color=me):($.textContent=Ht,pt?$.style.color=pt:$.classList.add("tvw-text-white"))}else $.textContent=Ht,pt?$.style.color=pt:$.classList.add("tvw-text-white");$.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",qt?($.style.backgroundColor=qt,$.classList.remove("tvw-bg-cw-primary")):$.classList.add("tvw-bg-cw-primary")}else $.textContent=(eo=(Qs=t.copy)==null?void 0:Qs.sendButtonLabel)!=null?eo:"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",qt?($.style.backgroundColor=qt,$.classList.remove("tvw-bg-cw-accent")):$.classList.add("tvw-bg-cw-accent"),pt?$.style.color=pt:$.classList.add("tvw-text-white");ae.borderWidth?($.style.borderWidth=ae.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),ae.borderColor?$.style.borderColor=ae.borderColor:$.style.borderColor="",ae.paddingX?($.style.paddingLeft=ae.paddingX,$.style.paddingRight=ae.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),ae.paddingY?($.style.paddingTop=ae.paddingY,$.style.paddingBottom=ae.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let Pt=qe==null?void 0:qe.querySelector(".tvw-send-button-tooltip");if(_t&&Lt)if(Pt)Pt.textContent=Lt,Pt.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=Lt,qe==null||qe.insertBefore(M,$)}else Pt&&(Pt.style.display="none");let $t=(to=t.statusIndicator)!=null?to:{},pn=(no=$t.visible)!=null?no:!0;if(tt.style.display=pn?"":"none",U){let M=U.getStatus(),me=se=>{var Le,Ce,Ze,je;return se==="idle"?(Le=$t.idleText)!=null?Le:Ke.idle:se==="connecting"?(Ce=$t.connectingText)!=null?Ce:Ke.connecting:se==="connected"?(Ze=$t.connectedText)!=null?Ze:Ke.connected:se==="error"?(je=$t.errorText)!=null?je:Ke.error:Ke[se]};tt.textContent=me(M)}},open(){f&&ot(!0,"api")},close(){f&&ot(!1,"api")},toggle(){f&&ot(!x,"api")},clearChat(){U.clearMessages();try{localStorage.removeItem(Gt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",W)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}l={},b.syncFromMetadata()},setMessage(a){return!oe||U.isStreaming()?!1:(!x&&f&&ot(!0,"system"),oe.value=a,oe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(U.isStreaming())return!1;let g=(a==null?void 0:a.trim())||oe.value.trim();return g?(!x&&f&&ot(!0,"system"),oe.value="",U.sendMessage(g),!0):!1},startVoiceRecognition(){return te||U.isStreaming()||!Ne()?!1:(!x&&f&&ot(!0,"system"),we.manuallyDeactivated=!1,Ye(),Se("user"),!0)},stopVoiceRecognition(){return te?(we.manuallyDeactivated=!0,Ye(),A("user"),!0):!1},injectTestMessage(a){!x&&f&&ot(!0,"system"),U.injectTestEvent(a)},getMessages(){return U.getMessages()},getStatus(){return U.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){c(a)},on(a,g){return s.on(a,g)},off(a,g){s.off(a,g)},isOpen(){return f&&x},isVoiceActive(){return we.active},getState(){return{open:f&&x,launcherEnabled:f,voiceActive:we.active,streaming:U.isStreaming()}},destroy(){$e.forEach(a=>a()),P.remove(),B==null||B.destroy(),V==null||V.remove(),Ue&&q.removeEventListener("click",Ue)}};if((((ns=o==null?void 0:o.debugTools)!=null?ns:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,g={controller:ve,getMessages:ve.getMessages,getStatus:ve.getStatus,getMetadata:ve.getPersistentMetadata,updateMetadata:ve.updatePersistentMetadata,clearHistory:()=>ve.clearChat(),setVoiceActive:W=>W?ve.startVoiceRecognition():ve.stopVoiceRecognition()};window.AgentWidgetBrowser=g,$e.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=a)})}return ve};var Kn={},rr=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},ir=()=>{try{if(typeof Kn!="undefined"&&Kn.url)return new URL("../widget.css",Kn.url).href}catch{}return null},Wo=n=>{let e=ir(),o=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let r=t.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else o();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},Mo=n=>{var u,c,y,m;let e=rr(n.target),o=document.createElement("div");o.className="vanilla-agent-host";let t=(y=(c=(u=n.config)==null?void 0:u.launcher)==null?void 0:c.enabled)!=null?y:!0;t||(o.style.height="100%"),e.appendChild(o);let r=n.useShadowDom===!0,s,i;if(r){let b=o.attachShadow({mode:"open"});i=b,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"),b.appendChild(s),Wo(b)}else i=o,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"),o.appendChild(s),Wo(o);let l=Yn(s,n.config,{debugTools:n.debugTools});(m=n.onReady)==null||m.call(n);let d={...l,host:o,destroy(){l.destroy(),o.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=d),d};function ar(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function bn(n){var e,o;return(o=(e=n.parserType)!=null?e:ar(n.streamParser))!=null?o:"plain"}function lr(n,e="esm"){let o={...n};return delete o.postprocessMessage,delete o.initialMessages,e==="esm"?dr(o):e==="script-installer"?ur(o):e==="script-advanced"?hr(o):e==="react-component"?cr(o):e==="react-advanced"?pr(o):gr(o)}function dr(n){let e=bn(n),o=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}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
|
|
57
|
+
`)}function cr(n){let e=bn(n),o=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}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
|
|
58
|
+
`)}function pr(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(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"?e.push(` ${o}: ${t},`):typeof t=="number"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,t])=>{e.push(` ${o}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
|
|
59
|
+
`)}function ur(n){let e=bn(n),o=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
|
|
60
|
+
`)}function gr(n){let e=bn(n),o=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}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
|
|
61
|
+
`)}function hr(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(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"?e.push(` ${o}: ${t},`):typeof t=="number"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,t])=>{e.push(` ${o}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" }),"),e.push(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
|
|
62
|
+
`)}var ea=Mo;export{Xt as AgentWidgetClient,tn as AgentWidgetSession,He as DEFAULT_WIDGET_CONFIG,sn as attachHeaderToContainer,on as buildComposer,go as buildDefaultHeader,mo as buildExpandedHeader,zt as buildHeader,Bn as buildHeaderWithLayout,ho as buildMinimalHeader,an as componentRegistry,vn as createActionManager,Yn as createAgentExperience,Jo as createBubbleWithLayout,sr as createComponentMiddleware,_n as createComponentStreamParser,Ho as createDirectivePostprocessor,Oo as createFlexibleJsonStreamParser,Wn as createJsonStreamParser,Nn as createLocalStorageAdapter,un as createMarkdownProcessor,gn as createMarkdownProcessorFromConfig,bo as createMessageActions,Tn as createPlainTextParser,En as createRegexJsonParser,rn as createStandardBubble,fn as createTypingIndicator,Mn as createXmlParser,ea as default,Vt as defaultActionHandlers,yn as defaultJsonActionParser,Ro as directivePostprocessor,Sn as escapeHtml,zn as extractComponentDirectiveFromMessage,lr as generateCodeSnippet,fo as getHeaderLayout,Un as hasComponentDirective,kn as headerLayouts,Mo as initAgentWidget,nr as isComponentDirectiveType,oo as markdownPostprocessor,Fn as mergeWithDefaults,wn as pluginRegistry,qn as renderComponentDirective};
|
|
63
63
|
//# sourceMappingURL=index.js.map
|