vanilla-agent 1.26.0 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +20 -20
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/utils/code-generators.ts +36 -5
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import{Marked as Jo}from"marked";var Yo=n=>{if(n)return n},gn=n=>{var r,o;let t=n==null?void 0:n.markedOptions,s=new Jo({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=Yo(n==null?void 0:n.renderer);return e&&s.use({renderer:e}),i=>s.parse(i)},mn=n=>n?gn({markedOptions:n.options,renderer:n.renderer}):gn(),Ko=gn(),wo=n=>Ko(n),Wn=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),yo=n=>n.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),fo=n=>`%%FORM_PLACEHOLDER_${n}%%`,vo=(n,t)=>{let s=n;return s=s.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,r)=>{try{let o=JSON.parse(r.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let i=fo(t.length);return t.push({token:i,type:String(o.type)}),i}}catch{return e}return e}),s=s.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let o=fo(t.length);return t.push({token:o,type:r}),o}),s},Xo=n=>{let t=mn(n);return s=>{let e=[],r=vo(s,e),o=t(r);return e.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),w=`<div class="tvw-form-directive" data-tv-form="${yo(l)}"></div>`;o=o.replace(d,w)}),o}},Vo=n=>{let t=[],s=vo(n,t),e=wo(s);return t.forEach(({token:r,type:o})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${yo(o)}"></div>`;e=e.replace(i,d)}),e};import{parse as bo,STR as Co,OBJ as xo}from"partial-json";var hn=n=>n.replace(/\\n/g,`
|
|
2
2
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ln=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)}},Go=n=>{var i,l;let t=(i=n.completedAt)!=null?i:Date.now(),s=(l=n.startedAt)!=null?l:t,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-s))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},So=n=>n.status==="complete"?Go(n):n.status==="pending"?"Waiting":"",Qo=n=>{var r,o,i;let s=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((r=n.completedAt)!=null?r:Date.now())-((i=(o=n.startedAt)!=null?o:n.completedAt)!=null?i:Date.now())))/1e3;return s<.1?"Used tool for <0.1 seconds":`Used tool for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`};var Ao=n=>n.status==="complete"?Qo(n):"Using tool...",Zo=()=>{let n=null,t=0,s=e=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=e.match(r);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=e.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 e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let o=s(e);return o!==null&&(n=o),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},fn=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Bn=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Hn=()=>{var t;let n=Zo();return{processChunk:async s=>{let e=s.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(s)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},Rn=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:s=>{let e=s.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(s.length<=t)return n!==null||n===""?{text:n||"",raw:s}:null;try{let r=bo(s,Co|xo);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 t=s.length,n!==null?{text:n,raw:s}:null},close:()=>{}}},er=n=>{let t=null,s=0,r=n||(o=>{if(!o||typeof o!="object")return null;let i=l=>typeof l=="string"?hn(l):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?hn(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return i(o.on_load_text)||i(o.text)||null;case"message":case"message_and_click":case"checkout":return i(o.text)||null;default:return i(o.text)||i(o.display_text)||i(o.message)||null}return i(o.text)||i(o.display_text)||i(o.message)||i(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let i=o.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(o.length<=s)return t!==null?{text:t,raw:o}:null;try{let l=bo(o,Co|xo),d=r(l);d!==null&&(t=d)}catch{}return s=o.length,{text:t||"",raw:o}},close:()=>{}}},Pn=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var tr="https://api.travrse.ai/v1/dispatch",To="https://api.travrse.ai";function nr(n){switch(n){case"json":return Rn;case"regex-json":return Hn;case"xml":return Pn;case"plain":default:return Bn}}var Xt=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var s,e,r;this.apiUrl=(s=t.apiUrl)!=null?s:tr,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:nr(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(t){var e;let s=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||To;return t==="init"?`${s}/v1/client/init`:`${s}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,s;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,(s=(t=this.config).onSessionInit)==null||s.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=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(!t.ok){let e=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${e.hint||e.error}`):t.status===403?new Error(`Origin not allowed: ${e.hint||e.error}`):new Error(e.error||"Failed to initialize session")}let s=await t.json();return{sessionId:s.session_id,expiresAt:new Date(s.expires_at),flow:s.flow,config:{welcomeMessage:s.config.welcome_message,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var s;return`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||To}/v1/client/feedback`}async sendFeedback(t){var o,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.message_id)throw new Error(`message_id is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(o=this.config).onSessionExpired)==null||i.call(o),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,message_id:t,type:s})}async submitCSATFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"csat",rating:t,comment:s})}async submitNPSFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"nps",rating:t,comment:s})}async dispatch(t,s){return this.isClientTokenMode()?this.dispatchClientToken(t,s):this.dispatchProxy(t,s)}async dispatchClientToken(t,s){var r,o,i,l;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),s({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(r=this.config).onSessionExpired)==null||o.call(r);let u=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:u}),u}let c=await this.buildPayload(t.messages),w={session_id:d.sessionId,messages:t.messages.map(u=>({id:u.id,role:u.role,content:u.rawContent||u.content})),...t.assistantMessageId&&{assistant_message_id:t.assistantMessageId},...c.metadata&&{metadata:c.metadata},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w);let y=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:e.signal});if(!y.ok){let u=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let g=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:g}),g}if(y.status===429){let g=new Error(u.hint||"Message limit reached for this session.");throw s({type:"error",error:g}),g}let C=new Error(u.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!y.body){let u=new Error("No response body received");throw s({type:"error",error:u}),u}s({type:"status",status:"connected"});try{await this.streamResponse(y.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&s({type:"error",error:c}),c}}async dispatchProxy(t,s){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),s({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();o={...o,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw s({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw s({type:"error",error:l}),l}s({type:"status",status:"connected"});try{await this.streamResponse(i.body,s)}finally{s({type:"status",status:"idle"})}}async buildPayload(t){let e={messages:t.slice().sort((r,o)=>{let i=new Date(r.createdAt).getTime(),l=new Date(o.createdAt).getTime();return i-l}).map(r=>({role:r.role,content:r.rawContent||r.content,createdAt:r.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async o=>{try{let i=await o({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(e.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...e},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return e}async handleCustomSSEEvent(t,s,e,r,o){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let l=()=>{if(e.current)return e.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return e.current=d,r(d),d};if(i.text!==void 0){let d=l();d.content+=i.text,r(d)}return i.done&&(e.current&&(e.current.streaming=!1,r(e.current)),s({type:"status",status:"idle"})),i.error&&s({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,s,e){var de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye,E,$e,V,Le,Ie,Fe,Ne,ut,At,vt,Wt,Lt,Nt,Et,Z,pt,bt,gt,Bt,an,Qt,Ot,Mt,ln,dn,cn,Mn,Dt,_t,Ke,Jt,Zt;let r=t.getReader(),o=new TextDecoder,i="",l=Date.now(),d=0,c=()=>l+d++,w=M=>{let ce=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,se=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,me=M.tools?M.tools.map(Se=>({...Se,chunks:Se.chunks?[...Se.chunks]:void 0})):void 0;return{...M,reasoning:ce,toolCall:se,tools:me}},y=M=>{s({type:"message",message:w(M)})},u=null,C={current:null},g=new Map,j=new Map,$={lastId:null,byStep:new Map},m={lastId:null,byCall:new Map},b=M=>{if(M==null)return null;try{return String(M)}catch{return null}},W=M=>{var ce,se,me,Se,Te;return b((Te=(Se=(me=(se=(ce=M.stepId)!=null?ce:M.step_id)!=null?se:M.step)!=null?me:M.parentId)!=null?Se:M.flowStepId)!=null?Te:M.flow_step_id)},v=M=>{var ce,se,me,Se,Te,Ee,L;return b((L=(Ee=(Te=(Se=(me=(se=(ce=M.callId)!=null?ce:M.call_id)!=null?se:M.requestId)!=null?me:M.request_id)!=null?Se:M.toolCallId)!=null?Te:M.tool_call_id)!=null?Ee:M.stepId)!=null?L:M.step_id)},N=()=>u||(u={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},y(u),u),x=(M,ce)=>{$.lastId=ce,M&&$.byStep.set(M,ce)},S=(M,ce)=>{var Te;let se=(Te=M.reasoningId)!=null?Te:M.id,me=W(M);if(se){let Ee=String(se);return x(me,Ee),Ee}if(me){let Ee=$.byStep.get(me);if(Ee)return $.lastId=Ee,Ee}if($.lastId&&!ce)return $.lastId;if(!ce)return null;let Se=`reason-${c()}`;return x(me,Se),Se},Y=M=>{let ce=g.get(M);if(ce)return ce;let se={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return g.set(M,se),y(se),se},R=(M,ce)=>{m.lastId=ce,M&&m.byCall.set(M,ce)},O=(M,ce)=>{var Te;let se=(Te=M.toolId)!=null?Te:M.id,me=v(M);if(se){let Ee=String(se);return R(me,Ee),Ee}if(me){let Ee=m.byCall.get(me);if(Ee)return m.lastId=Ee,Ee}if(m.lastId&&!ce)return m.lastId;if(!ce)return null;let Se=`tool-${c()}`;return R(me,Se),Se},G=M=>{let ce=j.get(M);if(ce)return ce;let se={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return j.set(M,se),y(se),se},D=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ce=Number(M);if(!Number.isNaN(ce)&&Number.isFinite(ce))return ce;let se=Date.parse(M);if(!Number.isNaN(se))return se}return Date.now()},U=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},Q=new Map,ie=new Map;for(;;){let{done:M,value:ce}=await r.read();if(M)break;i+=o.decode(ce,{stream:!0});let se=i.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let o=s(e);return o!==null&&(n=o),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},fn=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Bn=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Hn=()=>{var t;let n=Zo();return{processChunk:async s=>{let e=s.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(s)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},Rn=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:s=>{let e=s.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(s.length<=t)return n!==null||n===""?{text:n||"",raw:s}:null;try{let r=bo(s,Co|xo);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 t=s.length,n!==null?{text:n,raw:s}:null},close:()=>{}}},er=n=>{let t=null,s=0,r=n||(o=>{if(!o||typeof o!="object")return null;let i=l=>typeof l=="string"?hn(l):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?hn(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return i(o.on_load_text)||i(o.text)||null;case"message":case"message_and_click":case"checkout":return i(o.text)||null;default:return i(o.text)||i(o.display_text)||i(o.message)||null}return i(o.text)||i(o.display_text)||i(o.message)||i(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let i=o.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(o.length<=s)return t!==null?{text:t,raw:o}:null;try{let l=bo(o,Co|xo),d=r(l);d!==null&&(t=d)}catch{}return s=o.length,{text:t||"",raw:o}},close:()=>{}}},Pn=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var tr="https://api.travrse.ai/v1/dispatch",To="https://api.travrse.ai";function nr(n){switch(n){case"json":return Rn;case"regex-json":return Hn;case"xml":return Pn;case"plain":default:return Bn}}var Xt=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var s,e,r;this.apiUrl=(s=t.apiUrl)!=null?s:tr,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:nr(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(t){var e;let s=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||To;return t==="init"?`${s}/v1/client/init`:`${s}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,s;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,(s=(t=this.config).onSessionInit)==null||s.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=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(!t.ok){let e=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${e.hint||e.error}`):t.status===403?new Error(`Origin not allowed: ${e.hint||e.error}`):new Error(e.error||"Failed to initialize session")}let s=await t.json();return{sessionId:s.session_id,expiresAt:new Date(s.expires_at),flow:s.flow,config:{welcomeMessage:s.config.welcome_message,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var s;return`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||To}/v1/client/feedback`}async sendFeedback(t){var o,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.message_id)throw new Error(`message_id is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let l=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(o=this.config).onSessionExpired)==null||i.call(o),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,message_id:t,type:s})}async submitCSATFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"csat",rating:t,comment:s})}async submitNPSFeedback(t,s){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:e.sessionId,type:"nps",rating:t,comment:s})}async dispatch(t,s){return this.isClientTokenMode()?this.dispatchClientToken(t,s):this.dispatchProxy(t,s)}async dispatchClientToken(t,s){var r,o,i,l;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),s({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(r=this.config).onSessionExpired)==null||o.call(r);let u=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:u}),u}let c=await this.buildPayload(t.messages),w={session_id:d.sessionId,messages:t.messages.map(u=>({id:u.id,role:u.role,content:u.rawContent||u.content})),...t.assistantMessageId&&{assistant_message_id:t.assistantMessageId},...c.metadata&&{metadata:c.metadata},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w);let y=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:e.signal});if(!y.ok){let u=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clientSession=null,(l=(i=this.config).onSessionExpired)==null||l.call(i);let g=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:g}),g}if(y.status===429){let g=new Error(u.hint||"Message limit reached for this session.");throw s({type:"error",error:g}),g}let C=new Error(u.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!y.body){let u=new Error("No response body received");throw s({type:"error",error:u}),u}s({type:"status",status:"connected"});try{await this.streamResponse(y.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&s({type:"error",error:c}),c}}async dispatchProxy(t,s){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),s({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();o={...o,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw s({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw s({type:"error",error:l}),l}s({type:"status",status:"connected"});try{await this.streamResponse(i.body,s)}finally{s({type:"status",status:"idle"})}}async buildPayload(t){let e={messages:t.slice().sort((r,o)=>{let i=new Date(r.createdAt).getTime(),l=new Date(o.createdAt).getTime();return i-l}).map(r=>({role:r.role,content:r.rawContent||r.content,createdAt:r.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async o=>{try{let i=await o({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(e.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...e},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return e}async handleCustomSSEEvent(t,s,e,r,o){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let l=()=>{if(e.current)return e.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return e.current=d,r(d),d};if(i.text!==void 0){let d=l();d.content+=i.text,r(d)}return i.done&&(e.current&&(e.current.streaming=!1,r(e.current)),s({type:"status",status:"idle"})),i.error&&s({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,s,e){var de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye,E,$e,V,Le,Ie,Fe,Ne,ut,At,vt,Wt,Lt,Nt,Et,Z,pt,bt,gt,Bt,an,Qt,Ot,kt,ln,dn,cn,kn,Dt,_t,Ke,Jt,Zt;let r=t.getReader(),o=new TextDecoder,i="",l=Date.now(),d=0,c=()=>l+d++,w=k=>{let ce=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,se=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,me=k.tools?k.tools.map(Se=>({...Se,chunks:Se.chunks?[...Se.chunks]:void 0})):void 0;return{...k,reasoning:ce,toolCall:se,tools:me}},y=k=>{s({type:"message",message:w(k)})},u=null,C={current:null},g=new Map,j=new Map,$={lastId:null,byStep:new Map},m={lastId:null,byCall:new Map},b=k=>{if(k==null)return null;try{return String(k)}catch{return null}},W=k=>{var ce,se,me,Se,Te;return b((Te=(Se=(me=(se=(ce=k.stepId)!=null?ce:k.step_id)!=null?se:k.step)!=null?me:k.parentId)!=null?Se:k.flowStepId)!=null?Te:k.flow_step_id)},v=k=>{var ce,se,me,Se,Te,Ee,L;return b((L=(Ee=(Te=(Se=(me=(se=(ce=k.callId)!=null?ce:k.call_id)!=null?se:k.requestId)!=null?me:k.request_id)!=null?Se:k.toolCallId)!=null?Te:k.tool_call_id)!=null?Ee:k.stepId)!=null?L:k.step_id)},N=()=>u||(u={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},y(u),u),x=(k,ce)=>{$.lastId=ce,k&&$.byStep.set(k,ce)},S=(k,ce)=>{var Te;let se=(Te=k.reasoningId)!=null?Te:k.id,me=W(k);if(se){let Ee=String(se);return x(me,Ee),Ee}if(me){let Ee=$.byStep.get(me);if(Ee)return $.lastId=Ee,Ee}if($.lastId&&!ce)return $.lastId;if(!ce)return null;let Se=`reason-${c()}`;return x(me,Se),Se},Y=k=>{let ce=g.get(k);if(ce)return ce;let se={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:k,status:"streaming",chunks:[]}};return g.set(k,se),y(se),se},R=(k,ce)=>{m.lastId=ce,k&&m.byCall.set(k,ce)},O=(k,ce)=>{var Te;let se=(Te=k.toolId)!=null?Te:k.id,me=v(k);if(se){let Ee=String(se);return R(me,Ee),Ee}if(me){let Ee=m.byCall.get(me);if(Ee)return m.lastId=Ee,Ee}if(m.lastId&&!ce)return m.lastId;if(!ce)return null;let Se=`tool-${c()}`;return R(me,Se),Se},G=k=>{let ce=j.get(k);if(ce)return ce;let se={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:k,status:"pending"}};return j.set(k,se),y(se),se},D=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let ce=Number(k);if(!Number.isNaN(ce)&&Number.isFinite(ce))return ce;let se=Date.parse(k);if(!Number.isNaN(se))return se}return Date.now()},U=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Q=new Map,ie=new Map;for(;;){let{done:k,value:ce}=await r.read();if(k)break;i+=o.decode(ce,{stream:!0});let se=i.split(`
|
|
5
5
|
|
|
6
6
|
`);i=(de=se.pop())!=null?de:"";for(let me of se){let Se=me.split(`
|
|
7
|
-
`),Te="message",Ee="";for(let ae of Se)ae.startsWith("event:")?Te=ae.replace("event:","").trim():ae.startsWith("data:")&&(Ee+=ae.replace("data:","").trim());if(!Ee)continue;let L;try{L=JSON.parse(Ee)}catch(ae){s({type:"error",error:ae instanceof Error?ae:new Error("Failed to parse chat stream payload")});continue}let Oe=Te!=="message"?Te:(_=L.type)!=null?_:"message";if(this.parseSSEEvent){C.current=u;let ae=await this.handleCustomSSEEvent(L,s,C,y,c);if(C.current&&!u&&(u=C.current),ae)continue}if(Oe==="reason_start"){let ae=(ze=S(L,!0))!=null?ze:`reason-${c()}`,k=Y(ae);k.reasoning=(Ge=k.reasoning)!=null?Ge:{id:ae,status:"streaming",chunks:[]},k.reasoning.startedAt=(xt=k.reasoning.startedAt)!=null?xt:D((nt=L.startedAt)!=null?nt:L.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",y(k)}else if(Oe==="reason_chunk"){let ae=(q=(St=S(L,!1))!=null?St:S(L,!0))!=null?q:`reason-${c()}`,k=Y(ae);k.reasoning=(ve=k.reasoning)!=null?ve:{id:ae,status:"streaming",chunks:[]},k.reasoning.startedAt=(ft=k.reasoning.startedAt)!=null?ft:D((ht=L.startedAt)!=null?ht:L.timestamp);let A=(I=(st=(Qe=L.reasoningText)!=null?Qe:L.text)!=null?st:L.delta)!=null?I:"";if(A&&L.hidden!==!0&&k.reasoning.chunks.push(String(A)),k.reasoning.status=L.done?"complete":"streaming",L.done){k.reasoning.completedAt=D((Be=L.completedAt)!=null?Be:L.timestamp);let z=(at=k.reasoning.startedAt)!=null?at:Date.now();k.reasoning.durationMs=Math.max(0,((lt=k.reasoning.completedAt)!=null?lt:Date.now())-z)}k.streaming=k.reasoning.status!=="complete",y(k)}else if(Oe==="reason_complete"){let ae=(wt=(Tt=S(L,!1))!=null?Tt:S(L,!0))!=null?wt:`reason-${c()}`,k=g.get(ae);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=D((He=L.completedAt)!=null?He:L.timestamp);let z=(Je=k.reasoning.startedAt)!=null?Je:Date.now();k.reasoning.durationMs=Math.max(0,((yt=k.reasoning.completedAt)!=null?yt:Date.now())-z),k.streaming=!1,y(k)}let A=W(L);A&&$.byStep.delete(A)}else if(Oe==="tool_start"){let ae=(ot=O(L,!0))!=null?ot:`tool-${c()}`,k=G(ae),A=(Ye=k.toolCall)!=null?Ye:{id:ae,status:"pending"};A.name=(E=L.toolName)!=null?E:A.name,A.status="running",L.args!==void 0&&(A.args=L.args),A.startedAt=(V=A.startedAt)!=null?V:D(($e=L.startedAt)!=null?$e:L.timestamp),A.completedAt=void 0,A.durationMs=void 0,k.toolCall=A,k.streaming=!0,y(k)}else if(Oe==="tool_chunk"){let ae=(Ie=(Le=O(L,!1))!=null?Le:O(L,!0))!=null?Ie:`tool-${c()}`,k=G(ae),A=(Fe=k.toolCall)!=null?Fe:{id:ae,status:"running"};A.startedAt=(ut=A.startedAt)!=null?ut:D((Ne=L.startedAt)!=null?Ne:L.timestamp);let z=(Wt=(vt=(At=L.text)!=null?At:L.delta)!=null?vt:L.message)!=null?Wt:"";z&&(A.chunks=(Lt=A.chunks)!=null?Lt:[],A.chunks.push(String(z))),A.status="running",k.toolCall=A,k.streaming=!0,y(k)}else if(Oe==="tool_complete"){let ae=(Et=(Nt=O(L,!1))!=null?Nt:O(L,!0))!=null?Et:`tool-${c()}`,k=G(ae),A=(Z=k.toolCall)!=null?Z:{id:ae,status:"running"};if(A.status="complete",L.result!==void 0&&(A.result=L.result),typeof L.duration=="number"&&(A.duration=L.duration),A.completedAt=D((pt=L.completedAt)!=null?pt:L.timestamp),typeof L.duration=="number")A.durationMs=L.duration;else{let K=(bt=A.startedAt)!=null?bt:Date.now();A.durationMs=Math.max(0,((gt=A.completedAt)!=null?gt:Date.now())-K)}k.toolCall=A,k.streaming=!1,y(k);let z=v(L);z&&m.byCall.delete(z)}else if(Oe==="step_chunk"){let ae=L.stepType,k=L.executionType;if(ae==="tool"||k==="context")continue;let A=N(),z=(Ot=(Qt=(an=(Bt=L.text)!=null?Bt:L.delta)!=null?an:L.content)!=null?Qt:L.chunk)!=null?Ot:"";if(z){let X=((Mt=ie.get(A.id))!=null?Mt:"")+z;A.rawContent=X,Q.has(A.id)||Q.set(A.id,this.createStreamParser());let je=Q.get(A.id),Me=X.trim().startsWith("{")||X.trim().startsWith("[");if(Me&&ie.set(A.id,X),je.__isPlainTextParser===!0){A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A);continue}let qe=je.processChunk(X);if(qe instanceof Promise)qe.then(re=>{var Re;let Ce=typeof re=="string"?re:(Re=re==null?void 0:re.text)!=null?Re:null;if(Ce!==null&&Ce.trim()!==""){let fe=u;fe&&fe.id===A.id&&(fe.content=Ce,y(fe))}else if(!Me&&!X.trim().startsWith("<")){let fe=u;fe&&fe.id===A.id&&(fe.content+=z,ie.delete(fe.id),Q.delete(fe.id),fe.rawContent=void 0,y(fe))}}).catch(()=>{A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A)});else{let re=typeof qe=="string"?qe:(ln=qe==null?void 0:qe.text)!=null?ln:null;re!==null&&re.trim()!==""?(A.content=re,y(A)):!Me&&!X.trim().startsWith("<")&&(A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A))}}if(L.isComplete){let K=(cn=(dn=L.result)==null?void 0:dn.response)!=null?cn:A.content;if(K){let X=ie.get(A.id),je=X!=null?X:U(K);A.rawContent=je;let Me=Q.get(A.id),De=null,qe=!1;if(Me&&(De=Me.getExtractedText(),De===null&&(De=fn(je)),De===null)){let re=Me.processChunk(je);re instanceof Promise?(qe=!0,re.then(Ce=>{var fe;let Re=typeof Ce=="string"?Ce:(fe=Ce==null?void 0:Ce.text)!=null?fe:null;if(Re!==null){let _e=u;_e&&_e.id===A.id&&(_e.content=Re,_e.streaming=!1,Q.delete(_e.id),ie.delete(_e.id),y(_e))}})):De=typeof re=="string"?re:(Mn=re==null?void 0:re.text)!=null?Mn:null}if(!qe){De!==null&&De.trim()!==""?A.content=De:ie.has(A.id)||(A.content=U(K));let re=Q.get(A.id);if(re){let Ce=(Dt=re.close)==null?void 0:Dt.call(re);Ce instanceof Promise&&Ce.catch(()=>{}),Q.delete(A.id)}ie.delete(A.id),A.streaming=!1,y(A)}}}}else if(Oe==="step_complete"){let ae=L.stepType,k=L.executionType;if(ae==="tool"||k==="context")continue;let A=(_t=L.result)==null?void 0:_t.response,z=N();if(A!=null){let K=Q.get(z.id),X=!1,je=!1;if(K){let Me=K.getExtractedText(),De=ie.get(z.id),qe=De!=null?De:U(A);if(z.rawContent=qe,Me!==null&&Me.trim()!=="")z.content=Me,X=!0;else{let re=fn(qe);if(re!==null)z.content=re,X=!0;else{let Ce=K.processChunk(qe);if(Ce instanceof Promise)je=!0,Ce.then(Re=>{var _e;let fe=typeof Re=="string"?Re:(_e=Re==null?void 0:Re.text)!=null?_e:null;if(fe!==null&&fe.trim()!==""){let rt=u;rt&&rt.id===z.id&&(rt.content=fe,rt.streaming=!1,Q.delete(rt.id),ie.delete(rt.id),y(rt))}else{let rt=K.getExtractedText(),mt=u;mt&&mt.id===z.id&&(rt!==null&&rt.trim()!==""?mt.content=rt:ie.has(mt.id)||(mt.content=U(A)),mt.streaming=!1,Q.delete(mt.id),ie.delete(mt.id),y(mt))}});else{let Re=typeof Ce=="string"?Ce:(Ke=Ce==null?void 0:Ce.text)!=null?Ke:null;if(Re!==null&&Re.trim()!=="")z.content=Re,X=!0;else{let fe=K.getExtractedText();fe!==null&&fe.trim()!==""&&(z.content=fe,X=!0)}}}}}if(!je){if(!z.rawContent){let Me=ie.get(z.id);z.rawContent=Me!=null?Me:U(A)}if(!X&&!ie.has(z.id)&&(z.content=U(A)),K){let Me=(Jt=K.close)==null?void 0:Jt.call(K);Me instanceof Promise&&Me.catch(()=>{})}Q.delete(z.id),ie.delete(z.id),z.streaming=!1,y(z)}}else Q.delete(z.id),ie.delete(z.id),z.streaming=!1,y(z)}else if(Oe==="flow_complete"){let ae=(Zt=L.result)==null?void 0:Zt.response;if(ae!=null){let k=N(),A=ie.get(k.id),z=A!=null?A:U(ae);k.rawContent=z;let K=U(ae),X=Q.get(k.id);if(X){let De=fn(z);if(De!==null)K=De;else{let qe=X.processChunk(z);qe instanceof Promise&&qe.then(Ce=>{var fe;let Re=typeof Ce=="string"?Ce:(fe=Ce==null?void 0:Ce.text)!=null?fe:null;if(Re!==null){let _e=u;_e&&_e.id===k.id&&(_e.content=Re,_e.streaming=!1,y(_e))}});let re=X.getExtractedText();re!==null&&(K=re)}}Q.delete(k.id),ie.delete(k.id);let je=K!==k.content,Me=k.streaming!==!1;je&&(k.content=K),k.streaming=!1,(je||Me)&&y(k)}else if(u!==null){let k=u;Q.delete(k.id),ie.delete(k.id),k.streaming!==!1&&(k.streaming=!1,y(k))}s({type:"status",status:"idle"})}else Oe==="error"&&L.error&&s({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};function sr(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function In(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function $n(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var en=class{constructor(t={},s){this.config=t;this.callbacks=s;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=t=>{var s,e;t.type==="message"?this.upsertMessage(t.message):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null)):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(s=this.callbacks).onError)==null||e.call(s,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(r=>{var o;return{...r,sequence:(o=r.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Xt(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var t,s;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(s=(t=this.callbacks).onError)==null||s.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let s={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(s)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,s){return this.client.submitMessageFeedback(t,s)}async submitCSATFeedback(t,s){return this.client.submitCSATFeedback(t,s)}async submitNPSFeedback(t,s){return this.client.submitNPSFeedback(t,s)}updateConfig(t){this.config={...this.config,...t},this.client=new Xt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}async sendMessage(t,s){var c,w,y,u,C;let e=t.trim();if(!e)return;(c=this.abortController)==null||c.abort();let r=In(),o=$n(),i={id:r,role:"user",content:e,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(s==null?void 0:s.viaVoice)||!1};this.appendMessage(i),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:l.signal,assistantMessageId:o},this.handleEvent)}catch(g){let j={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(j),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(y=(w=this.callbacks).onError)==null||y.call(w,g):(C=(u=this.callbacks).onError)==null||C.call(u,new Error(String(g)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var r;return{...e,streaming:!1,sequence:(r=e.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){this.streaming!==t&&(this.streaming=t,this.callbacks.onStreamingChanged(t))}appendMessage(t){let s=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,s]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let s=this.ensureSequence(t),e=this.messages.findIndex(r=>r.id===s.id);if(e===-1){this.appendMessage(s);return}this.messages=this.messages.map((r,o)=>o===e?{...r,...s}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((s,e)=>{var d,c;let r=new Date(s.createdAt).getTime(),o=new Date(e.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let i=(d=s.sequence)!=null?d:0,l=(c=e.sequence)!=null?c:0;return i!==l?i-l:s.id.localeCompare(e.id)})}};var Fn=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},or=n=>{var o,i,l;let t=(o=n==null?void 0:n.colorScheme)!=null?o:"light",s=(i=n==null?void 0:n.theme)!=null?i:{},e=(l=n==null?void 0:n.darkTheme)!=null?l:s;return t==="light"?s:t==="dark"||Fn()==="dark"?e:s},Eo=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let s=new MutationObserver(()=>{n(Fn())});s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>s.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let s=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(Fn());s.addEventListener?(s.addEventListener("change",e),t.push(()=>s.removeEventListener("change",e))):s.addListener&&(s.addListener(e),t.push(()=>s.removeListener(e)))}return()=>{t.forEach(s=>s())}},wn=(n,t)=>{let s=or(t);Object.entries(s).forEach(([e,r])=>{if(r==null||r==="")return;let o=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${o}`,String(r))})};import*as rr from"lucide";var ge=(n,t=24,s="currentColor",e=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),o=rr[r];return o?ir(o,t,s,e):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function ir(n,t,s,e){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",s),r.setAttribute("stroke-width",String(e)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let i=o[0],l=o[1];if(l){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([c,w])=>{c!=="stroke"&&d.setAttribute(c,String(w))}),r.appendChild(d)}}}),r}var f=(n,t)=>{let s=document.createElement(n);return t&&(s.className=t),s};var Ve={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ct={"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 tn=(n,t)=>{let s=f("button");s.type="button",s.innerHTML=`
|
|
7
|
+
`),Te="message",Ee="";for(let ae of Se)ae.startsWith("event:")?Te=ae.replace("event:","").trim():ae.startsWith("data:")&&(Ee+=ae.replace("data:","").trim());if(!Ee)continue;let L;try{L=JSON.parse(Ee)}catch(ae){s({type:"error",error:ae instanceof Error?ae:new Error("Failed to parse chat stream payload")});continue}let Oe=Te!=="message"?Te:(_=L.type)!=null?_:"message";if(this.parseSSEEvent){C.current=u;let ae=await this.handleCustomSSEEvent(L,s,C,y,c);if(C.current&&!u&&(u=C.current),ae)continue}if(Oe==="reason_start"){let ae=(ze=S(L,!0))!=null?ze:`reason-${c()}`,M=Y(ae);M.reasoning=(Ge=M.reasoning)!=null?Ge:{id:ae,status:"streaming",chunks:[]},M.reasoning.startedAt=(xt=M.reasoning.startedAt)!=null?xt:D((nt=L.startedAt)!=null?nt:L.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",y(M)}else if(Oe==="reason_chunk"){let ae=(q=(St=S(L,!1))!=null?St:S(L,!0))!=null?q:`reason-${c()}`,M=Y(ae);M.reasoning=(ve=M.reasoning)!=null?ve:{id:ae,status:"streaming",chunks:[]},M.reasoning.startedAt=(ft=M.reasoning.startedAt)!=null?ft:D((ht=L.startedAt)!=null?ht:L.timestamp);let A=(I=(st=(Qe=L.reasoningText)!=null?Qe:L.text)!=null?st:L.delta)!=null?I:"";if(A&&L.hidden!==!0&&M.reasoning.chunks.push(String(A)),M.reasoning.status=L.done?"complete":"streaming",L.done){M.reasoning.completedAt=D((Be=L.completedAt)!=null?Be:L.timestamp);let z=(at=M.reasoning.startedAt)!=null?at:Date.now();M.reasoning.durationMs=Math.max(0,((lt=M.reasoning.completedAt)!=null?lt:Date.now())-z)}M.streaming=M.reasoning.status!=="complete",y(M)}else if(Oe==="reason_complete"){let ae=(wt=(Tt=S(L,!1))!=null?Tt:S(L,!0))!=null?wt:`reason-${c()}`,M=g.get(ae);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=D((He=L.completedAt)!=null?He:L.timestamp);let z=(Je=M.reasoning.startedAt)!=null?Je:Date.now();M.reasoning.durationMs=Math.max(0,((yt=M.reasoning.completedAt)!=null?yt:Date.now())-z),M.streaming=!1,y(M)}let A=W(L);A&&$.byStep.delete(A)}else if(Oe==="tool_start"){let ae=(ot=O(L,!0))!=null?ot:`tool-${c()}`,M=G(ae),A=(Ye=M.toolCall)!=null?Ye:{id:ae,status:"pending"};A.name=(E=L.toolName)!=null?E:A.name,A.status="running",L.args!==void 0&&(A.args=L.args),A.startedAt=(V=A.startedAt)!=null?V:D(($e=L.startedAt)!=null?$e:L.timestamp),A.completedAt=void 0,A.durationMs=void 0,M.toolCall=A,M.streaming=!0,y(M)}else if(Oe==="tool_chunk"){let ae=(Ie=(Le=O(L,!1))!=null?Le:O(L,!0))!=null?Ie:`tool-${c()}`,M=G(ae),A=(Fe=M.toolCall)!=null?Fe:{id:ae,status:"running"};A.startedAt=(ut=A.startedAt)!=null?ut:D((Ne=L.startedAt)!=null?Ne:L.timestamp);let z=(Wt=(vt=(At=L.text)!=null?At:L.delta)!=null?vt:L.message)!=null?Wt:"";z&&(A.chunks=(Lt=A.chunks)!=null?Lt:[],A.chunks.push(String(z))),A.status="running",M.toolCall=A,M.streaming=!0,y(M)}else if(Oe==="tool_complete"){let ae=(Et=(Nt=O(L,!1))!=null?Nt:O(L,!0))!=null?Et:`tool-${c()}`,M=G(ae),A=(Z=M.toolCall)!=null?Z:{id:ae,status:"running"};if(A.status="complete",L.result!==void 0&&(A.result=L.result),typeof L.duration=="number"&&(A.duration=L.duration),A.completedAt=D((pt=L.completedAt)!=null?pt:L.timestamp),typeof L.duration=="number")A.durationMs=L.duration;else{let K=(bt=A.startedAt)!=null?bt:Date.now();A.durationMs=Math.max(0,((gt=A.completedAt)!=null?gt:Date.now())-K)}M.toolCall=A,M.streaming=!1,y(M);let z=v(L);z&&m.byCall.delete(z)}else if(Oe==="step_chunk"){let ae=L.stepType,M=L.executionType;if(ae==="tool"||M==="context")continue;let A=N(),z=(Ot=(Qt=(an=(Bt=L.text)!=null?Bt:L.delta)!=null?an:L.content)!=null?Qt:L.chunk)!=null?Ot:"";if(z){let X=((kt=ie.get(A.id))!=null?kt:"")+z;A.rawContent=X,Q.has(A.id)||Q.set(A.id,this.createStreamParser());let je=Q.get(A.id),ke=X.trim().startsWith("{")||X.trim().startsWith("[");if(ke&&ie.set(A.id,X),je.__isPlainTextParser===!0){A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A);continue}let qe=je.processChunk(X);if(qe instanceof Promise)qe.then(re=>{var Re;let Ce=typeof re=="string"?re:(Re=re==null?void 0:re.text)!=null?Re:null;if(Ce!==null&&Ce.trim()!==""){let fe=u;fe&&fe.id===A.id&&(fe.content=Ce,y(fe))}else if(!ke&&!X.trim().startsWith("<")){let fe=u;fe&&fe.id===A.id&&(fe.content+=z,ie.delete(fe.id),Q.delete(fe.id),fe.rawContent=void 0,y(fe))}}).catch(()=>{A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A)});else{let re=typeof qe=="string"?qe:(ln=qe==null?void 0:qe.text)!=null?ln:null;re!==null&&re.trim()!==""?(A.content=re,y(A)):!ke&&!X.trim().startsWith("<")&&(A.content+=z,ie.delete(A.id),Q.delete(A.id),A.rawContent=void 0,y(A))}}if(L.isComplete){let K=(cn=(dn=L.result)==null?void 0:dn.response)!=null?cn:A.content;if(K){let X=ie.get(A.id),je=X!=null?X:U(K);A.rawContent=je;let ke=Q.get(A.id),De=null,qe=!1;if(ke&&(De=ke.getExtractedText(),De===null&&(De=fn(je)),De===null)){let re=ke.processChunk(je);re instanceof Promise?(qe=!0,re.then(Ce=>{var fe;let Re=typeof Ce=="string"?Ce:(fe=Ce==null?void 0:Ce.text)!=null?fe:null;if(Re!==null){let _e=u;_e&&_e.id===A.id&&(_e.content=Re,_e.streaming=!1,Q.delete(_e.id),ie.delete(_e.id),y(_e))}})):De=typeof re=="string"?re:(kn=re==null?void 0:re.text)!=null?kn:null}if(!qe){De!==null&&De.trim()!==""?A.content=De:ie.has(A.id)||(A.content=U(K));let re=Q.get(A.id);if(re){let Ce=(Dt=re.close)==null?void 0:Dt.call(re);Ce instanceof Promise&&Ce.catch(()=>{}),Q.delete(A.id)}ie.delete(A.id),A.streaming=!1,y(A)}}}}else if(Oe==="step_complete"){let ae=L.stepType,M=L.executionType;if(ae==="tool"||M==="context")continue;let A=(_t=L.result)==null?void 0:_t.response,z=N();if(A!=null){let K=Q.get(z.id),X=!1,je=!1;if(K){let ke=K.getExtractedText(),De=ie.get(z.id),qe=De!=null?De:U(A);if(z.rawContent=qe,ke!==null&&ke.trim()!=="")z.content=ke,X=!0;else{let re=fn(qe);if(re!==null)z.content=re,X=!0;else{let Ce=K.processChunk(qe);if(Ce instanceof Promise)je=!0,Ce.then(Re=>{var _e;let fe=typeof Re=="string"?Re:(_e=Re==null?void 0:Re.text)!=null?_e:null;if(fe!==null&&fe.trim()!==""){let rt=u;rt&&rt.id===z.id&&(rt.content=fe,rt.streaming=!1,Q.delete(rt.id),ie.delete(rt.id),y(rt))}else{let rt=K.getExtractedText(),mt=u;mt&&mt.id===z.id&&(rt!==null&&rt.trim()!==""?mt.content=rt:ie.has(mt.id)||(mt.content=U(A)),mt.streaming=!1,Q.delete(mt.id),ie.delete(mt.id),y(mt))}});else{let Re=typeof Ce=="string"?Ce:(Ke=Ce==null?void 0:Ce.text)!=null?Ke:null;if(Re!==null&&Re.trim()!=="")z.content=Re,X=!0;else{let fe=K.getExtractedText();fe!==null&&fe.trim()!==""&&(z.content=fe,X=!0)}}}}}if(!je){if(!z.rawContent){let ke=ie.get(z.id);z.rawContent=ke!=null?ke:U(A)}if(!X&&!ie.has(z.id)&&(z.content=U(A)),K){let ke=(Jt=K.close)==null?void 0:Jt.call(K);ke instanceof Promise&&ke.catch(()=>{})}Q.delete(z.id),ie.delete(z.id),z.streaming=!1,y(z)}}else Q.delete(z.id),ie.delete(z.id),z.streaming=!1,y(z)}else if(Oe==="flow_complete"){let ae=(Zt=L.result)==null?void 0:Zt.response;if(ae!=null){let M=N(),A=ie.get(M.id),z=A!=null?A:U(ae);M.rawContent=z;let K=U(ae),X=Q.get(M.id);if(X){let De=fn(z);if(De!==null)K=De;else{let qe=X.processChunk(z);qe instanceof Promise&&qe.then(Ce=>{var fe;let Re=typeof Ce=="string"?Ce:(fe=Ce==null?void 0:Ce.text)!=null?fe:null;if(Re!==null){let _e=u;_e&&_e.id===M.id&&(_e.content=Re,_e.streaming=!1,y(_e))}});let re=X.getExtractedText();re!==null&&(K=re)}}Q.delete(M.id),ie.delete(M.id);let je=K!==M.content,ke=M.streaming!==!1;je&&(M.content=K),M.streaming=!1,(je||ke)&&y(M)}else if(u!==null){let M=u;Q.delete(M.id),ie.delete(M.id),M.streaming!==!1&&(M.streaming=!1,y(M))}s({type:"status",status:"idle"})}else Oe==="error"&&L.error&&s({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};function sr(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function In(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function $n(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var en=class{constructor(t={},s){this.config=t;this.callbacks=s;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=t=>{var s,e;t.type==="message"?this.upsertMessage(t.message):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null)):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(e=(s=this.callbacks).onError)==null||e.call(s,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(r=>{var o;return{...r,sequence:(o=r.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Xt(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var t,s;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(s=(t=this.callbacks).onError)==null||s.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let s={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(s)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,s){return this.client.submitMessageFeedback(t,s)}async submitCSATFeedback(t,s){return this.client.submitCSATFeedback(t,s)}async submitNPSFeedback(t,s){return this.client.submitNPSFeedback(t,s)}updateConfig(t){this.config={...this.config,...t},this.client=new Xt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}async sendMessage(t,s){var c,w,y,u,C;let e=t.trim();if(!e)return;(c=this.abortController)==null||c.abort();let r=In(),o=$n(),i={id:r,role:"user",content:e,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(s==null?void 0:s.viaVoice)||!1};this.appendMessage(i),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:l.signal,assistantMessageId:o},this.handleEvent)}catch(g){let j={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(j),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(y=(w=this.callbacks).onError)==null||y.call(w,g):(C=(u=this.callbacks).onError)==null||C.call(u,new Error(String(g)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var s;(s=this.abortController)==null||s.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var r;return{...e,streaming:!1,sequence:(r=e.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){this.streaming!==t&&(this.streaming=t,this.callbacks.onStreamingChanged(t))}appendMessage(t){let s=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,s]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let s=this.ensureSequence(t),e=this.messages.findIndex(r=>r.id===s.id);if(e===-1){this.appendMessage(s);return}this.messages=this.messages.map((r,o)=>o===e?{...r,...s}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((s,e)=>{var d,c;let r=new Date(s.createdAt).getTime(),o=new Date(e.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let i=(d=s.sequence)!=null?d:0,l=(c=e.sequence)!=null?c:0;return i!==l?i-l:s.id.localeCompare(e.id)})}};var Fn=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},or=n=>{var o,i,l;let t=(o=n==null?void 0:n.colorScheme)!=null?o:"light",s=(i=n==null?void 0:n.theme)!=null?i:{},e=(l=n==null?void 0:n.darkTheme)!=null?l:s;return t==="light"?s:t==="dark"||Fn()==="dark"?e:s},Eo=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let s=new MutationObserver(()=>{n(Fn())});s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>s.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let s=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(Fn());s.addEventListener?(s.addEventListener("change",e),t.push(()=>s.removeEventListener("change",e))):s.addListener&&(s.addListener(e),t.push(()=>s.removeListener(e)))}return()=>{t.forEach(s=>s())}},wn=(n,t)=>{let s=or(t);Object.entries(s).forEach(([e,r])=>{if(r==null||r==="")return;let o=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${o}`,String(r))})};import*as rr from"lucide";var ge=(n,t=24,s="currentColor",e=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),o=rr[r];return o?ir(o,t,s,e):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function ir(n,t,s,e){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",s),r.setAttribute("stroke-width",String(e)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let i=o[0],l=o[1];if(l){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([c,w])=>{c!=="stroke"&&d.setAttribute(c,String(w))}),r.appendChild(d)}}}),r}var f=(n,t)=>{let s=document.createElement(n);return t&&(s.className=t),s};var Ve={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ct={"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 tn=(n,t)=>{let s=f("button");s.type="button",s.innerHTML=`
|
|
8
8
|
<span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
9
9
|
<img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
|
|
@@ -12,12 +12,12 @@ import{Marked as Jo}from"marked";var Yo=n=>{if(n)return n},gn=n=>{var r,o;let t=
|
|
|
12
12
|
<span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
15
|
-
`,s.addEventListener("click",t);let e=o=>{var m,b,W,v,N,x,S,Y,R,O,G,D;let i=(m=o.launcher)!=null?m:{},l=s.querySelector("[data-role='launcher-title']");l&&(l.textContent=(b=i.title)!=null?b:"Chat Assistant");let d=s.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(W=i.subtitle)!=null?W:"Get answers fast");let c=s.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let w=s.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let U=(v=i.agentIconSize)!=null?v:"40px";if(w.style.height=U,w.style.width=U,w.innerHTML="",i.agentIconName){let Q=parseFloat(U)||24,ie=ge(i.agentIconName,Q*.6,"#ffffff",2);ie?(w.appendChild(ie),w.style.display=""):(w.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(x=i.agentIconText)!=null?x:"\u{1F4AC}",w.style.display="")}let y=s.querySelector("[data-role='launcher-image']");if(y){let U=(S=i.agentIconSize)!=null?S:"40px";y.style.height=U,y.style.width=U,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let u=s.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let U=(Y=i.callToActionIconSize)!=null?Y:"32px";u.style.height=U,u.style.width=U,i.callToActionIconBackgroundColor?(u.style.backgroundColor=i.callToActionIconBackgroundColor,u.classList.remove("tvw-bg-cw-primary")):(u.style.backgroundColor="",u.classList.add("tvw-bg-cw-primary"));let Q=0;if(i.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=i.callToActionIconPadding,Q=(parseFloat(i.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),i.callToActionIconHidden)u.style.display="none";else if(u.style.display="",u.innerHTML="",i.callToActionIconName){let ie=parseFloat(U)||24,de=Math.max(ie-Q,8),_=ge(i.callToActionIconName,de,"currentColor",2);_?u.appendChild(_):u.textContent=(R=i.callToActionIconText)!=null?R:"\u2197"}else u.textContent=(O=i.callToActionIconText)!=null?O:"\u2197"}let C=i.position&&Ct[i.position]?Ct[i.position]:Ct["bottom-right"],g="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";s.className=`${g} ${C}`;let j="1px solid #e5e7eb",$="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";s.style.border=(G=i.border)!=null?G:j,s.style.boxShadow=(D=i.shadow)!=null?D:$},r=()=>{s.removeEventListener("click",t),s.remove()};return n&&e(n),{element:s,update:e,destroy:r}};var zt=n=>{var O,G,D,U,Q,ie,de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye,E,$e;let{config:t,showClose:s=!0}=n,e=f("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=(O=t==null?void 0:t.launcher)!=null?O:{},o=(G=r.headerIconSize)!=null?G:"48px",i=(D=r.closeButtonSize)!=null?D:"32px",l=(U=r.closeButtonPlacement)!=null?U:"inline",d=(Q=r.headerIconHidden)!=null?Q:!1,c=r.headerIconName,w=f("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=o,w.style.width=o,!d)if(c){let V=parseFloat(o)||24,Le=ge(c,V*.6,"#ffffff",2);Le?w.replaceChildren(Le):w.textContent=(de=(ie=t==null?void 0:t.launcher)==null?void 0:ie.agentIconText)!=null?de:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let V=f("img");V.src=t.launcher.iconUrl,V.alt="",V.className="tvw-rounded-xl tvw-object-cover",V.style.height=o,V.style.width=o,w.replaceChildren(V)}else w.textContent=(Ge=(ze=t==null?void 0:t.launcher)==null?void 0:ze.agentIconText)!=null?Ge:"\u{1F4AC}";let y=f("div","tvw-flex tvw-flex-col"),u=f("span","tvw-text-base tvw-font-semibold");u.textContent=(xt=(nt=t==null?void 0:t.launcher)==null?void 0:nt.title)!=null?xt:"Chat Assistant";let C=f("span","tvw-text-xs tvw-text-cw-muted");C.textContent=(q=(St=t==null?void 0:t.launcher)==null?void 0:St.subtitle)!=null?q:"Here to help you get answers fast",y.append(u,C),d?e.append(y):e.append(w,y);let g=(ve=r.clearChat)!=null?ve:{},j=(ht=g.enabled)!=null?ht:!0,$=(ft=g.placement)!=null?ft:"inline",m=null,b=null;if(j){let V=(Qe=g.size)!=null?Qe:"32px",Le=(st=g.iconName)!=null?st:"refresh-cw",Ie=(I=g.iconColor)!=null?I:"",Fe=(Be=g.backgroundColor)!=null?Be:"",Ne=(at=g.borderWidth)!=null?at:"",ut=(lt=g.borderColor)!=null?lt:"",At=(Tt=g.borderRadius)!=null?Tt:"",vt=(wt=g.paddingX)!=null?wt:"",Wt=(He=g.paddingY)!=null?He:"",Lt=(Je=g.tooltipText)!=null?Je:"Clear chat",Nt=(yt=g.showTooltip)!=null?yt:!0;b=f("div",$==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),$==="top-right"&&(b.style.right="48px"),m=f("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=V,m.style.width=V,m.type="button",m.setAttribute("aria-label",Lt);let Et=ge(Le,"20px",Ie||"",2);if(Et&&m.appendChild(Et),Ie&&(m.style.color=Ie,m.classList.remove("tvw-text-cw-muted")),Fe&&(m.style.backgroundColor=Fe,m.classList.remove("hover:tvw-bg-gray-100")),Ne||ut){let Z=Ne||"0px",pt=ut||"transparent";m.style.border=`${Z} solid ${pt}`,m.classList.remove("tvw-border-none")}if(At&&(m.style.borderRadius=At,m.classList.remove("tvw-rounded-full")),vt?(m.style.paddingLeft=vt,m.style.paddingRight=vt):(m.style.paddingLeft="",m.style.paddingRight=""),Wt?(m.style.paddingTop=Wt,m.style.paddingBottom=Wt):(m.style.paddingTop="",m.style.paddingBottom=""),b.appendChild(m),Nt&&Lt&&m&&b){let Z=null,pt=()=>{if(Z||!m)return;Z=f("div","tvw-clear-chat-tooltip"),Z.textContent=Lt;let gt=f("div");gt.className="tvw-clear-chat-tooltip-arrow",Z.appendChild(gt);let Bt=m.getBoundingClientRect();Z.style.position="fixed",Z.style.left=`${Bt.left+Bt.width/2}px`,Z.style.top=`${Bt.top-8}px`,Z.style.transform="translate(-50%, -100%)",document.body.appendChild(Z)},bt=()=>{Z&&Z.parentNode&&(Z.parentNode.removeChild(Z),Z=null)};b.addEventListener("mouseenter",pt),b.addEventListener("mouseleave",bt),m.addEventListener("focus",pt),m.addEventListener("blur",bt),b._cleanupTooltip=()=>{bt(),b&&(b.removeEventListener("mouseenter",pt),b.removeEventListener("mouseleave",bt)),m&&(m.removeEventListener("focus",pt),m.removeEventListener("blur",bt))}}$==="inline"&&e.appendChild(b)}let W=f("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":j&&$==="inline"?"":"tvw-ml-auto"),v=f("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let N=(ot=r.closeButtonTooltipText)!=null?ot:"Close chat",x=(Ye=r.closeButtonShowTooltip)!=null?Ye:!0;v.setAttribute("aria-label",N),v.style.display=s?"":"none";let S=(E=r.closeButtonIconName)!=null?E:"x",Y=($e=r.closeButtonIconText)!=null?$e:"\xD7",R=ge(S,"20px",r.closeButtonColor||"",2);if(R?v.appendChild(R):v.textContent=Y,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let V=r.closeButtonBorderWidth||"0px",Le=r.closeButtonBorderColor||"transparent";v.style.border=`${V} solid ${Le}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),W.appendChild(v),x&&N){let V=null,Le=()=>{if(V)return;V=f("div","tvw-clear-chat-tooltip"),V.textContent=N;let Fe=f("div");Fe.className="tvw-clear-chat-tooltip-arrow",V.appendChild(Fe);let Ne=v.getBoundingClientRect();V.style.position="fixed",V.style.left=`${Ne.left+Ne.width/2}px`,V.style.top=`${Ne.top-8}px`,V.style.transform="translate(-50%, -100%)",document.body.appendChild(V)},Ie=()=>{V&&V.parentNode&&(V.parentNode.removeChild(V),V=null)};W.addEventListener("mouseenter",Le),W.addEventListener("mouseleave",Ie),v.addEventListener("focus",Le),v.addEventListener("blur",Ie),W._cleanupTooltip=()=>{Ie(),W.removeEventListener("mouseenter",Le),W.removeEventListener("mouseleave",Ie),v.removeEventListener("focus",Le),v.removeEventListener("blur",Ie)}}return l!=="top-right"&&e.appendChild(W),{header:e,iconHolder:w,headerTitle:u,headerSubtitle:C,closeButton:v,closeButtonWrapper:W,clearChatButton:m,clearChatButtonWrapper:b}},nn=(n,t,s)=>{var i,l,d,c;let e=(i=s==null?void 0:s.launcher)!=null?i:{},r=(l=e.closeButtonPlacement)!=null?l:"inline",o=(c=(d=e.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),r==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var Mo=n=>zt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),ko=n=>{var g,j,$,m;let{config:t,showClose:s=!0,onClose:e}=n,r=(g=t==null?void 0:t.launcher)!=null?g:{},o=f("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=f("span","tvw-text-base tvw-font-semibold");i.textContent=(j=r.title)!=null?j:"Chat Assistant",o.appendChild(i);let l=($=r.closeButtonSize)!=null?$:"32px",d=f("div",""),c=f("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=l,c.style.width=l,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=s?"":"none";let w=(m=r.closeButtonIconName)!=null?m:"x",y=ge(w,"20px",r.closeButtonColor||"",2);y?c.appendChild(y):c.textContent="\xD7",e&&c.addEventListener("click",e),d.appendChild(c),o.appendChild(d);let u=f("div");u.style.display="none";let C=f("span");return C.style.display="none",{header:o,iconHolder:u,headerTitle:i,headerSubtitle:C,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Wo=n=>{var v,N,x,S,Y,R,O,G;let{config:t,showClose:s=!0,onClose:e,onClearChat:r}=n,o=(v=t==null?void 0:t.launcher)!=null?v:{},i=f("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=f("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=o.headerIconSize)!=null?N:"56px",c=f("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let w=o.headerIconName;if(w){let D=parseFloat(d)||24,U=ge(w,D*.5,"#ffffff",2);U?c.replaceChildren(U):c.textContent=(x=o.agentIconText)!=null?x:"\u{1F4AC}"}else if(o.iconUrl){let D=f("img");D.src=o.iconUrl,D.alt="",D.className="tvw-rounded-xl tvw-object-cover",D.style.height=d,D.style.width=d,c.replaceChildren(D)}else c.textContent=(S=o.agentIconText)!=null?S:"\u{1F4AC}";let y=f("div","tvw-flex tvw-flex-col tvw-flex-1"),u=f("span","tvw-text-lg tvw-font-semibold");u.textContent=(Y=o.title)!=null?Y:"Chat Assistant";let C=f("span","tvw-text-sm tvw-text-cw-muted");C.textContent=(R=o.subtitle)!=null?R:"Here to help you get answers fast",y.append(u,C),l.append(c,y);let g=(O=o.closeButtonSize)!=null?O:"32px",j=f("div",""),$=f("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");$.style.height=g,$.style.width=g,$.type="button",$.setAttribute("aria-label","Close chat"),$.style.display=s?"":"none";let m=(G=o.closeButtonIconName)!=null?G:"x",b=ge(m,"20px",o.closeButtonColor||"",2);b?$.appendChild(b):$.textContent="\xD7",e&&$.addEventListener("click",e),j.appendChild($),l.appendChild(j),i.appendChild(l);let W=f("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return W.textContent="Online and ready to help",i.appendChild(W),{header:i,iconHolder:c,headerTitle:u,headerSubtitle:C,closeButton:$,closeButtonWrapper:j,clearChatButton:null,clearChatButtonWrapper:null}},Nn={default:Mo,minimal:ko,expanded:Wo},Lo=n=>{var t;return(t=Nn[n])!=null?t:Nn.default},On=(n,t,s)=>{var i,l,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat}),w=f("div");w.style.display="none";let y=f("span"),u=f("span"),C=f("button");C.style.display="none";let g=f("div");return g.style.display="none",{header:c,iconHolder:w,headerTitle:y,headerSubtitle:u,closeButton:C,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",o=Lo(e)({config:n,showClose:(d=(l=t==null?void 0:t.showCloseButton)!=null?l:s==null?void 0:s.showClose)!=null?d:!0,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var ar=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},sn=n=>{var ie,de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye;let{config:t}=n,s=f("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=f("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((ie=t==null?void 0:t.voiceRecognition)==null?void 0:ie.enabled)===!0,o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=f("form",`tvw-widget-composer tvw-flex tvw-items-end ${r&&o?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);d.style.outline="none";let c=f("textarea");c.placeholder=(_=(de=t==null?void 0:t.copy)==null?void 0:de.inputPlaceholder)!=null?_:"Type your message\u2026",c.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",c.rows=1;let w=(Ge=(ze=t==null?void 0:t.theme)==null?void 0:ze.inputFontFamily)!=null?Ge:"sans-serif",y=(xt=(nt=t==null?void 0:t.theme)==null?void 0:nt.inputFontWeight)!=null?xt:"400";c.style.fontFamily=ar(w),c.style.fontWeight=y,c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.addEventListener("focus",()=>{c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.style.boxShadow="none"}),c.addEventListener("blur",()=>{c.style.border="none",c.style.outline="none"});let u=(St=t==null?void 0:t.sendButton)!=null?St:{},C=(q=u.useIcon)!=null?q:!1,g=(ve=u.iconText)!=null?ve:"\u2191",j=u.iconName,$=(ht=u.tooltipText)!=null?ht:"Send message",m=(ft=u.showTooltip)!=null?ft:!1,b=(Qe=u.size)!=null?Qe:"40px",W=u.backgroundColor,v=u.textColor,N=f("div","tvw-send-button-wrapper"),x=f("button",C?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(x.type="submit",C){if(x.style.width=b,x.style.height=b,x.style.minWidth=b,x.style.minHeight=b,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",j){let E=parseFloat(b)||24,$e=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",V=ge(j,E,$e,2);V?(x.appendChild(V),x.style.color=$e):(x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white"))}else x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white");W?x.style.backgroundColor=W:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(I=(st=t==null?void 0:t.copy)==null?void 0:st.sendButtonLabel)!=null?I:"Send",v?x.style.color=v:x.classList.add("tvw-text-white");if(u.borderWidth&&(x.style.borderWidth=u.borderWidth,x.style.borderStyle="solid"),u.borderColor&&(x.style.borderColor=u.borderColor),u.paddingX?(x.style.paddingLeft=u.paddingX,x.style.paddingRight=u.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),u.paddingY?(x.style.paddingTop=u.paddingY,x.style.paddingBottom=u.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),m&&$){let E=f("div","tvw-send-button-tooltip");E.textContent=$,N.appendChild(E)}N.appendChild(x);let S=(Be=t==null?void 0:t.voiceRecognition)!=null?Be:{},Y=S.enabled===!0,R=null,O=null,G=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Y&&G){O=f("div","tvw-send-button-wrapper"),R=f("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 E=(at=S.iconName)!=null?at:"mic",$e=(lt=S.iconSize)!=null?lt:b,V=parseFloat($e)||24,Le=(Tt=S.backgroundColor)!=null?Tt:W,Ie=(wt=S.iconColor)!=null?wt:v;R.style.width=$e,R.style.height=$e,R.style.minWidth=$e,R.style.minHeight=$e,R.style.fontSize="18px",R.style.lineHeight="1";let Fe=Ie||"currentColor",Ne=ge(E,V,Fe,1.5);Ne?(R.appendChild(Ne),R.style.color=Fe):(R.textContent="\u{1F3A4}",R.style.color=Fe),Le?R.style.backgroundColor=Le:R.classList.add("tvw-bg-cw-primary"),Ie?R.style.color=Ie:!Ie&&!v&&R.classList.add("tvw-text-white"),S.borderWidth&&(R.style.borderWidth=S.borderWidth,R.style.borderStyle="solid"),S.borderColor&&(R.style.borderColor=S.borderColor),S.paddingX&&(R.style.paddingLeft=S.paddingX,R.style.paddingRight=S.paddingX),S.paddingY&&(R.style.paddingTop=S.paddingY,R.style.paddingBottom=S.paddingY),O.appendChild(R);let ut=(He=S.tooltipText)!=null?He:"Start voice recognition";if(((Je=S.showTooltip)!=null?Je:!1)&&ut){let vt=f("div","tvw-send-button-tooltip");vt.textContent=ut,O.appendChild(vt)}}d.addEventListener("click",E=>{E.target!==x&&E.target!==N&&E.target!==R&&E.target!==O&&c.focus()}),d.append(c),O&&d.append(O),d.append(N);let D=f("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),U=(yt=t==null?void 0:t.statusIndicator)!=null?yt:{},Q=(ot=U.visible)!=null?ot:!0;return D.style.display=Q?"":"none",D.textContent=(Ye=U.idleText)!=null?Ye:"Online",s.append(e,d,D),{footer:s,suggestions:e,composerForm:d,textarea:c,sendButton:x,sendButtonWrapper:N,micButton:R,micButtonWrapper:O,statusText:D}};var Bo=n=>{var d,c,w,y,u,C,g;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let j=f("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),$=f("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),m=(y=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?y:"100%";return j.style.width=m,$.style.width="100%",j.appendChild($),{wrapper:j,panel:$}}let s=(u=n==null?void 0:n.launcher)!=null?u:{},e=s.position&&Ct[s.position]?Ct[s.position]:Ct["bottom-right"],r=f("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),o=f("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(g=(C=n==null?void 0:n.launcher)==null?void 0:C.width)!=null?g:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return o.style.width=l,o.style.maxWidth=l,r.appendChild(o),{wrapper:r,panel:o}},Ho=(n,t=!0)=>{var y,u,C,g,j;let s=f("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"),e=(y=n==null?void 0:n.layout)==null?void 0:y.header,r=e?On(n,e,{showClose:t}):zt({config:n,showClose:t}),o=f("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");o.id="vanilla-agent-scroll-container";let i=f("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=f("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(C=(u=n==null?void 0:n.copy)==null?void 0:u.welcomeTitle)!=null?C:"Hello \u{1F44B}";let d=f("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");d.textContent=(j=(g=n==null?void 0:n.copy)==null?void 0:g.welcomeSubtitle)!=null?j:"Ask anything about your account or products.",i.append(l,d);let c=f("div","tvw-flex tvw-flex-col tvw-gap-3");o.append(i,c);let w=sn({config:n});return nn(s,r,n),s.append(o,w.footer),{container:s,body:o,messagesWrapper:c,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.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:w.footer}};var yn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let s=document.createElement("div");s.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",s.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(t),n.appendChild(s),n.appendChild(e),n.appendChild(r),n},lr=(n,t)=>{let s=f("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let r=f("img");r.src=e,r.alt=t==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",s.appendChild(r)}else s.textContent=e,s.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else s.textContent=t==="user"?"U":"A",s.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return s},Ro=(n,t)=>{let s=f("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?s.textContent=t.format(e):s.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s},dr=(n,t="bubble")=>{let s=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):s.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":s.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:s.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return s},Po=(n,t,s)=>{var g,j,$,m,b,W;let e=(g=t.showCopy)!=null?g:!0,r=(j=t.showUpvote)!=null?j:!0,o=($=t.showDownvote)!=null?$:!0,i=(m=t.visibility)!=null?m:"hover",l=(b=t.align)!=null?b:"right",d=(W=t.layout)!=null?W:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],y=f("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`),u=null,C=(v,N,x,S)=>{let Y=document.createElement("button");Y.className="tvw-message-action-btn",Y.setAttribute("aria-label",N),Y.setAttribute("title",N),S&&Y.setAttribute("data-action",S);let R=ge(v,14,"currentColor",2);return R&&Y.appendChild(R),Y.addEventListener("click",O=>{O.preventDefault(),O.stopPropagation(),x()}),Y};if(e){let v=C("copy","Copy message",()=>{let N=n.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let x=ge("check",14,"currentColor",2);x&&(v.innerHTML="",v.appendChild(x)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let S=ge("copy",14,"currentColor",2);S&&(v.innerHTML="",v.appendChild(S))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),s!=null&&s.onCopy&&s.onCopy(n),t.onCopy&&t.onCopy(n)},"copy");y.appendChild(v)}if(r){let v=C("thumbs-up","Upvote",()=>{if(u==="upvote")u=null,v.classList.remove("tvw-message-action-active");else{let x=y.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),u="upvote",v.classList.add("tvw-message-action-active");let S={type:"upvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),t.onFeedback&&t.onFeedback(S)}},"upvote");y.appendChild(v)}if(o){let v=C("thumbs-down","Downvote",()=>{if(u==="downvote")u=null,v.classList.remove("tvw-message-action-active");else{let x=y.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),u="downvote",v.classList.add("tvw-message-action-active");let S={type:"downvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),t.onFeedback&&t.onFeedback(S)}},"downvote");y.appendChild(v)}return y},on=(n,t,s,e,r)=>{var W,v,N,x,S;let o=s!=null?s:{},i=(W=o.layout)!=null?W:"bubble",l=o.avatar,d=o.timestamp,c=(v=l==null?void 0:l.show)!=null?v:!1,w=(N=d==null?void 0:d.show)!=null?N:!1,y=(x=l==null?void 0:l.position)!=null?x:"left",u=(S=d==null?void 0:d.position)!=null?S:"below",C=dr(n.role,i),g=f("div",C.join(" ")),j=document.createElement("div");if(j.innerHTML=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),w&&u==="inline"&&n.createdAt){let Y=Ro(n,d);Y.classList.add("tvw-ml-2","tvw-inline"),j.appendChild(Y)}if(g.appendChild(j),w&&u==="below"&&n.createdAt){let Y=Ro(n,d);Y.classList.add("tvw-mt-1"),g.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=yn();g.appendChild(Y)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let Y=Po(n,e,r);g.appendChild(Y)}if(!c||n.role==="system")return g;let m=f("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),b=lr(l,n.role);return y==="right"||y==="left"&&n.role==="user"?m.append(g,b):m.append(b,g),g.classList.remove("tvw-max-w-[85%]"),g.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),m},cr=(n,t,s,e,r)=>{let o=s!=null?s:{};return n.role==="user"&&o.renderUserMessage?o.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&o.renderAssistantMessage?o.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):on(n,t,s,e,r)};var Dn=new Set,_n=n=>{let t=n.reasoning,s=f("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(!t)return s;let e=Dn.has(n.id),r=f("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",e?"true":"false");let o=f("div","tvw-flex tvw-flex-col tvw-text-left"),i=f("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",o.appendChild(i);let l=f("span","tvw-text-xs tvw-text-cw-primary");l.textContent=So(t),o.appendChild(l),t.status==="complete"?i.style.display="none":i.style.display="";let d=f("div","tvw-flex tvw-items-center"),w=ge(e?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=e?"Hide":"Show";let y=f("div","tvw-flex tvw-items-center tvw-ml-auto");y.append(d),r.append(o,y);let u=f("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");u.style.display=e?"":"none";let C=t.chunks.join(""),g=f("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");g.textContent=C||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),u.appendChild(g);let j=()=>{r.setAttribute("aria-expanded",e?"true":"false"),d.innerHTML="";let b=ge(e?"chevron-up":"chevron-down",16,"currentColor",2);b?d.appendChild(b):d.textContent=e?"Hide":"Show",u.style.display=e?"":"none"},$=()=>{e=!e,e?Dn.add(n.id):Dn.delete(n.id),j()};return r.addEventListener("pointerdown",m=>{m.preventDefault(),$()}),r.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),$())}),j(),s.append(r,u),s};var jn=new Set,qn=(n,t)=>{var $;let s=n.toolCall,e=($=t==null?void 0:t.toolCall)!=null?$:{},r=f("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(e.backgroundColor&&(r.style.backgroundColor=e.backgroundColor),e.borderColor&&(r.style.borderColor=e.borderColor),e.borderWidth&&(r.style.borderWidth=e.borderWidth),e.borderRadius&&(r.style.borderRadius=e.borderRadius),!s)return r;let o=jn.has(n.id),i=f("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",o?"true":"false"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let l=f("div","tvw-flex tvw-flex-col tvw-text-left"),d=f("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(d.style.color=e.headerTextColor),d.textContent=Ao(s),l.appendChild(d);let c=f("div","tvw-flex tvw-items-center"),w=e.toggleTextColor||e.headerTextColor||"currentColor",y=ge(o?"chevron-up":"chevron-down",16,w,2);y?c.appendChild(y):c.textContent=o?"Hide":"Show";let u=f("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");u.append(c),i.append(l,u);let C=f("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(C.style.display=o?"":"none",e.contentBackgroundColor&&(C.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(C.style.color=e.contentTextColor),e.contentPaddingX&&(C.style.paddingLeft=e.contentPaddingX,C.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(C.style.paddingTop=e.contentPaddingY,C.style.paddingBottom=e.contentPaddingY),s.name){let m=f("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?m.style.color=e.contentTextColor:e.headerTextColor&&(m.style.color=e.headerTextColor),m.textContent=s.name,C.appendChild(m)}if(s.args!==void 0){let m=f("div","tvw-space-y-1"),b=f("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(b.style.color=e.labelTextColor),b.textContent="Arguments";let W=f("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=Ln(s.args),m.append(b,W),C.appendChild(m)}if(s.chunks&&s.chunks.length){let m=f("div","tvw-space-y-1"),b=f("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(b.style.color=e.labelTextColor),b.textContent="Activity";let W=f("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=s.chunks.join(`
|
|
15
|
+
`,s.addEventListener("click",t);let e=o=>{var m,b,W,v,N,x,S,Y,R,O,G,D;let i=(m=o.launcher)!=null?m:{},l=s.querySelector("[data-role='launcher-title']");l&&(l.textContent=(b=i.title)!=null?b:"Chat Assistant");let d=s.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(W=i.subtitle)!=null?W:"Get answers fast");let c=s.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let w=s.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let U=(v=i.agentIconSize)!=null?v:"40px";if(w.style.height=U,w.style.width=U,w.innerHTML="",i.agentIconName){let Q=parseFloat(U)||24,ie=ge(i.agentIconName,Q*.6,"#ffffff",2);ie?(w.appendChild(ie),w.style.display=""):(w.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(x=i.agentIconText)!=null?x:"\u{1F4AC}",w.style.display="")}let y=s.querySelector("[data-role='launcher-image']");if(y){let U=(S=i.agentIconSize)!=null?S:"40px";y.style.height=U,y.style.width=U,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let u=s.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let U=(Y=i.callToActionIconSize)!=null?Y:"32px";u.style.height=U,u.style.width=U,i.callToActionIconBackgroundColor?(u.style.backgroundColor=i.callToActionIconBackgroundColor,u.classList.remove("tvw-bg-cw-primary")):(u.style.backgroundColor="",u.classList.add("tvw-bg-cw-primary"));let Q=0;if(i.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=i.callToActionIconPadding,Q=(parseFloat(i.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),i.callToActionIconHidden)u.style.display="none";else if(u.style.display="",u.innerHTML="",i.callToActionIconName){let ie=parseFloat(U)||24,de=Math.max(ie-Q,8),_=ge(i.callToActionIconName,de,"currentColor",2);_?u.appendChild(_):u.textContent=(R=i.callToActionIconText)!=null?R:"\u2197"}else u.textContent=(O=i.callToActionIconText)!=null?O:"\u2197"}let C=i.position&&Ct[i.position]?Ct[i.position]:Ct["bottom-right"],g="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";s.className=`${g} ${C}`;let j="1px solid #e5e7eb",$="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";s.style.border=(G=i.border)!=null?G:j,s.style.boxShadow=(D=i.shadow)!=null?D:$},r=()=>{s.removeEventListener("click",t),s.remove()};return n&&e(n),{element:s,update:e,destroy:r}};var zt=n=>{var O,G,D,U,Q,ie,de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye,E,$e;let{config:t,showClose:s=!0}=n,e=f("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=(O=t==null?void 0:t.launcher)!=null?O:{},o=(G=r.headerIconSize)!=null?G:"48px",i=(D=r.closeButtonSize)!=null?D:"32px",l=(U=r.closeButtonPlacement)!=null?U:"inline",d=(Q=r.headerIconHidden)!=null?Q:!1,c=r.headerIconName,w=f("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=o,w.style.width=o,!d)if(c){let V=parseFloat(o)||24,Le=ge(c,V*.6,"#ffffff",2);Le?w.replaceChildren(Le):w.textContent=(de=(ie=t==null?void 0:t.launcher)==null?void 0:ie.agentIconText)!=null?de:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let V=f("img");V.src=t.launcher.iconUrl,V.alt="",V.className="tvw-rounded-xl tvw-object-cover",V.style.height=o,V.style.width=o,w.replaceChildren(V)}else w.textContent=(Ge=(ze=t==null?void 0:t.launcher)==null?void 0:ze.agentIconText)!=null?Ge:"\u{1F4AC}";let y=f("div","tvw-flex tvw-flex-col"),u=f("span","tvw-text-base tvw-font-semibold");u.textContent=(xt=(nt=t==null?void 0:t.launcher)==null?void 0:nt.title)!=null?xt:"Chat Assistant";let C=f("span","tvw-text-xs tvw-text-cw-muted");C.textContent=(q=(St=t==null?void 0:t.launcher)==null?void 0:St.subtitle)!=null?q:"Here to help you get answers fast",y.append(u,C),d?e.append(y):e.append(w,y);let g=(ve=r.clearChat)!=null?ve:{},j=(ht=g.enabled)!=null?ht:!0,$=(ft=g.placement)!=null?ft:"inline",m=null,b=null;if(j){let V=(Qe=g.size)!=null?Qe:"32px",Le=(st=g.iconName)!=null?st:"refresh-cw",Ie=(I=g.iconColor)!=null?I:"",Fe=(Be=g.backgroundColor)!=null?Be:"",Ne=(at=g.borderWidth)!=null?at:"",ut=(lt=g.borderColor)!=null?lt:"",At=(Tt=g.borderRadius)!=null?Tt:"",vt=(wt=g.paddingX)!=null?wt:"",Wt=(He=g.paddingY)!=null?He:"",Lt=(Je=g.tooltipText)!=null?Je:"Clear chat",Nt=(yt=g.showTooltip)!=null?yt:!0;b=f("div",$==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),$==="top-right"&&(b.style.right="48px"),m=f("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=V,m.style.width=V,m.type="button",m.setAttribute("aria-label",Lt);let Et=ge(Le,"20px",Ie||"",2);if(Et&&m.appendChild(Et),Ie&&(m.style.color=Ie,m.classList.remove("tvw-text-cw-muted")),Fe&&(m.style.backgroundColor=Fe,m.classList.remove("hover:tvw-bg-gray-100")),Ne||ut){let Z=Ne||"0px",pt=ut||"transparent";m.style.border=`${Z} solid ${pt}`,m.classList.remove("tvw-border-none")}if(At&&(m.style.borderRadius=At,m.classList.remove("tvw-rounded-full")),vt?(m.style.paddingLeft=vt,m.style.paddingRight=vt):(m.style.paddingLeft="",m.style.paddingRight=""),Wt?(m.style.paddingTop=Wt,m.style.paddingBottom=Wt):(m.style.paddingTop="",m.style.paddingBottom=""),b.appendChild(m),Nt&&Lt&&m&&b){let Z=null,pt=()=>{if(Z||!m)return;Z=f("div","tvw-clear-chat-tooltip"),Z.textContent=Lt;let gt=f("div");gt.className="tvw-clear-chat-tooltip-arrow",Z.appendChild(gt);let Bt=m.getBoundingClientRect();Z.style.position="fixed",Z.style.left=`${Bt.left+Bt.width/2}px`,Z.style.top=`${Bt.top-8}px`,Z.style.transform="translate(-50%, -100%)",document.body.appendChild(Z)},bt=()=>{Z&&Z.parentNode&&(Z.parentNode.removeChild(Z),Z=null)};b.addEventListener("mouseenter",pt),b.addEventListener("mouseleave",bt),m.addEventListener("focus",pt),m.addEventListener("blur",bt),b._cleanupTooltip=()=>{bt(),b&&(b.removeEventListener("mouseenter",pt),b.removeEventListener("mouseleave",bt)),m&&(m.removeEventListener("focus",pt),m.removeEventListener("blur",bt))}}$==="inline"&&e.appendChild(b)}let W=f("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":j&&$==="inline"?"":"tvw-ml-auto"),v=f("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let N=(ot=r.closeButtonTooltipText)!=null?ot:"Close chat",x=(Ye=r.closeButtonShowTooltip)!=null?Ye:!0;v.setAttribute("aria-label",N),v.style.display=s?"":"none";let S=(E=r.closeButtonIconName)!=null?E:"x",Y=($e=r.closeButtonIconText)!=null?$e:"\xD7",R=ge(S,"20px",r.closeButtonColor||"",2);if(R?v.appendChild(R):v.textContent=Y,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let V=r.closeButtonBorderWidth||"0px",Le=r.closeButtonBorderColor||"transparent";v.style.border=`${V} solid ${Le}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),W.appendChild(v),x&&N){let V=null,Le=()=>{if(V)return;V=f("div","tvw-clear-chat-tooltip"),V.textContent=N;let Fe=f("div");Fe.className="tvw-clear-chat-tooltip-arrow",V.appendChild(Fe);let Ne=v.getBoundingClientRect();V.style.position="fixed",V.style.left=`${Ne.left+Ne.width/2}px`,V.style.top=`${Ne.top-8}px`,V.style.transform="translate(-50%, -100%)",document.body.appendChild(V)},Ie=()=>{V&&V.parentNode&&(V.parentNode.removeChild(V),V=null)};W.addEventListener("mouseenter",Le),W.addEventListener("mouseleave",Ie),v.addEventListener("focus",Le),v.addEventListener("blur",Ie),W._cleanupTooltip=()=>{Ie(),W.removeEventListener("mouseenter",Le),W.removeEventListener("mouseleave",Ie),v.removeEventListener("focus",Le),v.removeEventListener("blur",Ie)}}return l!=="top-right"&&e.appendChild(W),{header:e,iconHolder:w,headerTitle:u,headerSubtitle:C,closeButton:v,closeButtonWrapper:W,clearChatButton:m,clearChatButtonWrapper:b}},nn=(n,t,s)=>{var i,l,d,c;let e=(i=s==null?void 0:s.launcher)!=null?i:{},r=(l=e.closeButtonPlacement)!=null?l:"inline",o=(c=(d=e.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),r==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var ko=n=>zt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Mo=n=>{var g,j,$,m;let{config:t,showClose:s=!0,onClose:e}=n,r=(g=t==null?void 0:t.launcher)!=null?g:{},o=f("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=f("span","tvw-text-base tvw-font-semibold");i.textContent=(j=r.title)!=null?j:"Chat Assistant",o.appendChild(i);let l=($=r.closeButtonSize)!=null?$:"32px",d=f("div",""),c=f("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=l,c.style.width=l,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=s?"":"none";let w=(m=r.closeButtonIconName)!=null?m:"x",y=ge(w,"20px",r.closeButtonColor||"",2);y?c.appendChild(y):c.textContent="\xD7",e&&c.addEventListener("click",e),d.appendChild(c),o.appendChild(d);let u=f("div");u.style.display="none";let C=f("span");return C.style.display="none",{header:o,iconHolder:u,headerTitle:i,headerSubtitle:C,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Wo=n=>{var v,N,x,S,Y,R,O,G;let{config:t,showClose:s=!0,onClose:e,onClearChat:r}=n,o=(v=t==null?void 0:t.launcher)!=null?v:{},i=f("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=f("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=o.headerIconSize)!=null?N:"56px",c=f("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let w=o.headerIconName;if(w){let D=parseFloat(d)||24,U=ge(w,D*.5,"#ffffff",2);U?c.replaceChildren(U):c.textContent=(x=o.agentIconText)!=null?x:"\u{1F4AC}"}else if(o.iconUrl){let D=f("img");D.src=o.iconUrl,D.alt="",D.className="tvw-rounded-xl tvw-object-cover",D.style.height=d,D.style.width=d,c.replaceChildren(D)}else c.textContent=(S=o.agentIconText)!=null?S:"\u{1F4AC}";let y=f("div","tvw-flex tvw-flex-col tvw-flex-1"),u=f("span","tvw-text-lg tvw-font-semibold");u.textContent=(Y=o.title)!=null?Y:"Chat Assistant";let C=f("span","tvw-text-sm tvw-text-cw-muted");C.textContent=(R=o.subtitle)!=null?R:"Here to help you get answers fast",y.append(u,C),l.append(c,y);let g=(O=o.closeButtonSize)!=null?O:"32px",j=f("div",""),$=f("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");$.style.height=g,$.style.width=g,$.type="button",$.setAttribute("aria-label","Close chat"),$.style.display=s?"":"none";let m=(G=o.closeButtonIconName)!=null?G:"x",b=ge(m,"20px",o.closeButtonColor||"",2);b?$.appendChild(b):$.textContent="\xD7",e&&$.addEventListener("click",e),j.appendChild($),l.appendChild(j),i.appendChild(l);let W=f("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return W.textContent="Online and ready to help",i.appendChild(W),{header:i,iconHolder:c,headerTitle:u,headerSubtitle:C,closeButton:$,closeButtonWrapper:j,clearChatButton:null,clearChatButtonWrapper:null}},Nn={default:ko,minimal:Mo,expanded:Wo},Lo=n=>{var t;return(t=Nn[n])!=null?t:Nn.default},On=(n,t,s)=>{var i,l,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat}),w=f("div");w.style.display="none";let y=f("span"),u=f("span"),C=f("button");C.style.display="none";let g=f("div");return g.style.display="none",{header:c,iconHolder:w,headerTitle:y,headerSubtitle:u,closeButton:C,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",o=Lo(e)({config:n,showClose:(d=(l=t==null?void 0:t.showCloseButton)!=null?l:s==null?void 0:s.showClose)!=null?d:!0,onClose:s==null?void 0:s.onClose,onClearChat:s==null?void 0:s.onClearChat});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var ar=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},sn=n=>{var ie,de,_,ze,Ge,nt,xt,St,q,ve,ht,ft,Qe,st,I,Be,at,lt,Tt,wt,He,Je,yt,ot,Ye;let{config:t}=n,s=f("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=f("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((ie=t==null?void 0:t.voiceRecognition)==null?void 0:ie.enabled)===!0,o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),d=f("form",`tvw-widget-composer tvw-flex tvw-items-end ${r&&o?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);d.style.outline="none";let c=f("textarea");c.placeholder=(_=(de=t==null?void 0:t.copy)==null?void 0:de.inputPlaceholder)!=null?_:"Type your message\u2026",c.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",c.rows=1;let w=(Ge=(ze=t==null?void 0:t.theme)==null?void 0:ze.inputFontFamily)!=null?Ge:"sans-serif",y=(xt=(nt=t==null?void 0:t.theme)==null?void 0:nt.inputFontWeight)!=null?xt:"400";c.style.fontFamily=ar(w),c.style.fontWeight=y,c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.addEventListener("focus",()=>{c.style.border="none",c.style.outline="none",c.style.borderWidth="0",c.style.borderStyle="none",c.style.borderColor="transparent",c.style.boxShadow="none"}),c.addEventListener("blur",()=>{c.style.border="none",c.style.outline="none"});let u=(St=t==null?void 0:t.sendButton)!=null?St:{},C=(q=u.useIcon)!=null?q:!1,g=(ve=u.iconText)!=null?ve:"\u2191",j=u.iconName,$=(ht=u.tooltipText)!=null?ht:"Send message",m=(ft=u.showTooltip)!=null?ft:!1,b=(Qe=u.size)!=null?Qe:"40px",W=u.backgroundColor,v=u.textColor,N=f("div","tvw-send-button-wrapper"),x=f("button",C?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(x.type="submit",C){if(x.style.width=b,x.style.height=b,x.style.minWidth=b,x.style.minHeight=b,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",j){let E=parseFloat(b)||24,$e=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",V=ge(j,E,$e,2);V?(x.appendChild(V),x.style.color=$e):(x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white"))}else x.textContent=g,v?x.style.color=v:x.classList.add("tvw-text-white");W?x.style.backgroundColor=W:x.classList.add("tvw-bg-cw-primary")}else x.textContent=(I=(st=t==null?void 0:t.copy)==null?void 0:st.sendButtonLabel)!=null?I:"Send",v?x.style.color=v:x.classList.add("tvw-text-white");if(u.borderWidth&&(x.style.borderWidth=u.borderWidth,x.style.borderStyle="solid"),u.borderColor&&(x.style.borderColor=u.borderColor),u.paddingX?(x.style.paddingLeft=u.paddingX,x.style.paddingRight=u.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),u.paddingY?(x.style.paddingTop=u.paddingY,x.style.paddingBottom=u.paddingY):(x.style.paddingTop="",x.style.paddingBottom=""),m&&$){let E=f("div","tvw-send-button-tooltip");E.textContent=$,N.appendChild(E)}N.appendChild(x);let S=(Be=t==null?void 0:t.voiceRecognition)!=null?Be:{},Y=S.enabled===!0,R=null,O=null,G=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Y&&G){O=f("div","tvw-send-button-wrapper"),R=f("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 E=(at=S.iconName)!=null?at:"mic",$e=(lt=S.iconSize)!=null?lt:b,V=parseFloat($e)||24,Le=(Tt=S.backgroundColor)!=null?Tt:W,Ie=(wt=S.iconColor)!=null?wt:v;R.style.width=$e,R.style.height=$e,R.style.minWidth=$e,R.style.minHeight=$e,R.style.fontSize="18px",R.style.lineHeight="1";let Fe=Ie||"currentColor",Ne=ge(E,V,Fe,1.5);Ne?(R.appendChild(Ne),R.style.color=Fe):(R.textContent="\u{1F3A4}",R.style.color=Fe),Le?R.style.backgroundColor=Le:R.classList.add("tvw-bg-cw-primary"),Ie?R.style.color=Ie:!Ie&&!v&&R.classList.add("tvw-text-white"),S.borderWidth&&(R.style.borderWidth=S.borderWidth,R.style.borderStyle="solid"),S.borderColor&&(R.style.borderColor=S.borderColor),S.paddingX&&(R.style.paddingLeft=S.paddingX,R.style.paddingRight=S.paddingX),S.paddingY&&(R.style.paddingTop=S.paddingY,R.style.paddingBottom=S.paddingY),O.appendChild(R);let ut=(He=S.tooltipText)!=null?He:"Start voice recognition";if(((Je=S.showTooltip)!=null?Je:!1)&&ut){let vt=f("div","tvw-send-button-tooltip");vt.textContent=ut,O.appendChild(vt)}}d.addEventListener("click",E=>{E.target!==x&&E.target!==N&&E.target!==R&&E.target!==O&&c.focus()}),d.append(c),O&&d.append(O),d.append(N);let D=f("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),U=(yt=t==null?void 0:t.statusIndicator)!=null?yt:{},Q=(ot=U.visible)!=null?ot:!0;return D.style.display=Q?"":"none",D.textContent=(Ye=U.idleText)!=null?Ye:"Online",s.append(e,d,D),{footer:s,suggestions:e,composerForm:d,textarea:c,sendButton:x,sendButtonWrapper:N,micButton:R,micButtonWrapper:O,statusText:D}};var Bo=n=>{var d,c,w,y,u,C,g;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let j=f("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),$=f("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),m=(y=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?y:"100%";return j.style.width=m,$.style.width="100%",j.appendChild($),{wrapper:j,panel:$}}let s=(u=n==null?void 0:n.launcher)!=null?u:{},e=s.position&&Ct[s.position]?Ct[s.position]:Ct["bottom-right"],r=f("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),o=f("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(g=(C=n==null?void 0:n.launcher)==null?void 0:C.width)!=null?g:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return o.style.width=l,o.style.maxWidth=l,r.appendChild(o),{wrapper:r,panel:o}},Ho=(n,t=!0)=>{var y,u,C,g,j;let s=f("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"),e=(y=n==null?void 0:n.layout)==null?void 0:y.header,r=e?On(n,e,{showClose:t}):zt({config:n,showClose:t}),o=f("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");o.id="vanilla-agent-scroll-container";let i=f("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=f("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(C=(u=n==null?void 0:n.copy)==null?void 0:u.welcomeTitle)!=null?C:"Hello \u{1F44B}";let d=f("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");d.textContent=(j=(g=n==null?void 0:n.copy)==null?void 0:g.welcomeSubtitle)!=null?j:"Ask anything about your account or products.",i.append(l,d);let c=f("div","tvw-flex tvw-flex-col tvw-gap-3");o.append(i,c);let w=sn({config:n});return nn(s,r,n),s.append(o,w.footer),{container:s,body:o,messagesWrapper:c,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.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:w.footer}};var yn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let s=document.createElement("div");s.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",s.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(t),n.appendChild(s),n.appendChild(e),n.appendChild(r),n},lr=(n,t)=>{let s=f("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let r=f("img");r.src=e,r.alt=t==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",s.appendChild(r)}else s.textContent=e,s.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else s.textContent=t==="user"?"U":"A",s.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return s},Ro=(n,t)=>{let s=f("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?s.textContent=t.format(e):s.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s},dr=(n,t="bubble")=>{let s=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):s.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":s.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:s.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?s.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):s.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return s},Po=(n,t,s)=>{var g,j,$,m,b,W;let e=(g=t.showCopy)!=null?g:!0,r=(j=t.showUpvote)!=null?j:!0,o=($=t.showDownvote)!=null?$:!0,i=(m=t.visibility)!=null?m:"hover",l=(b=t.align)!=null?b:"right",d=(W=t.layout)!=null?W:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[l],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],y=f("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`),u=null,C=(v,N,x,S)=>{let Y=document.createElement("button");Y.className="tvw-message-action-btn",Y.setAttribute("aria-label",N),Y.setAttribute("title",N),S&&Y.setAttribute("data-action",S);let R=ge(v,14,"currentColor",2);return R&&Y.appendChild(R),Y.addEventListener("click",O=>{O.preventDefault(),O.stopPropagation(),x()}),Y};if(e){let v=C("copy","Copy message",()=>{let N=n.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let x=ge("check",14,"currentColor",2);x&&(v.innerHTML="",v.appendChild(x)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let S=ge("copy",14,"currentColor",2);S&&(v.innerHTML="",v.appendChild(S))},2e3)}).catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",x)}),s!=null&&s.onCopy&&s.onCopy(n),t.onCopy&&t.onCopy(n)},"copy");y.appendChild(v)}if(r){let v=C("thumbs-up","Upvote",()=>{if(u==="upvote")u=null,v.classList.remove("tvw-message-action-active");else{let x=y.querySelector('[data-action="downvote"]');x&&x.classList.remove("tvw-message-action-active"),u="upvote",v.classList.add("tvw-message-action-active");let S={type:"upvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),t.onFeedback&&t.onFeedback(S)}},"upvote");y.appendChild(v)}if(o){let v=C("thumbs-down","Downvote",()=>{if(u==="downvote")u=null,v.classList.remove("tvw-message-action-active");else{let x=y.querySelector('[data-action="upvote"]');x&&x.classList.remove("tvw-message-action-active"),u="downvote",v.classList.add("tvw-message-action-active");let S={type:"downvote",messageId:n.id,message:n};s!=null&&s.onFeedback&&s.onFeedback(S),t.onFeedback&&t.onFeedback(S)}},"downvote");y.appendChild(v)}return y},on=(n,t,s,e,r)=>{var W,v,N,x,S;let o=s!=null?s:{},i=(W=o.layout)!=null?W:"bubble",l=o.avatar,d=o.timestamp,c=(v=l==null?void 0:l.show)!=null?v:!1,w=(N=d==null?void 0:d.show)!=null?N:!1,y=(x=l==null?void 0:l.position)!=null?x:"left",u=(S=d==null?void 0:d.position)!=null?S:"below",C=dr(n.role,i),g=f("div",C.join(" ")),j=document.createElement("div");if(j.innerHTML=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),w&&u==="inline"&&n.createdAt){let Y=Ro(n,d);Y.classList.add("tvw-ml-2","tvw-inline"),j.appendChild(Y)}if(g.appendChild(j),w&&u==="below"&&n.createdAt){let Y=Ro(n,d);Y.classList.add("tvw-mt-1"),g.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=yn();g.appendChild(Y)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let Y=Po(n,e,r);g.appendChild(Y)}if(!c||n.role==="system")return g;let m=f("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),b=lr(l,n.role);return y==="right"||y==="left"&&n.role==="user"?m.append(g,b):m.append(b,g),g.classList.remove("tvw-max-w-[85%]"),g.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),m},cr=(n,t,s,e,r)=>{let o=s!=null?s:{};return n.role==="user"&&o.renderUserMessage?o.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&o.renderAssistantMessage?o.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):on(n,t,s,e,r)};var Dn=new Set,_n=n=>{let t=n.reasoning,s=f("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(!t)return s;let e=Dn.has(n.id),r=f("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",e?"true":"false");let o=f("div","tvw-flex tvw-flex-col tvw-text-left"),i=f("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",o.appendChild(i);let l=f("span","tvw-text-xs tvw-text-cw-primary");l.textContent=So(t),o.appendChild(l),t.status==="complete"?i.style.display="none":i.style.display="";let d=f("div","tvw-flex tvw-items-center"),w=ge(e?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=e?"Hide":"Show";let y=f("div","tvw-flex tvw-items-center tvw-ml-auto");y.append(d),r.append(o,y);let u=f("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");u.style.display=e?"":"none";let C=t.chunks.join(""),g=f("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");g.textContent=C||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),u.appendChild(g);let j=()=>{r.setAttribute("aria-expanded",e?"true":"false"),d.innerHTML="";let b=ge(e?"chevron-up":"chevron-down",16,"currentColor",2);b?d.appendChild(b):d.textContent=e?"Hide":"Show",u.style.display=e?"":"none"},$=()=>{e=!e,e?Dn.add(n.id):Dn.delete(n.id),j()};return r.addEventListener("pointerdown",m=>{m.preventDefault(),$()}),r.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),$())}),j(),s.append(r,u),s};var jn=new Set,qn=(n,t)=>{var $;let s=n.toolCall,e=($=t==null?void 0:t.toolCall)!=null?$:{},r=f("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(e.backgroundColor&&(r.style.backgroundColor=e.backgroundColor),e.borderColor&&(r.style.borderColor=e.borderColor),e.borderWidth&&(r.style.borderWidth=e.borderWidth),e.borderRadius&&(r.style.borderRadius=e.borderRadius),!s)return r;let o=jn.has(n.id),i=f("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",o?"true":"false"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let l=f("div","tvw-flex tvw-flex-col tvw-text-left"),d=f("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(d.style.color=e.headerTextColor),d.textContent=Ao(s),l.appendChild(d);let c=f("div","tvw-flex tvw-items-center"),w=e.toggleTextColor||e.headerTextColor||"currentColor",y=ge(o?"chevron-up":"chevron-down",16,w,2);y?c.appendChild(y):c.textContent=o?"Hide":"Show";let u=f("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");u.append(c),i.append(l,u);let C=f("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(C.style.display=o?"":"none",e.contentBackgroundColor&&(C.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(C.style.color=e.contentTextColor),e.contentPaddingX&&(C.style.paddingLeft=e.contentPaddingX,C.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(C.style.paddingTop=e.contentPaddingY,C.style.paddingBottom=e.contentPaddingY),s.name){let m=f("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?m.style.color=e.contentTextColor:e.headerTextColor&&(m.style.color=e.headerTextColor),m.textContent=s.name,C.appendChild(m)}if(s.args!==void 0){let m=f("div","tvw-space-y-1"),b=f("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(b.style.color=e.labelTextColor),b.textContent="Arguments";let W=f("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=Ln(s.args),m.append(b,W),C.appendChild(m)}if(s.chunks&&s.chunks.length){let m=f("div","tvw-space-y-1"),b=f("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(b.style.color=e.labelTextColor),b.textContent="Activity";let W=f("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=s.chunks.join(`
|
|
16
16
|
`),m.append(b,W),C.appendChild(m)}if(s.status==="complete"&&s.result!==void 0){let m=f("div","tvw-space-y-1"),b=f("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(b.style.color=e.labelTextColor),b.textContent="Result";let W=f("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=Ln(s.result),m.append(b,W),C.appendChild(m)}if(s.status==="complete"&&typeof s.duration=="number"){let m=f("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(m.style.color=e.contentTextColor),m.textContent=`Duration: ${s.duration}ms`,C.appendChild(m)}let g=()=>{i.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let m=e.toggleTextColor||e.headerTextColor||"currentColor",b=ge(o?"chevron-up":"chevron-down",16,m,2);b?c.appendChild(b):c.textContent=o?"Hide":"Show",C.style.display=o?"":"none"},j=()=>{o=!o,o?jn.add(n.id):jn.delete(n.id),g()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),j()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),j())}),g(),r.append(i,C),r};var Io=n=>{let t=[];return{buttons:t,render:(e,r,o,i,l)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:r?r.getMessages():[]).some(C=>C.role==="user"))return;let w=document.createDocumentFragment(),y=r?r.isStreaming():!1,u=C=>{switch(C){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(C=>{let g=f("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");g.type="button",g.textContent=C,g.disabled=y,l!=null&&l.fontFamily&&(g.style.fontFamily=u(l.fontFamily)),l!=null&&l.fontWeight&&(g.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(g.style.paddingLeft=l.paddingX,g.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(g.style.paddingTop=l.paddingY,g.style.paddingBottom=l.paddingY),g.addEventListener("click",()=>{!r||r.isStreaming()||(o.value="",r.sendMessage(C))}),w.appendChild(g),t.push(g)}),n.appendChild(w)}}};var $o={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"}},Un=(n,t,s,e)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(o=>{var g,j,$;if(o.dataset.enhanced==="true")return;let i=(g=o.dataset.tvForm)!=null?g:"init";o.dataset.enhanced="true";let l=(j=$o[i])!=null?j:$o.init;o.classList.add("tvw-form-card","tvw-space-y-4");let d=f("div","tvw-space-y-1"),c=f("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=l.title,d.appendChild(c),l.description){let m=f("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,d.appendChild(m)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var x,S;let b=f("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");b.htmlFor=`${t.id}-${i}-${m.name}`;let W=f("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");W.textContent=m.label,b.appendChild(W);let v=(x=m.type)!=null?x:"text",N;v==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=v),N.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",N.id=`${t.id}-${i}-${m.name}`,N.name=m.name,N.placeholder=(S=m.placeholder)!=null?S:"",m.required&&(N.required=!0),b.appendChild(N),w.appendChild(b)});let y=f("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),u=f("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),C=f("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");C.type="submit",C.textContent=($=l.submitLabel)!=null?$:"Submit",y.appendChild(u),y.appendChild(C),w.appendChild(y),o.replaceChildren(d,w),w.addEventListener("submit",async m=>{var N,x;m.preventDefault();let b=(N=s.formEndpoint)!=null?N:"/form",W=new FormData(w),v={};W.forEach((S,Y)=>{v[Y]=S}),v.type=i,C.disabled=!0,u.textContent="Submitting\u2026";try{let S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let Y=await S.json();u.textContent=(x=Y.message)!=null?x:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await e.sendMessage(String(Y.nextPrompt))}catch(S){u.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{C.disabled=!1}})})};var zn=class{constructor(){this.plugins=new Map}register(t){var s;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(s=t.onRegister)==null||s.call(t)}unregister(t){var e;let s=this.plugins.get(t);s&&((e=s.onUnregister)==null||e.call(s),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,s)=>{var e,r;return((e=s.priority)!=null?e:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let s=this.getAll();if(!t||t.length===0)return s;let e=new Set(t.map(o=>o.id));return[...s.filter(o=>!e.has(o.id)),...t].sort((o,i)=>{var l,d;return((l=i.priority)!=null?l:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var s;return(s=t.onUnregister)==null?void 0:s.call(t)}),this.plugins.clear()}},vn=new zn;var Fo={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"},No={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",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"},We={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Fo,darkTheme:No,colorScheme:"light",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 Jn(n){var t,s,e,r,o,i,l,d,c,w,y,u,C,g,j,$,m,b,W;return n?{...We,...n,theme:{...We.theme,...n.theme},darkTheme:{...We.darkTheme,...n.darkTheme},launcher:{...We.launcher,...n.launcher,clearChat:{...(t=We.launcher)==null?void 0:t.clearChat,...(s=n.launcher)==null?void 0:s.clearChat}},copy:{...We.copy,...n.copy},sendButton:{...We.sendButton,...n.sendButton},statusIndicator:{...We.statusIndicator,...n.statusIndicator},voiceRecognition:{...We.voiceRecognition,...n.voiceRecognition},features:{...We.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:We.suggestionChips,suggestionChipsConfig:{...We.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...We.layout,...n.layout,header:{...(r=We.layout)==null?void 0:r.header,...(o=n.layout)==null?void 0:o.header},messages:{...(i=We.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(c=(d=We.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(y=(w=n.layout)==null?void 0:w.messages)==null?void 0:y.avatar},timestamp:{...(C=(u=We.layout)==null?void 0:u.messages)==null?void 0:C.timestamp,...(j=(g=n.layout)==null?void 0:g.messages)==null?void 0:j.timestamp}},slots:{...($=We.layout)==null?void 0:$.slots,...(m=n.layout)==null?void 0:m.slots}},markdown:{...We.markdown,...n.markdown,options:{...(b=We.markdown)==null?void 0:b.options,...(W=n.markdown)==null?void 0:W.options}},messageActions:{...We.messageActions,...n.messageActions}}:We}var Oo=()=>{let n=new Map,t=(r,o)=>(n.has(r)||n.set(r,new Set),n.get(r).add(o),()=>s(r,o)),s=(r,o)=>{var i;(i=n.get(r))==null||i.delete(o)};return{on:t,off:s,emit:(r,o)=>{var i;(i=n.get(r))==null||i.forEach(l=>{try{l(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var ur=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},pr=n=>{let t=n.trim(),s=t.indexOf("{");if(s===-1)return null;let e=0;for(let r=s;r<t.length;r+=1){let o=t[r];if(o==="{"&&(e+=1),o==="}"&&(e-=1,e===0))return t.slice(s,r+1)}return null},bn=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=ur(n),s=pr(t);if(!s)return null;let e=JSON.parse(s);if(!e||typeof e!="object"||!e.action)return null;let{action:r,...o}=e;return{type:String(r),payload:o,raw:e}}catch{return null}},Yn=n=>typeof n=="string"?n:n==null?"":String(n),Vt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Yn(n.payload.text)},messageAndClick:(n,t)=>{var r;if(n.type!=="message_and_click")return;let s=n.payload,e=Yn(s.element);if(e&&((r=t.document)!=null&&r.querySelector)){let o=t.document.querySelector(e);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Yn(s.text)}}},Do=n=>Array.isArray(n)?n.map(t=>String(t)):[],Cn=n=>{let t=new Set(Do(n.getMetadata().processedActionMessageIds)),s=()=>{t=new Set(Do(n.getMetadata().processedActionMessageIds))},e=()=>{let o=Array.from(t);n.updateMetadata(i=>({...i,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let i=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!i&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((c,w)=>c||(w==null?void 0:w({text:i,message:o.message}))||null,null):null;if(!l)return null;t.add(o.message.id),e();let d={action:l,message:o.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let w=c(l,{message:o.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!w)continue;if(w.handled){let y=w.persistMessage!==!1;return{text:w.displayText!==void 0?w.displayText:"",persist:y}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:s}};var gr=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},mr=n=>n.map(t=>({...t,streaming:!1})),Kn=(n="vanilla-agent-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let s=t();return s?gr(s.getItem(n)):null},save:s=>{let e=t();if(e)try{let r={...s,messages:s.messages?mr(s.messages):void 0};e.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let s=t();if(s)try{s.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Xn=class{constructor(){this.components=new Map}register(t,s){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,s)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([s,e])=>{this.register(s,e)})}},rn=new Xn;import{parse as hr,STR as fr,OBJ as wr}from"partial-json";function yr(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function vr(n,t){if(!yr(n))return null;let s=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:s,raw:t}}function Vn(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:s=>{let e=s.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(s.length<=t)return n;try{let r=hr(s,fr|wr),o=vr(r,s);o&&(n=o)}catch{}return t=s.length,n},reset:()=>{n=null,t=0}}}function br(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Gn(n,t){let{config:s,message:e,onPropsUpdate:r}=t,o=rn.get(n.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:e,config:s,updateProps:l=>{r&&r(l)}};try{return o(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Cr(){let n=Vn();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Qn(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Zn(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var xr=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function es(n){let{onSubmit:t,onDismiss:s,title:e="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:c=xr}=n,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-csat",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Customer satisfaction feedback");let y=null,u=document.createElement("div");u.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let g=document.createElement("h3");g.className="tvw-feedback-title",g.textContent=e,C.appendChild(g);let j=document.createElement("p");j.className="tvw-feedback-subtitle",j.textContent=r,C.appendChild(j),u.appendChild(C);let $=document.createElement("div");$.className="tvw-feedback-rating tvw-feedback-rating-csat",$.setAttribute("role","radiogroup"),$.setAttribute("aria-label","Satisfaction rating from 1 to 5");let m=[];for(let x=1;x<=5;x++){let S=document.createElement("button");S.type="button",S.className="tvw-feedback-rating-btn tvw-feedback-star-btn",S.setAttribute("role","radio"),S.setAttribute("aria-checked","false"),S.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${c[x-1]}`),S.title=c[x-1],S.dataset.rating=String(x),S.innerHTML=`
|
|
17
17
|
<svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
18
18
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
19
19
|
</svg>
|
|
20
|
-
`,S.addEventListener("click",()=>{y=x,m.forEach((Y,R)=>{let O=R<x;Y.classList.toggle("selected",O),Y.setAttribute("aria-checked",R===x-1?"true":"false")})}),m.push(S),$.appendChild(S)}u.appendChild($);let b=null;if(d){let x=document.createElement("div");x.className="tvw-feedback-comment-container",b=document.createElement("textarea"),b.className="tvw-feedback-comment",b.placeholder=o,b.rows=3,b.setAttribute("aria-label","Additional comments"),x.appendChild(b),u.appendChild(x)}let W=document.createElement("div");W.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=l,v.addEventListener("click",()=>{s==null||s(),w.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(y===null){$.classList.add("tvw-feedback-shake"),setTimeout(()=>$.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let x=(b==null?void 0:b.value.trim())||void 0;await t(y,x),w.remove()}catch(x){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),W.appendChild(v),W.appendChild(N),u.appendChild(W),w.appendChild(u),w}function ts(n){let{onSubmit:t,onDismiss:s,title:e="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:w="Very likely"}=n,y=document.createElement("div");y.className="tvw-feedback-container tvw-feedback-nps",y.setAttribute("role","dialog"),y.setAttribute("aria-label","Net Promoter Score feedback");let u=null,C=document.createElement("div");C.className="tvw-feedback-content";let g=document.createElement("div");g.className="tvw-feedback-header";let j=document.createElement("h3");j.className="tvw-feedback-title",j.textContent=e,g.appendChild(j);let $=document.createElement("p");$.className="tvw-feedback-subtitle",$.textContent=r,g.appendChild($),C.appendChild(g);let m=document.createElement("div");m.className="tvw-feedback-rating tvw-feedback-rating-nps",m.setAttribute("role","radiogroup"),m.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="tvw-feedback-labels";let W=document.createElement("span");W.className="tvw-feedback-label-low",W.textContent=c;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=w,b.appendChild(W),b.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let x=[];for(let G=0;G<=10;G++){let D=document.createElement("button");D.type="button",D.className="tvw-feedback-rating-btn tvw-feedback-number-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`Rating ${G} out of 10`),D.textContent=String(G),D.dataset.rating=String(G),G<=6?D.classList.add("tvw-feedback-detractor"):G<=8?D.classList.add("tvw-feedback-passive"):D.classList.add("tvw-feedback-promoter"),D.addEventListener("click",()=>{u=G,x.forEach((U,Q)=>{U.classList.toggle("selected",Q===G),U.setAttribute("aria-checked",Q===G?"true":"false")})}),x.push(D),N.appendChild(D)}m.appendChild(b),m.appendChild(N),C.appendChild(m);let S=null;if(d){let G=document.createElement("div");G.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),G.appendChild(S),C.appendChild(G)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let R=document.createElement("button");R.type="button",R.className="tvw-feedback-btn tvw-feedback-btn-skip",R.textContent=l,R.addEventListener("click",()=>{s==null||s(),y.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(u===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let G=(S==null?void 0:S.value.trim())||void 0;await t(u,G),y.remove()}catch(G){O.disabled=!1,O.textContent=i,console.error("[NPS Feedback] Failed to submit:",G)}}),Y.appendChild(R),Y.appendChild(O),C.appendChild(Y),y.appendChild(C),y}var Gt="vanilla-agent-chat-history",Sr=30*1e3,ns=n=>!n||typeof n!="object"?{}:{...n},_o=n=>n.map(t=>({...t,streaming:!1})),jo=(n,t)=>{let s=n!=null&&n.markdown?mn(n.markdown):null;return e=>{var i,l,d;let r=(i=e.text)!=null?i:"",o=(l=e.message.rawContent)!=null?l:null;if(t){let c=t.process({text:r,raw:o!=null?o:r,message:e.message,streaming:e.streaming});c!==null&&(r=c.text,c.persist||(e.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...e,text:r,raw:(d=o!=null?o:e.text)!=null?d:""}):s?s(r):Wn(r)}},ss=(n,t,s)=>{var Re,fe,_e,rt,mt,rs,is,as,ls,ds,cs,us,ps,gs;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let e=Jn(t),r=vn.getForInstance(e.plugins);e.components&&rn.registerAll(e.components);let o=Oo(),i=(Re=e.storageAdapter)!=null?Re:Kn(),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 p=a;p.metadata&&(l=ns(p.metadata)),(fe=p.messages)!=null&&fe.length&&(e={...e,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let c=()=>l,w=a=>{var T;l=(T=a({...l}))!=null?T:{},Qt()},y=e.actionParsers&&e.actionParsers.length?e.actionParsers:[bn],u=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Vt.message,Vt.messageAndClick],C=Cn({parsers:y,handlers:u,getMetadata:c,updateMetadata:w,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let g=(rt=(_e=e.launcher)==null?void 0:_e.enabled)!=null?rt:!0,j=(rs=(mt=e.launcher)==null?void 0:mt.autoExpand)!=null?rs:!1,$=j,m=g,b=g?j:!0,W=jo(e,C),v=(as=(is=e.features)==null?void 0:is.showReasoning)!=null?as:!0,N=(ds=(ls=e.features)==null?void 0:ls.showToolCalls)!=null?ds:!0,x={onCopy:a=>{var p,T;o.emit("message:copy",a),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(a.id,"copy").catch(F=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",F)}),(T=(p=e.messageActions)==null?void 0:p.onCopy)==null||T.call(p,a)},onFeedback:a=>{var p,T;o.emit("message:feedback",a),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(a.messageId,a.type).catch(F=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",F)}),(T=(p=e.messageActions)==null?void 0:p.onFeedback)==null||T.call(p,a)}},S=(cs=e.statusIndicator)!=null?cs:{},Y=a=>{var p,T,F,B;return a==="idle"?(p=S.idleText)!=null?p:Ve.idle:a==="connecting"?(T=S.connectingText)!=null?T:Ve.connecting:a==="connected"?(F=S.connectedText)!=null?F:Ve.connected:a==="error"?(B=S.errorText)!=null?B:Ve.error:Ve[a]},{wrapper:R,panel:O}=Bo(e),G=Ho(e,g),{container:D,body:U,messagesWrapper:Q,suggestions:ie,textarea:de,sendButton:_,sendButtonWrapper:ze,composerForm:Ge,statusText:nt,introTitle:xt,introSubtitle:St,closeButton:q,iconHolder:ve,headerTitle:ht,headerSubtitle:ft,header:Qe,footer:st}=G,I=G.micButton,Be=G.micButtonWrapper,at=r.find(a=>a.renderHeader);if(at!=null&&at.renderHeader){let a=at.renderHeader({config:e,defaultRenderer:()=>{let p=zt({config:e,showClose:g});return nn(D,p,e),p.header},onClose:()=>Ke(!1,"user")});if(a){let p=D.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Qe=a)}}let lt=r.find(a=>a.renderComposer);if(lt!=null&<.renderComposer){let a=lt.renderComposer({config:e,defaultRenderer:()=>sn({config:e}).footer,onSubmit:p=>{E&&!E.isStreaming()&&E.sendMessage(p)},disabled:!1});a&&(st.replaceWith(a),st=a)}(()=>{var F,B;let a=(B=(F=e.layout)==null?void 0:F.slots)!=null?B:{},p=ne=>{switch(ne){case"body-top":return D.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Q;case"footer-top":return ie;case"composer":return Ge;case"footer-bottom":return nt;default:return null}},T=(ne,pe)=>{var h;switch(ne){case"header-left":case"header-center":case"header-right":if(ne==="header-left")Qe.insertBefore(pe,Qe.firstChild);else if(ne==="header-right")Qe.appendChild(pe);else{let J=Qe.querySelector(".tvw-flex-col");J?(h=J.parentNode)==null||h.insertBefore(pe,J.nextSibling):Qe.appendChild(pe)}break;case"body-top":let ee=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ee?ee.replaceWith(pe):U.insertBefore(pe,U.firstChild);break;case"body-bottom":U.appendChild(pe);break;case"footer-top":ie.replaceWith(pe);break;case"footer-bottom":nt.replaceWith(pe);break;default:break}};for(let[ne,pe]of Object.entries(a))if(pe)try{let h=pe({config:e,defaultContent:()=>p(ne)});h&&T(ne,h)}catch(h){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ne}":`,h)}})(),O.appendChild(D),n.appendChild(R);let wt=()=>{var ue,Pe,it,Xe,he,jt,Ht,Rt,kt,un,Pt,qt,dt,It,$t,pn;let a=(Pe=(ue=e.launcher)==null?void 0:ue.sidebarMode)!=null?Pe:!1,p=a||((Xe=(it=e.launcher)==null?void 0:it.fullHeight)!=null?Xe:!1),T=(he=e.theme)!=null?he:{},F=(Ht=(jt=e.launcher)==null?void 0:jt.position)!=null?Ht:"bottom-left",B=F==="bottom-left"||F==="top-left",ne=a?"none":"1px solid var(--tvw-cw-border)",pe=a?B?"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)",h=a?"0":"16px",ee=(Rt=T.panelBorder)!=null?Rt:ne,J=(kt=T.panelShadow)!=null?kt:pe,oe=(un=T.panelBorderRadius)!=null?un:h;n.style.cssText="",R.style.cssText="",O.style.cssText="",D.style.cssText="",U.style.cssText="",st.style.cssText="";let P=(qt=(Pt=e==null?void 0:e.launcher)==null?void 0:Pt.width)!=null?qt:e==null?void 0:e.launcherWidth,te=P!=null?P:"min(400px, calc(100vw - 24px))";a||(O.style.width=te,O.style.maxWidth=te),O.style.boxShadow=J,O.style.borderRadius=oe,D.style.border=ee,D.style.borderRadius=oe;let we=((dt=e.launcher)==null?void 0:dt.enabled)===!1;if(p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",R.style.display="flex",R.style.flexDirection="column",R.style.flex="1 1 0%",R.style.minHeight="0",R.style.maxHeight="100%",R.style.height="100%",we&&(R.style.overflow="hidden"),O.style.display="flex",O.style.flexDirection="column",O.style.flex="1 1 0%",O.style.minHeight="0",O.style.maxHeight="100%",O.style.height="100%",O.style.overflow="hidden",D.style.display="flex",D.style.flexDirection="column",D.style.flex="1 1 0%",D.style.minHeight="0",D.style.maxHeight="100%",D.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",st.style.flexShrink="0"),R.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&&!we&&((It=Ct[F])!=null?It:Ct["bottom-right"]).split(" ").forEach(Yt=>R.classList.add(Yt)),a){let Ut=(pn=($t=e.launcher)==null?void 0:$t.sidebarWidth)!=null?pn:"420px";R.style.cssText=`
|
|
20
|
+
`,S.addEventListener("click",()=>{y=x,m.forEach((Y,R)=>{let O=R<x;Y.classList.toggle("selected",O),Y.setAttribute("aria-checked",R===x-1?"true":"false")})}),m.push(S),$.appendChild(S)}u.appendChild($);let b=null;if(d){let x=document.createElement("div");x.className="tvw-feedback-comment-container",b=document.createElement("textarea"),b.className="tvw-feedback-comment",b.placeholder=o,b.rows=3,b.setAttribute("aria-label","Additional comments"),x.appendChild(b),u.appendChild(x)}let W=document.createElement("div");W.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=l,v.addEventListener("click",()=>{s==null||s(),w.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(y===null){$.classList.add("tvw-feedback-shake"),setTimeout(()=>$.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let x=(b==null?void 0:b.value.trim())||void 0;await t(y,x),w.remove()}catch(x){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),W.appendChild(v),W.appendChild(N),u.appendChild(W),w.appendChild(u),w}function ts(n){let{onSubmit:t,onDismiss:s,title:e="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:w="Very likely"}=n,y=document.createElement("div");y.className="tvw-feedback-container tvw-feedback-nps",y.setAttribute("role","dialog"),y.setAttribute("aria-label","Net Promoter Score feedback");let u=null,C=document.createElement("div");C.className="tvw-feedback-content";let g=document.createElement("div");g.className="tvw-feedback-header";let j=document.createElement("h3");j.className="tvw-feedback-title",j.textContent=e,g.appendChild(j);let $=document.createElement("p");$.className="tvw-feedback-subtitle",$.textContent=r,g.appendChild($),C.appendChild(g);let m=document.createElement("div");m.className="tvw-feedback-rating tvw-feedback-rating-nps",m.setAttribute("role","radiogroup"),m.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="tvw-feedback-labels";let W=document.createElement("span");W.className="tvw-feedback-label-low",W.textContent=c;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=w,b.appendChild(W),b.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let x=[];for(let G=0;G<=10;G++){let D=document.createElement("button");D.type="button",D.className="tvw-feedback-rating-btn tvw-feedback-number-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`Rating ${G} out of 10`),D.textContent=String(G),D.dataset.rating=String(G),G<=6?D.classList.add("tvw-feedback-detractor"):G<=8?D.classList.add("tvw-feedback-passive"):D.classList.add("tvw-feedback-promoter"),D.addEventListener("click",()=>{u=G,x.forEach((U,Q)=>{U.classList.toggle("selected",Q===G),U.setAttribute("aria-checked",Q===G?"true":"false")})}),x.push(D),N.appendChild(D)}m.appendChild(b),m.appendChild(N),C.appendChild(m);let S=null;if(d){let G=document.createElement("div");G.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),G.appendChild(S),C.appendChild(G)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let R=document.createElement("button");R.type="button",R.className="tvw-feedback-btn tvw-feedback-btn-skip",R.textContent=l,R.addEventListener("click",()=>{s==null||s(),y.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(u===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let G=(S==null?void 0:S.value.trim())||void 0;await t(u,G),y.remove()}catch(G){O.disabled=!1,O.textContent=i,console.error("[NPS Feedback] Failed to submit:",G)}}),Y.appendChild(R),Y.appendChild(O),C.appendChild(Y),y.appendChild(C),y}var Gt="vanilla-agent-chat-history",Sr=30*1e3,ns=n=>!n||typeof n!="object"?{}:{...n},_o=n=>n.map(t=>({...t,streaming:!1})),jo=(n,t)=>{let s=n!=null&&n.markdown?mn(n.markdown):null;return e=>{var i,l,d;let r=(i=e.text)!=null?i:"",o=(l=e.message.rawContent)!=null?l:null;if(t){let c=t.process({text:r,raw:o!=null?o:r,message:e.message,streaming:e.streaming});c!==null&&(r=c.text,c.persist||(e.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...e,text:r,raw:(d=o!=null?o:e.text)!=null?d:""}):s?s(r):Wn(r)}},ss=(n,t,s)=>{var Re,fe,_e,rt,mt,rs,is,as,ls,ds,cs,us,ps,gs;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let e=Jn(t),r=vn.getForInstance(e.plugins);e.components&&rn.registerAll(e.components);let o=Oo(),i=(Re=e.storageAdapter)!=null?Re:Kn(),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 p=a;p.metadata&&(l=ns(p.metadata)),(fe=p.messages)!=null&&fe.length&&(e={...e,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let c=()=>l,w=a=>{var T;l=(T=a({...l}))!=null?T:{},Qt()},y=e.actionParsers&&e.actionParsers.length?e.actionParsers:[bn],u=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Vt.message,Vt.messageAndClick],C=Cn({parsers:y,handlers:u,getMetadata:c,updateMetadata:w,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let g=(rt=(_e=e.launcher)==null?void 0:_e.enabled)!=null?rt:!0,j=(rs=(mt=e.launcher)==null?void 0:mt.autoExpand)!=null?rs:!1,$=j,m=g,b=g?j:!0,W=jo(e,C),v=(as=(is=e.features)==null?void 0:is.showReasoning)!=null?as:!0,N=(ds=(ls=e.features)==null?void 0:ls.showToolCalls)!=null?ds:!0,x={onCopy:a=>{var p,T;o.emit("message:copy",a),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(a.id,"copy").catch(F=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",F)}),(T=(p=e.messageActions)==null?void 0:p.onCopy)==null||T.call(p,a)},onFeedback:a=>{var p,T;o.emit("message:feedback",a),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(a.messageId,a.type).catch(F=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",F)}),(T=(p=e.messageActions)==null?void 0:p.onFeedback)==null||T.call(p,a)}},S=(cs=e.statusIndicator)!=null?cs:{},Y=a=>{var p,T,F,B;return a==="idle"?(p=S.idleText)!=null?p:Ve.idle:a==="connecting"?(T=S.connectingText)!=null?T:Ve.connecting:a==="connected"?(F=S.connectedText)!=null?F:Ve.connected:a==="error"?(B=S.errorText)!=null?B:Ve.error:Ve[a]},{wrapper:R,panel:O}=Bo(e),G=Ho(e,g),{container:D,body:U,messagesWrapper:Q,suggestions:ie,textarea:de,sendButton:_,sendButtonWrapper:ze,composerForm:Ge,statusText:nt,introTitle:xt,introSubtitle:St,closeButton:q,iconHolder:ve,headerTitle:ht,headerSubtitle:ft,header:Qe,footer:st}=G,I=G.micButton,Be=G.micButtonWrapper,at=r.find(a=>a.renderHeader);if(at!=null&&at.renderHeader){let a=at.renderHeader({config:e,defaultRenderer:()=>{let p=zt({config:e,showClose:g});return nn(D,p,e),p.header},onClose:()=>Ke(!1,"user")});if(a){let p=D.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Qe=a)}}let lt=r.find(a=>a.renderComposer);if(lt!=null&<.renderComposer){let a=lt.renderComposer({config:e,defaultRenderer:()=>sn({config:e}).footer,onSubmit:p=>{E&&!E.isStreaming()&&E.sendMessage(p)},disabled:!1});a&&(st.replaceWith(a),st=a)}(()=>{var F,B;let a=(B=(F=e.layout)==null?void 0:F.slots)!=null?B:{},p=ne=>{switch(ne){case"body-top":return D.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Q;case"footer-top":return ie;case"composer":return Ge;case"footer-bottom":return nt;default:return null}},T=(ne,pe)=>{var h;switch(ne){case"header-left":case"header-center":case"header-right":if(ne==="header-left")Qe.insertBefore(pe,Qe.firstChild);else if(ne==="header-right")Qe.appendChild(pe);else{let J=Qe.querySelector(".tvw-flex-col");J?(h=J.parentNode)==null||h.insertBefore(pe,J.nextSibling):Qe.appendChild(pe)}break;case"body-top":let ee=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ee?ee.replaceWith(pe):U.insertBefore(pe,U.firstChild);break;case"body-bottom":U.appendChild(pe);break;case"footer-top":ie.replaceWith(pe);break;case"footer-bottom":nt.replaceWith(pe);break;default:break}};for(let[ne,pe]of Object.entries(a))if(pe)try{let h=pe({config:e,defaultContent:()=>p(ne)});h&&T(ne,h)}catch(h){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ne}":`,h)}})(),O.appendChild(D),n.appendChild(R);let wt=()=>{var ue,Pe,it,Xe,he,jt,Ht,Rt,Mt,un,Pt,qt,dt,It,$t,pn;let a=(Pe=(ue=e.launcher)==null?void 0:ue.sidebarMode)!=null?Pe:!1,p=a||((Xe=(it=e.launcher)==null?void 0:it.fullHeight)!=null?Xe:!1),T=(he=e.theme)!=null?he:{},F=(Ht=(jt=e.launcher)==null?void 0:jt.position)!=null?Ht:"bottom-left",B=F==="bottom-left"||F==="top-left",ne=a?"none":"1px solid var(--tvw-cw-border)",pe=a?B?"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)",h=a?"0":"16px",ee=(Rt=T.panelBorder)!=null?Rt:ne,J=(Mt=T.panelShadow)!=null?Mt:pe,oe=(un=T.panelBorderRadius)!=null?un:h;n.style.cssText="",R.style.cssText="",O.style.cssText="",D.style.cssText="",U.style.cssText="",st.style.cssText="";let P=(qt=(Pt=e==null?void 0:e.launcher)==null?void 0:Pt.width)!=null?qt:e==null?void 0:e.launcherWidth,te=P!=null?P:"min(400px, calc(100vw - 24px))";a||(O.style.width=te,O.style.maxWidth=te),O.style.boxShadow=J,O.style.borderRadius=oe,D.style.border=ee,D.style.borderRadius=oe;let we=((dt=e.launcher)==null?void 0:dt.enabled)===!1;if(p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",R.style.display="flex",R.style.flexDirection="column",R.style.flex="1 1 0%",R.style.minHeight="0",R.style.maxHeight="100%",R.style.height="100%",we&&(R.style.overflow="hidden"),O.style.display="flex",O.style.flexDirection="column",O.style.flex="1 1 0%",O.style.minHeight="0",O.style.maxHeight="100%",O.style.height="100%",O.style.overflow="hidden",D.style.display="flex",D.style.flexDirection="column",D.style.flex="1 1 0%",D.style.minHeight="0",D.style.maxHeight="100%",D.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",st.style.flexShrink="0"),R.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&&!we&&((It=Ct[F])!=null?It:Ct["bottom-right"]).split(" ").forEach(Yt=>R.classList.add(Yt)),a){let Ut=(pn=($t=e.launcher)==null?void 0:$t.sidebarWidth)!=null?pn:"420px";R.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
top: 0 !important;
|
|
23
23
|
bottom: 0 !important;
|
|
@@ -57,12 +57,12 @@ import{Marked as Jo}from"marked";var Yo=n=>{if(n)return n},gn=n=>{var r,o;let t=
|
|
|
57
57
|
flex-shrink: 0 !important;
|
|
58
58
|
border-top: none !important;
|
|
59
59
|
padding: 8px 16px 12px 16px !important;
|
|
60
|
-
`}if(!we){let Ut="max-height: -moz-available !important; max-height: stretch !important;",Yt=a?"":"padding-top: 1.25em !important;";R.style.cssText+=Ut+Yt}};wt(),wn(n,e);let He=[],Je=null,yt=()=>{Je&&(Je(),Je=null),e.colorScheme==="auto"&&(Je=Eo(()=>{wn(n,e)}))};yt(),He.push(()=>{Je&&(Je(),Je=null)});let ot=Io(ie),Ye=null,E,$e=!1,V=!0,Le=0,Ie=0,Fe=null,Ne=!1,ut=0,At=!1,vt=125,Wt=2e3,Lt=5,Nt=50,Et=new Map,Z={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},pt=(ps=(us=e.voiceRecognition)==null?void 0:us.autoResume)!=null?ps:!1,bt=a=>{o.emit("voice:state",{active:Z.active,source:a,timestamp:Date.now()})},gt=()=>{w(a=>({...a,voiceState:{active:Z.active,timestamp:Date.now(),manuallyDeactivated:Z.manuallyDeactivated}}))},Bt=()=>{var F,B;if(((F=e.voiceRecognition)==null?void 0:F.enabled)===!1)return;let a=ns(l.voiceState),p=!!a.active,T=Number((B=a.timestamp)!=null?B:0);Z.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-T<Sr&&setTimeout(()=>{Z.active||(Z.manuallyDeactivated=!1,L("restore"))},1e3)},an=()=>E?_o(E.getMessages()).filter(a=>!a.__skipPersist):[];function Qt(a){if(!(i!=null&&i.save))return;let T={messages:a?_o(a):E?an():[],metadata:l};try{let F=i.save(T);F instanceof Promise&&F.catch(B=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",B)})}catch(F){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",F)}}let Ot=(a=!1)=>{if(!V)return;let p=Date.now();Ne&&p<ut&&!a||(Ne&&p>=ut&&(Ne=!1),!(!a&&!$e)&&(p-Ie<vt||(Ie=p,Fe&&cancelAnimationFrame(Fe),Fe=requestAnimationFrame(()=>{Ne||!V||(At=!0,U.scrollTop=U.scrollHeight,Le=U.scrollTop,requestAnimationFrame(()=>{At=!1}),Fe=null)}))))},Mt=null,ln=()=>R.querySelector("#vanilla-agent-scroll-container")||U,dn=(a,p=500)=>{let T=a.scrollTop,F=a.clientHeight,B=a.scrollHeight,ne=B-T;if(T+F>=B-2||Math.abs(ne)<5)return;Mt!==null&&(cancelAnimationFrame(Mt),Mt=null);let h=performance.now(),ee=oe=>1-Math.pow(1-oe,3),J=oe=>{let P=a.scrollHeight;P!==B&&(B=P,ne=B-T);let te=oe-h,we=Math.min(te/p,1),ue=ee(we),Pe=T+ne*ue;a.scrollTop=Pe,we<1?Mt=requestAnimationFrame(J):(a.scrollTop=a.scrollHeight,Mt=null)};Mt=requestAnimationFrame(J)},cn=a=>{let p=new Map;a.forEach(T=>{let F=Et.get(T.id);p.set(T.id,{streaming:T.streaming,role:T.role}),!F&&T.role==="assistant"&&o.emit("assistant:message",T),T.role==="assistant"&&(F!=null&&F.streaming)&&T.streaming===!1&&o.emit("assistant:complete",T)}),Et.clear(),p.forEach((T,F)=>{Et.set(F,T)})},Dt=(a,p,T)=>{a.innerHTML="";let F=document.createDocumentFragment();p.forEach(h=>{var te,we;let ee=null,J=r.find(ue=>!!(h.variant==="reasoning"&&ue.renderReasoning||h.variant==="tool"&&ue.renderToolCall||!h.variant&&ue.renderMessage)),oe=(te=e.layout)==null?void 0:te.messages;if(J)if(h.variant==="reasoning"&&h.reasoning&&J.renderReasoning){if(!v)return;ee=J.renderReasoning({message:h,defaultRenderer:()=>_n(h),config:e})}else if(h.variant==="tool"&&h.toolCall&&J.renderToolCall){if(!N)return;ee=J.renderToolCall({message:h,defaultRenderer:()=>qn(h,e),config:e})}else J.renderMessage&&(ee=J.renderMessage({message:h,defaultRenderer:()=>{let ue=on(h,T,oe,e.messageActions,x);return h.role!=="user"&&Un(ue,h,e,E),ue},config:e}));if(!ee&&h.role==="assistant"&&!h.variant&&e.enableComponentStreaming!==!1&&Qn(h)){let Pe=Zn(h);if(Pe){let it=Gn(Pe,{config:e,message:h,transform:T});if(it){let Xe=document.createElement("div");if(Xe.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(" "),Xe.setAttribute("data-message-id",h.id),h.content&&h.content.trim()){let he=document.createElement("div");he.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",he.innerHTML=T({text:h.content,message:h,streaming:!!h.streaming,raw:h.rawContent}),Xe.appendChild(he)}Xe.appendChild(it),ee=Xe}}}if(!ee)if(h.variant==="reasoning"&&h.reasoning){if(!v)return;ee=_n(h)}else if(h.variant==="tool"&&h.toolCall){if(!N)return;ee=qn(h,e)}else{let ue=(we=e.layout)==null?void 0:we.messages;ue!=null&&ue.renderUserMessage&&h.role==="user"?ee=ue.renderUserMessage({message:h,config:e,streaming:!!h.streaming}):ue!=null&&ue.renderAssistantMessage&&h.role==="assistant"?ee=ue.renderAssistantMessage({message:h,config:e,streaming:!!h.streaming}):ee=on(h,T,ue,e.messageActions,x),h.role!=="user"&&ee&&Un(ee,h,e,E)}let P=document.createElement("div");P.className="tvw-flex",h.role==="user"&&P.classList.add("tvw-justify-end"),P.appendChild(ee),F.appendChild(P)});let B=p.some(h=>h.role==="assistant"&&h.streaming),ne=p[p.length-1],pe=(ne==null?void 0:ne.role)==="assistant"&&!ne.streaming;if($e&&p.some(h=>h.role==="user")&&!B&&!pe){let h=yn(),ee=document.createElement("div");ee.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(" "),ee.appendChild(h);let J=document.createElement("div");J.className="tvw-flex",J.appendChild(ee),F.appendChild(J)}a.appendChild(F),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let h=ln();dn(h)})})},_t=()=>{g&&(b?(R.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-95","tvw-opacity-0"),O.classList.add("tvw-scale-100","tvw-opacity-100"),K?K.element.style.display="none":X&&(X.style.display="none")):(R.classList.add("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-100","tvw-opacity-100"),O.classList.add("tvw-scale-95","tvw-opacity-0"),K?K.element.style.display="":X&&(X.style.display="")))},Ke=(a,p="user")=>{if(!g||b===a)return;let T=b;b=a,_t(),b&&(je(),Ot(!0));let F={open:b,source:p,timestamp:Date.now()};b&&!T?o.emit("widget:opened",F):!b&&T&&o.emit("widget:closed",F),o.emit("widget:state",{open:b,launcherEnabled:g,voiceActive:Z.active,streaming:E.isStreaming()})},Jt=a=>{_.disabled=a,I&&(I.disabled=a),ot.buttons.forEach(p=>{p.disabled=a})},Zt=()=>{var B,ne,pe,h,ee,J,oe,P,te,we,ue,Pe,it,Xe;xt.textContent=(ne=(B=e.copy)==null?void 0:B.welcomeTitle)!=null?ne:"Hello \u{1F44B}",St.textContent=(h=(pe=e.copy)==null?void 0:pe.welcomeSubtitle)!=null?h:"Ask anything about your account or products.",de.placeholder=(J=(ee=e.copy)==null?void 0:ee.inputPlaceholder)!=null?J:"How can I help...",((P=(oe=e.sendButton)==null?void 0:oe.useIcon)!=null?P:!1)||(_.textContent=(we=(te=e.copy)==null?void 0:te.sendButtonLabel)!=null?we:"Send");let p=(Pe=(ue=e.theme)==null?void 0:ue.inputFontFamily)!=null?Pe:"sans-serif",T=(Xe=(it=e.theme)==null?void 0:it.inputFontWeight)!=null?Xe:"400",F=he=>{switch(he){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'}};de.style.fontFamily=F(p),de.style.fontWeight=T};E=new en(e,{onMessagesChanged(a){Dt(Q,a,W),E&&(a.some(F=>F.role==="user")?ot.render([],E,de,a):ot.render(e.suggestionChips,E,de,a,e.suggestionChipsConfig)),Ot(!$e),cn(a);let p=[...a].reverse().find(T=>T.role==="user");Z.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Qt(a)},onStatusChanged(a){var F;let p=(F=e.statusIndicator)!=null?F:{},T=B=>{var ne,pe,h,ee;return B==="idle"?(ne=p.idleText)!=null?ne:Ve.idle:B==="connecting"?(pe=p.connectingText)!=null?pe:Ve.connecting:B==="connected"?(h=p.connectedText)!=null?h:Ve.connected:B==="error"?(ee=p.errorText)!=null?ee:Ve.error:Ve[B]};nt.textContent=T(a)},onStreamingChanged(a){$e=a,Jt(a),E&&Dt(Q,E.getMessages(),W),a||Ot(!0)}}),d&&d.then(a=>{var p;a&&(a.metadata&&(l=ns(a.metadata),C.syncFromMetadata()),(p=a.messages)!=null&&p.length&&E.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let M=a=>{a.preventDefault();let p=de.value.trim();p&&(de.value="",E.sendMessage(p))},ce=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),_.click())},se=null,me=!1,Se=null,Te=null,Ee=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,L=(a="user")=>{var ne,pe,h,ee;if(me||E.isStreaming())return;let p=Ee();if(!p)return;se=new p;let F=(pe=((ne=e.voiceRecognition)!=null?ne:{}).pauseDuration)!=null?pe:2e3;se.continuous=!0,se.interimResults=!0,se.lang="en-US";let B=de.value;se.onresult=J=>{let oe="",P="";for(let we=0;we<J.results.length;we++){let ue=J.results[we],Pe=ue[0].transcript;ue.isFinal?oe+=Pe+" ":P=Pe}let te=B+oe+P;de.value=te,Se&&clearTimeout(Se),(oe||P)&&(Se=window.setTimeout(()=>{let we=de.value.trim();we&&se&&me&&(Oe(),de.value="",E.sendMessage(we,{viaVoice:!0}))},F))},se.onerror=J=>{J.error!=="no-speech"&&Oe()},se.onend=()=>{if(me){let J=de.value.trim();J&&J!==B.trim()&&(de.value="",E.sendMessage(J,{viaVoice:!0})),Oe()}};try{if(se.start(),me=!0,Z.active=!0,a!=="system"&&(Z.manuallyDeactivated=!1),bt(a),gt(),I){Te={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor};let J=(h=e.voiceRecognition)!=null?h:{},oe=(ee=J.recordingBackgroundColor)!=null?ee:"#ef4444",P=J.recordingIconColor,te=J.recordingBorderColor;if(I.classList.add("tvw-voice-recording"),I.style.backgroundColor=oe,P){I.style.color=P;let we=I.querySelector("svg");we&&we.setAttribute("stroke",P)}te&&(I.style.borderColor=te),I.setAttribute("aria-label","Stop voice recognition")}}catch{Oe("system")}},Oe=(a="user")=>{if(me){if(me=!1,Se&&(clearTimeout(Se),Se=null),se){try{se.stop()}catch{}se=null}if(Z.active=!1,bt(a),gt(),I){if(I.classList.remove("tvw-voice-recording"),Te){I.style.backgroundColor=Te.backgroundColor,I.style.color=Te.color,I.style.borderColor=Te.borderColor;let p=I.querySelector("svg");p&&p.setAttribute("stroke",Te.color||"currentColor"),Te=null}I.setAttribute("aria-label","Start voice recognition")}}},ae=(a,p)=>{var Pe,it,Xe,he,jt,Ht,Rt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let F=f("div","tvw-send-button-wrapper"),B=f("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let ne=(Pe=a==null?void 0:a.iconName)!=null?Pe:"mic",pe=(it=p==null?void 0:p.size)!=null?it:"40px",h=(Xe=a==null?void 0:a.iconSize)!=null?Xe:pe,ee=parseFloat(h)||24,J=(he=a==null?void 0:a.backgroundColor)!=null?he:p==null?void 0:p.backgroundColor,oe=(jt=a==null?void 0:a.iconColor)!=null?jt:p==null?void 0:p.textColor;B.style.width=h,B.style.height=h,B.style.minWidth=h,B.style.minHeight=h,B.style.fontSize="18px",B.style.lineHeight="1";let P=oe||"currentColor",te=ge(ne,ee,P,1.5);te?(B.appendChild(te),B.style.color=P):(B.textContent="\u{1F3A4}",B.style.color=P),J?B.style.backgroundColor=J:B.classList.add("tvw-bg-cw-primary"),oe?B.style.color=oe:!oe&&!(p!=null&&p.textColor)&&B.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(B.style.borderWidth=a.borderWidth,B.style.borderStyle="solid"),a!=null&&a.borderColor&&(B.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(B.style.paddingLeft=a.paddingX,B.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(B.style.paddingTop=a.paddingY,B.style.paddingBottom=a.paddingY),F.appendChild(B);let we=(Ht=a==null?void 0:a.tooltipText)!=null?Ht:"Start voice recognition";if(((Rt=a==null?void 0:a.showTooltip)!=null?Rt:!1)&&we){let kt=f("div","tvw-send-button-tooltip");kt.textContent=we,F.appendChild(kt)}return{micButton:B,micButtonWrapper:F}},k=()=>{if(me){let a=de.value.trim();Z.manuallyDeactivated=!0,gt(),Oe("user"),a&&(de.value="",E.sendMessage(a))}else Z.manuallyDeactivated=!1,gt(),L("user")};I&&(I.addEventListener("click",k),He.push(()=>{Oe("system"),I&&I.removeEventListener("click",k)}));let A=o.on("assistant:complete",()=>{pt&&(Z.active||Z.manuallyDeactivated||pt==="assistant"&&!Z.lastUserMessageWasVoice||setTimeout(()=>{!Z.active&&!Z.manuallyDeactivated&&L("auto")},600))});He.push(A);let z=()=>{Ke(!b,"user")},K=null,X=null;if(g){let a=r.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:e,defaultRenderer:()=>tn(e,z).element,onToggle:z});p&&(X=p)}X||(K=tn(e,z))}K?n.appendChild(K.element):X&&n.appendChild(X),_t(),ot.render(e.suggestionChips,E,de,void 0,e.suggestionChipsConfig),Zt(),Jt(E.isStreaming()),Ot(!0),Bt();let je=()=>{var T,F,B,ne,pe,h,ee,J;let a=(F=(T=e.launcher)==null?void 0:T.sidebarMode)!=null?F:!1,p=a||((ne=(B=e.launcher)==null?void 0:B.fullHeight)!=null?ne:!1);if(!g){O.style.height="",O.style.width="";return}if(!a){let oe=(h=(pe=e==null?void 0:e.launcher)==null?void 0:pe.width)!=null?h:e==null?void 0:e.launcherWidth,P=oe!=null?oe:"min(400px, calc(100vw - 24px))";O.style.width=P,O.style.maxWidth=P}if(!p){let oe=window.innerHeight,P=64,te=(J=(ee=e.launcher)==null?void 0:ee.heightOffset)!=null?J:0,we=Math.max(200,oe-P),ue=Math.min(640,we),Pe=Math.max(200,ue-te);O.style.height=`${Pe}px`}};je(),window.addEventListener("resize",je),He.push(()=>window.removeEventListener("resize",je)),Le=U.scrollTop;let Me=()=>{let a=U.scrollTop,p=U.scrollHeight,T=U.clientHeight,F=p-a-T,B=Math.abs(a-Le);if(Le=a,!At&&!(B<=Lt)){if(!V&&F<Nt){Ne=!1,V=!0;return}V&&F>Nt&&(Ne=!0,ut=Date.now()+Wt,V=!1)}};U.addEventListener("scroll",Me,{passive:!0}),He.push(()=>U.removeEventListener("scroll",Me)),He.push(()=>{Fe&&cancelAnimationFrame(Fe)});let De=()=>{q&&(Ye&&(q.removeEventListener("click",Ye),Ye=null),g?(q.style.display="",Ye=()=>{b=!1,_t()},q.addEventListener("click",Ye)):q.style.display="none")};De(),(()=>{let{clearChatButton:a}=G;a&&a.addEventListener("click",()=>{E.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(F=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",F)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}l={},C.syncFromMetadata()})})(),Ge.addEventListener("submit",M),de.addEventListener("keydown",ce),He.push(()=>{Ge.removeEventListener("submit",M),de.removeEventListener("keydown",ce)}),He.push(()=>{E.cancel()}),K?He.push(()=>{K==null||K.destroy()}):X&&He.push(()=>{X==null||X.remove()});let re={update(a){var Ut,Yt,ms,hs,fs,ws,ys,vs,bs,Cs,xs,Ss,As,Ts,Es,Ms,ks,Ws,Ls,Bs,Hs,Rs,Ps,Is,$s,Fs,Ns,Os,Ds,_s,js,qs,Us,zs,Js,Ys,Ks,Xs,Vs,Gs,Qs,Zs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho;let p=e.toolCall,T=e.colorScheme;e={...e,...a},wt(),wn(n,e),e.colorScheme!==T&&yt();let F=vn.getForInstance(e.plugins);if(r.length=0,r.push(...F),g=(Yt=(Ut=e.launcher)==null?void 0:Ut.enabled)!=null?Yt:!0,j=(hs=(ms=e.launcher)==null?void 0:ms.autoExpand)!=null?hs:!1,v=(ws=(fs=e.features)==null?void 0:fs.showReasoning)!=null?ws:!0,N=(vs=(ys=e.features)==null?void 0:ys.showToolCalls)!=null?vs:!0,((bs=e.launcher)==null?void 0:bs.enabled)===!1&&K&&(K.destroy(),K=null),((Cs=e.launcher)==null?void 0:Cs.enabled)===!1&&X&&(X.remove(),X=null),((xs=e.launcher)==null?void 0:xs.enabled)!==!1&&!K&&!X){let H=r.find(be=>be.renderLauncher);if(H!=null&&H.renderLauncher){let be=H.renderLauncher({config:e,defaultRenderer:()=>tn(e,z).element,onToggle:z});be&&(X=be,n.appendChild(X))}X||(K=tn(e,z),n.appendChild(K.element))}K&&K.update(e),ht&&((Ss=e.launcher)==null?void 0:Ss.title)!==void 0&&(ht.textContent=e.launcher.title),ft&&((As=e.launcher)==null?void 0:As.subtitle)!==void 0&&(ft.textContent=e.launcher.subtitle),g!==m?g?Ke(j,"auto"):(b=!0,_t()):j!==$&&Ke(j,"auto"),$=j,m=g,je(),De(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&E&&Dt(Q,E.getMessages(),W);let h=(Ts=e.launcher)!=null?Ts:{},ee=(Es=h.headerIconHidden)!=null?Es:!1,J=h.headerIconName,oe=(Ms=h.headerIconSize)!=null?Ms:"48px";if(ve){let H=D.querySelector(".tvw-border-b-cw-divider"),be=H==null?void 0:H.querySelector(".tvw-flex-col");if(ee)ve.style.display="none",H&&be&&!H.contains(be)&&H.insertBefore(be,H.firstChild);else{if(ve.style.display="",ve.style.height=oe,ve.style.width=oe,H&&be&&(H.contains(ve)?ve.nextSibling!==be&&(ve.remove(),H.insertBefore(ve,be)):H.insertBefore(ve,be)),J){let ke=parseFloat(oe)||24,xe=ge(J,ke*.6,"#ffffff",2);xe?ve.replaceChildren(xe):ve.textContent=(ks=h.agentIconText)!=null?ks:"\u{1F4AC}"}else if(h.iconUrl){let ke=ve.querySelector("img");if(ke)ke.src=h.iconUrl,ke.style.height=oe,ke.style.width=oe;else{let xe=document.createElement("img");xe.src=h.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=oe,xe.style.width=oe,ve.replaceChildren(xe)}}else{let ke=ve.querySelector("svg"),xe=ve.querySelector("img");(ke||xe)&&ve.replaceChildren(),ve.textContent=(Ws=h.agentIconText)!=null?Ws:"\u{1F4AC}"}let le=ve.querySelector("img");le&&(le.style.height=oe,le.style.width=oe)}}if(q){let H=(Ls=h.closeButtonSize)!=null?Ls:"32px",be=(Bs=h.closeButtonPlacement)!=null?Bs:"inline";q.style.height=H,q.style.width=H;let{closeButtonWrapper:le}=G,ke=be==="top-right",xe=le==null?void 0:le.classList.contains("tvw-absolute");if(le&&ke!==xe)if(le.remove(),ke)le.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",D.style.position="relative",D.appendChild(le);else{let ye=(Rs=(Hs=h.clearChat)==null?void 0:Hs.placement)!=null?Rs:"inline",et=(Is=(Ps=h.clearChat)==null?void 0:Ps.enabled)!=null?Is:!0;le.className=et&&ye==="inline"?"":"tvw-ml-auto";let tt=D.querySelector(".tvw-border-b-cw-divider");tt&&tt.appendChild(le)}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 ye=h.closeButtonBorderWidth||"0px",et=h.closeButtonBorderColor||"transparent";q.style.border=`${ye} solid ${et}`,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=($s=h.closeButtonIconName)!=null?$s:"x",Ue=(Fs=h.closeButtonIconText)!=null?Fs:"\xD7";q.innerHTML="";let ct=ge(Ze,"20px",h.closeButtonColor||"",2);ct?q.appendChild(ct):q.textContent=Ue;let Ft=(Ns=h.closeButtonTooltipText)!=null?Ns:"Close chat",Ae=(Os=h.closeButtonShowTooltip)!=null?Os:!0;if(q.setAttribute("aria-label",Ft),le&&(le._cleanupTooltip&&(le._cleanupTooltip(),delete le._cleanupTooltip),Ae&&Ft)){let ye=null,et=()=>{if(ye||!q)return;ye=f("div","tvw-clear-chat-tooltip"),ye.textContent=Ft;let Kt=f("div");Kt.className="tvw-clear-chat-tooltip-arrow",ye.appendChild(Kt);let kn=q.getBoundingClientRect();ye.style.position="fixed",ye.style.left=`${kn.left+kn.width/2}px`,ye.style.top=`${kn.top-8}px`,ye.style.transform="translate(-50%, -100%)",document.body.appendChild(ye)},tt=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};le.addEventListener("mouseenter",et),le.addEventListener("mouseleave",tt),q.addEventListener("focus",et),q.addEventListener("blur",tt),le._cleanupTooltip=()=>{tt(),le&&(le.removeEventListener("mouseenter",et),le.removeEventListener("mouseleave",tt)),q&&(q.removeEventListener("focus",et),q.removeEventListener("blur",tt))}}}let{clearChatButton:P,clearChatButtonWrapper:te}=G;if(P){let H=(Ds=h.clearChat)!=null?Ds:{},be=(_s=H.enabled)!=null?_s:!0,le=(js=H.placement)!=null?js:"inline";if(te){te.style.display=be?"":"none";let ke=le==="top-right",xe=te.classList.contains("tvw-absolute");if(ke!==xe&&be){if(te.remove(),ke)te.className="tvw-absolute tvw-top-4 tvw-z-50",te.style.right="48px",D.style.position="relative",D.appendChild(te);else{te.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",te.style.right="";let Ue=D.querySelector(".tvw-border-b-cw-divider"),ct=G.closeButtonWrapper;Ue&&ct&&ct.parentElement===Ue?Ue.insertBefore(te,ct):Ue&&Ue.appendChild(te)}let Ze=G.closeButtonWrapper;Ze&&!Ze.classList.contains("tvw-absolute")&&(ke?Ze.classList.add("tvw-ml-auto"):Ze.classList.remove("tvw-ml-auto"))}}if(be){let ke=(qs=H.size)!=null?qs:"32px";P.style.height=ke,P.style.width=ke;let xe=(Us=H.iconName)!=null?Us:"refresh-cw",Ze=(zs=H.iconColor)!=null?zs:"";P.innerHTML="";let Ue=ge(xe,"20px",Ze||"",2);if(Ue&&P.appendChild(Ue),Ze?(P.style.color=Ze,P.classList.remove("tvw-text-cw-muted")):(P.style.color="",P.classList.add("tvw-text-cw-muted")),H.backgroundColor?(P.style.backgroundColor=H.backgroundColor,P.classList.remove("hover:tvw-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:tvw-bg-gray-100")),H.borderWidth||H.borderColor){let Ae=H.borderWidth||"0px",ye=H.borderColor||"transparent";P.style.border=`${Ae} solid ${ye}`,P.classList.remove("tvw-border-none")}else P.style.border="",P.classList.add("tvw-border-none");H.borderRadius?(P.style.borderRadius=H.borderRadius,P.classList.remove("tvw-rounded-full")):(P.style.borderRadius="",P.classList.add("tvw-rounded-full")),H.paddingX?(P.style.paddingLeft=H.paddingX,P.style.paddingRight=H.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),H.paddingY?(P.style.paddingTop=H.paddingY,P.style.paddingBottom=H.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let ct=(Js=H.tooltipText)!=null?Js:"Clear chat",Ft=(Ys=H.showTooltip)!=null?Ys:!0;if(P.setAttribute("aria-label",ct),te&&(te._cleanupTooltip&&(te._cleanupTooltip(),delete te._cleanupTooltip),Ft&&ct)){let Ae=null,ye=()=>{if(Ae||!P)return;Ae=f("div","tvw-clear-chat-tooltip"),Ae.textContent=ct;let tt=f("div");tt.className="tvw-clear-chat-tooltip-arrow",Ae.appendChild(tt);let Kt=P.getBoundingClientRect();Ae.style.position="fixed",Ae.style.left=`${Kt.left+Kt.width/2}px`,Ae.style.top=`${Kt.top-8}px`,Ae.style.transform="translate(-50%, -100%)",document.body.appendChild(Ae)},et=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};te.addEventListener("mouseenter",ye),te.addEventListener("mouseleave",et),P.addEventListener("focus",ye),P.addEventListener("blur",et),te._cleanupTooltip=()=>{et(),te&&(te.removeEventListener("mouseenter",ye),te.removeEventListener("mouseleave",et)),P&&(P.removeEventListener("focus",ye),P.removeEventListener("blur",et))}}}}let we=e.actionParsers&&e.actionParsers.length?e.actionParsers:[bn],ue=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Vt.message,Vt.messageAndClick];C=Cn({parsers:we,handlers:ue,getMetadata:c,updateMetadata:w,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),W=jo(e,C),E.updateConfig(e),Dt(Q,E.getMessages(),W),ot.render(e.suggestionChips,E,de,void 0,e.suggestionChipsConfig),Zt(),Jt(E.isStreaming());let Pe=((Ks=e.voiceRecognition)==null?void 0:Ks.enabled)===!0,it=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Xe=Pe&⁢if(Ge.classList.remove("tvw-gap-1","tvw-gap-3"),Ge.classList.add(Xe?"tvw-gap-1":"tvw-gap-3"),Pe&&it)if(!I||!Be){let H=ae(e.voiceRecognition,e.sendButton);H&&(I=H.micButton,Be=H.micButtonWrapper,Ge.insertBefore(Be,ze),I.addEventListener("click",k),I.disabled=E.isStreaming())}else{let H=(Xs=e.voiceRecognition)!=null?Xs:{},be=(Vs=e.sendButton)!=null?Vs:{},le=(Gs=H.iconName)!=null?Gs:"mic",ke=(Qs=be.size)!=null?Qs:"40px",xe=(Zs=H.iconSize)!=null?Zs:ke,Ze=parseFloat(xe)||24;I.style.width=xe,I.style.height=xe,I.style.minWidth=xe,I.style.minHeight=xe;let Ue=(to=(eo=H.iconColor)!=null?eo:be.textColor)!=null?to:"currentColor";I.innerHTML="";let ct=ge(le,Ze,Ue,2);ct?I.appendChild(ct):I.textContent="\u{1F3A4}";let Ft=(no=H.backgroundColor)!=null?no:be.backgroundColor;Ft?(I.style.backgroundColor=Ft,I.classList.remove("tvw-bg-cw-primary")):(I.style.backgroundColor="",I.classList.add("tvw-bg-cw-primary")),Ue?(I.style.color=Ue,I.classList.remove("tvw-text-white")):!Ue&&!be.textColor&&(I.style.color="",I.classList.add("tvw-text-white")),H.borderWidth?(I.style.borderWidth=H.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),H.borderColor?I.style.borderColor=H.borderColor:I.style.borderColor="",H.paddingX?(I.style.paddingLeft=H.paddingX,I.style.paddingRight=H.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),H.paddingY?(I.style.paddingTop=H.paddingY,I.style.paddingBottom=H.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let Ae=Be==null?void 0:Be.querySelector(".tvw-send-button-tooltip"),ye=(so=H.tooltipText)!=null?so:"Start voice recognition";if(((oo=H.showTooltip)!=null?oo:!1)&&ye)if(Ae)Ae.textContent=ye,Ae.style.display="";else{let tt=document.createElement("div");tt.className="tvw-send-button-tooltip",tt.textContent=ye,Be==null||Be.insertBefore(tt,I)}else Ae&&(Ae.style.display="none");Be.style.display="",I.disabled=E.isStreaming()}else I&&Be&&(Be.style.display="none",me&&Oe());let he=(ro=e.sendButton)!=null?ro:{},jt=(io=he.useIcon)!=null?io:!1,Ht=(ao=he.iconText)!=null?ao:"\u2191",Rt=he.iconName,kt=(lo=he.tooltipText)!=null?lo:"Send message",un=(co=he.showTooltip)!=null?co:!1,Pt=(uo=he.size)!=null?uo:"40px",qt=he.backgroundColor,dt=he.textColor;if(jt){if(_.style.width=Pt,_.style.height=Pt,_.style.minWidth=Pt,_.style.minHeight=Pt,_.style.fontSize="18px",_.style.lineHeight="1",_.innerHTML="",Rt){let H=parseFloat(Pt)||24,be=dt&&typeof dt=="string"&&dt.trim()?dt.trim():"currentColor",le=ge(Rt,H,be,2);le?(_.appendChild(le),_.style.color=be):(_.textContent=Ht,dt?_.style.color=dt:_.classList.add("tvw-text-white"))}else _.textContent=Ht,dt?_.style.color=dt:_.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=(go=(po=e.copy)==null?void 0:po.sendButtonLabel)!=null?go:"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"),dt?_.style.color=dt:_.classList.add("tvw-text-white");he.borderWidth?(_.style.borderWidth=he.borderWidth,_.style.borderStyle="solid"):(_.style.borderWidth="",_.style.borderStyle=""),he.borderColor?_.style.borderColor=he.borderColor:_.style.borderColor="",he.paddingX?(_.style.paddingLeft=he.paddingX,_.style.paddingRight=he.paddingX):(_.style.paddingLeft="",_.style.paddingRight=""),he.paddingY?(_.style.paddingTop=he.paddingY,_.style.paddingBottom=he.paddingY):(_.style.paddingTop="",_.style.paddingBottom="");let It=ze==null?void 0:ze.querySelector(".tvw-send-button-tooltip");if(un&&kt)if(It)It.textContent=kt,It.style.display="";else{let H=document.createElement("div");H.className="tvw-send-button-tooltip",H.textContent=kt,ze==null||ze.insertBefore(H,_)}else It&&(It.style.display="none");let $t=(mo=e.statusIndicator)!=null?mo:{},pn=(ho=$t.visible)!=null?ho:!0;if(nt.style.display=pn?"":"none",E){let H=E.getStatus(),be=le=>{var ke,xe,Ze,Ue;return le==="idle"?(ke=$t.idleText)!=null?ke:Ve.idle:le==="connecting"?(xe=$t.connectingText)!=null?xe:Ve.connecting:le==="connected"?(Ze=$t.connectedText)!=null?Ze:Ve.connected:le==="error"?(Ue=$t.errorText)!=null?Ue:Ve.error:Ve[le]};nt.textContent=be(H)}},open(){g&&Ke(!0,"api")},close(){g&&Ke(!1,"api")},toggle(){g&&Ke(!b,"api")},clearChat(){E.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},C.syncFromMetadata()},setMessage(a){return!de||E.isStreaming()?!1:(!b&&g&&Ke(!0,"system"),de.value=a,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(E.isStreaming())return!1;let p=(a==null?void 0:a.trim())||de.value.trim();return p?(!b&&g&&Ke(!0,"system"),de.value="",E.sendMessage(p),!0):!1},startVoiceRecognition(){return me||E.isStreaming()||!Ee()?!1:(!b&&g&&Ke(!0,"system"),Z.manuallyDeactivated=!1,gt(),L("user"),!0)},stopVoiceRecognition(){return me?(Z.manuallyDeactivated=!0,gt(),Oe("user"),!0):!1},injectTestMessage(a){!b&&g&&Ke(!0,"system"),E.injectTestEvent(a)},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){w(a)},on(a,p){return o.on(a,p)},off(a,p){o.off(a,p)},isOpen(){return g&&b},isVoiceActive(){return Z.active},getState(){return{open:g&&b,launcherEnabled:g,voiceActive:Z.active,streaming:E.isStreaming()}},showCSATFeedback(a){!b&&g&&Ke(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let T=es({onSubmit:async(F,B)=>{var ne;E.isClientTokenMode()&&await E.submitCSATFeedback(F,B),(ne=a==null?void 0:a.onSubmit)==null||ne.call(a,F,B)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!b&&g&&Ke(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let T=ts({onSubmit:async(F,B)=>{var ne;E.isClientTokenMode()&&await E.submitNPSFeedback(F,B),(ne=a==null?void 0:a.onSubmit)==null||ne.call(a,F,B)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,p){return E.submitCSATFeedback(a,p)},async submitNPSFeedback(a,p){return E.submitNPSFeedback(a,p)},destroy(){He.forEach(a=>a()),R.remove(),K==null||K.destroy(),X==null||X.remove(),Ye&&q.removeEventListener("click",Ye)}};if((((gs=s==null?void 0:s.debugTools)!=null?gs:!1)||!!e.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:re,getMessages:re.getMessages,getStatus:re.getStatus,getMetadata:re.getPersistentMetadata,updateMetadata:re.updatePersistentMetadata,clearHistory:()=>re.clearChat(),setVoiceActive:T=>T?re.startVoiceRecognition():re.stopVoiceRecognition()};window.AgentWidgetBrowser=p,He.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return re};var os={},Ar=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 t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},Tr=()=>{try{if(typeof os!="undefined"&&os.url)return new URL("../widget.css",os.url).href}catch{}return null},qo=n=>{let t=Tr(),s=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let r=e.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-vanilla-agent","true"),n.insertBefore(e,n.firstChild)}else s();else if(!document.head.querySelector("link[data-vanilla-agent]")&&t){let r=document.createElement("link");r.rel="stylesheet",r.href=t,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},Uo=n=>{var c,w,y,u;let t=Ar(n.target),s=document.createElement("div");s.className="vanilla-agent-host";let e=(y=(w=(c=n.config)==null?void 0:c.launcher)==null?void 0:w.enabled)!=null?y:!0;e||(s.style.height="100%"),t.appendChild(s);let r=n.useShadowDom===!0,o,i;if(r){let C=s.attachShadow({mode:"open"});i=C,o=document.createElement("div"),o.id="vanilla-agent-root",e||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),C.appendChild(o),qo(C)}else i=s,o=document.createElement("div"),o.id="vanilla-agent-root",e||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),s.appendChild(o),qo(s);let l=ss(o,n.config,{debugTools:n.debugTools});(u=n.onReady)==null||u.call(n);let d={...l,host:s,destroy(){l.destroy(),s.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=d),d};function Er(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function xn(n){var t,s;return(s=(t=n.parserType)!=null?t:Er(n.streamParser))!=null?s:"plain"}function Sn(n,t){let s=[];return n.toolCall&&(s.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,r])=>{typeof r=="string"&&s.push(`${t} ${e}: "${r}",`)}),s.push(`${t}},`)),s}function An(n,t){let s=[];return n.messageActions&&Object.entries(n.messageActions).some(([r,o])=>r!=="onFeedback"&&r!=="onCopy"&&o!==void 0)&&(s.push(`${t}messageActions: {`),Object.entries(n.messageActions).forEach(([r,o])=>{r==="onFeedback"||r==="onCopy"||(typeof o=="string"?s.push(`${t} ${r}: "${o}",`):typeof o=="boolean"&&s.push(`${t} ${r}: ${o},`))}),s.push(`${t}},`)),s}function Tn(n,t){let s=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,r=n.markdown.disableDefaultStyles!==void 0;(e||r)&&(s.push(`${t}markdown: {`),e&&(s.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([o,i])=>{typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`)}),s.push(`${t} },`)),r&&s.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),s.push(`${t}},`))}return s}function En(n,t){let s=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(o=>o!=="render"),r=n.layout.messages&&Object.keys(n.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(e||r)&&(s.push(`${t}layout: {`),e&&(s.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([o,i])=>{o!=="render"&&(typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`))}),s.push(`${t} },`)),r&&(s.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([o,i])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof i=="object"&&i!==null?(s.push(`${t} avatar: {`),Object.entries(i).forEach(([l,d])=>{typeof d=="string"?s.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&s.push(`${t} ${l}: ${d},`)}),s.push(`${t} },`)):o==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(s.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?s.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&s.push(`${t} ${d}: ${c},`))}),s.push(`${t} },`)):typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`))}),s.push(`${t} },`)),s.push(`${t}},`))}return s}function Mr(n,t="esm"){let s={...n};return delete s.postprocessMessage,delete s.initialMessages,t==="esm"?kr(s):t==="script-installer"?Br(s):t==="script-advanced"?Rr(s):t==="react-component"?Wr(s):t==="react-advanced"?Lr(s):Hr(s)}function kr(n){let t=xn(n),s=t!=="plain",e=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),s&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"?e.push(` ${r}: ${o},`):typeof o=="number"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{e.push(` ${r}: ${o},`)}),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(" },")),e.push(...Sn(n," ")),e.push(...An(n," ")),e.push(...Tn(n," ")),e.push(...En(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push("});"),e.join(`
|
|
60
|
+
`}if(!we){let Ut="max-height: -moz-available !important; max-height: stretch !important;",Yt=a?"":"padding-top: 1.25em !important;";R.style.cssText+=Ut+Yt}};wt(),wn(n,e);let He=[],Je=null,yt=()=>{Je&&(Je(),Je=null),e.colorScheme==="auto"&&(Je=Eo(()=>{wn(n,e)}))};yt(),He.push(()=>{Je&&(Je(),Je=null)});let ot=Io(ie),Ye=null,E,$e=!1,V=!0,Le=0,Ie=0,Fe=null,Ne=!1,ut=0,At=!1,vt=125,Wt=2e3,Lt=5,Nt=50,Et=new Map,Z={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},pt=(ps=(us=e.voiceRecognition)==null?void 0:us.autoResume)!=null?ps:!1,bt=a=>{o.emit("voice:state",{active:Z.active,source:a,timestamp:Date.now()})},gt=()=>{w(a=>({...a,voiceState:{active:Z.active,timestamp:Date.now(),manuallyDeactivated:Z.manuallyDeactivated}}))},Bt=()=>{var F,B;if(((F=e.voiceRecognition)==null?void 0:F.enabled)===!1)return;let a=ns(l.voiceState),p=!!a.active,T=Number((B=a.timestamp)!=null?B:0);Z.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-T<Sr&&setTimeout(()=>{Z.active||(Z.manuallyDeactivated=!1,L("restore"))},1e3)},an=()=>E?_o(E.getMessages()).filter(a=>!a.__skipPersist):[];function Qt(a){if(!(i!=null&&i.save))return;let T={messages:a?_o(a):E?an():[],metadata:l};try{let F=i.save(T);F instanceof Promise&&F.catch(B=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",B)})}catch(F){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",F)}}let Ot=(a=!1)=>{if(!V)return;let p=Date.now();Ne&&p<ut&&!a||(Ne&&p>=ut&&(Ne=!1),!(!a&&!$e)&&(p-Ie<vt||(Ie=p,Fe&&cancelAnimationFrame(Fe),Fe=requestAnimationFrame(()=>{Ne||!V||(At=!0,U.scrollTop=U.scrollHeight,Le=U.scrollTop,requestAnimationFrame(()=>{At=!1}),Fe=null)}))))},kt=null,ln=()=>R.querySelector("#vanilla-agent-scroll-container")||U,dn=(a,p=500)=>{let T=a.scrollTop,F=a.clientHeight,B=a.scrollHeight,ne=B-T;if(T+F>=B-2||Math.abs(ne)<5)return;kt!==null&&(cancelAnimationFrame(kt),kt=null);let h=performance.now(),ee=oe=>1-Math.pow(1-oe,3),J=oe=>{let P=a.scrollHeight;P!==B&&(B=P,ne=B-T);let te=oe-h,we=Math.min(te/p,1),ue=ee(we),Pe=T+ne*ue;a.scrollTop=Pe,we<1?kt=requestAnimationFrame(J):(a.scrollTop=a.scrollHeight,kt=null)};kt=requestAnimationFrame(J)},cn=a=>{let p=new Map;a.forEach(T=>{let F=Et.get(T.id);p.set(T.id,{streaming:T.streaming,role:T.role}),!F&&T.role==="assistant"&&o.emit("assistant:message",T),T.role==="assistant"&&(F!=null&&F.streaming)&&T.streaming===!1&&o.emit("assistant:complete",T)}),Et.clear(),p.forEach((T,F)=>{Et.set(F,T)})},Dt=(a,p,T)=>{a.innerHTML="";let F=document.createDocumentFragment();p.forEach(h=>{var te,we;let ee=null,J=r.find(ue=>!!(h.variant==="reasoning"&&ue.renderReasoning||h.variant==="tool"&&ue.renderToolCall||!h.variant&&ue.renderMessage)),oe=(te=e.layout)==null?void 0:te.messages;if(J)if(h.variant==="reasoning"&&h.reasoning&&J.renderReasoning){if(!v)return;ee=J.renderReasoning({message:h,defaultRenderer:()=>_n(h),config:e})}else if(h.variant==="tool"&&h.toolCall&&J.renderToolCall){if(!N)return;ee=J.renderToolCall({message:h,defaultRenderer:()=>qn(h,e),config:e})}else J.renderMessage&&(ee=J.renderMessage({message:h,defaultRenderer:()=>{let ue=on(h,T,oe,e.messageActions,x);return h.role!=="user"&&Un(ue,h,e,E),ue},config:e}));if(!ee&&h.role==="assistant"&&!h.variant&&e.enableComponentStreaming!==!1&&Qn(h)){let Pe=Zn(h);if(Pe){let it=Gn(Pe,{config:e,message:h,transform:T});if(it){let Xe=document.createElement("div");if(Xe.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(" "),Xe.setAttribute("data-message-id",h.id),h.content&&h.content.trim()){let he=document.createElement("div");he.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",he.innerHTML=T({text:h.content,message:h,streaming:!!h.streaming,raw:h.rawContent}),Xe.appendChild(he)}Xe.appendChild(it),ee=Xe}}}if(!ee)if(h.variant==="reasoning"&&h.reasoning){if(!v)return;ee=_n(h)}else if(h.variant==="tool"&&h.toolCall){if(!N)return;ee=qn(h,e)}else{let ue=(we=e.layout)==null?void 0:we.messages;ue!=null&&ue.renderUserMessage&&h.role==="user"?ee=ue.renderUserMessage({message:h,config:e,streaming:!!h.streaming}):ue!=null&&ue.renderAssistantMessage&&h.role==="assistant"?ee=ue.renderAssistantMessage({message:h,config:e,streaming:!!h.streaming}):ee=on(h,T,ue,e.messageActions,x),h.role!=="user"&&ee&&Un(ee,h,e,E)}let P=document.createElement("div");P.className="tvw-flex",h.role==="user"&&P.classList.add("tvw-justify-end"),P.appendChild(ee),F.appendChild(P)});let B=p.some(h=>h.role==="assistant"&&h.streaming),ne=p[p.length-1],pe=(ne==null?void 0:ne.role)==="assistant"&&!ne.streaming;if($e&&p.some(h=>h.role==="user")&&!B&&!pe){let h=yn(),ee=document.createElement("div");ee.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(" "),ee.appendChild(h);let J=document.createElement("div");J.className="tvw-flex",J.appendChild(ee),F.appendChild(J)}a.appendChild(F),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let h=ln();dn(h)})})},_t=()=>{g&&(b?(R.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-95","tvw-opacity-0"),O.classList.add("tvw-scale-100","tvw-opacity-100"),K?K.element.style.display="none":X&&(X.style.display="none")):(R.classList.add("tvw-pointer-events-none","tvw-opacity-0"),O.classList.remove("tvw-scale-100","tvw-opacity-100"),O.classList.add("tvw-scale-95","tvw-opacity-0"),K?K.element.style.display="":X&&(X.style.display="")))},Ke=(a,p="user")=>{if(!g||b===a)return;let T=b;b=a,_t(),b&&(je(),Ot(!0));let F={open:b,source:p,timestamp:Date.now()};b&&!T?o.emit("widget:opened",F):!b&&T&&o.emit("widget:closed",F),o.emit("widget:state",{open:b,launcherEnabled:g,voiceActive:Z.active,streaming:E.isStreaming()})},Jt=a=>{_.disabled=a,I&&(I.disabled=a),ot.buttons.forEach(p=>{p.disabled=a})},Zt=()=>{var B,ne,pe,h,ee,J,oe,P,te,we,ue,Pe,it,Xe;xt.textContent=(ne=(B=e.copy)==null?void 0:B.welcomeTitle)!=null?ne:"Hello \u{1F44B}",St.textContent=(h=(pe=e.copy)==null?void 0:pe.welcomeSubtitle)!=null?h:"Ask anything about your account or products.",de.placeholder=(J=(ee=e.copy)==null?void 0:ee.inputPlaceholder)!=null?J:"How can I help...",((P=(oe=e.sendButton)==null?void 0:oe.useIcon)!=null?P:!1)||(_.textContent=(we=(te=e.copy)==null?void 0:te.sendButtonLabel)!=null?we:"Send");let p=(Pe=(ue=e.theme)==null?void 0:ue.inputFontFamily)!=null?Pe:"sans-serif",T=(Xe=(it=e.theme)==null?void 0:it.inputFontWeight)!=null?Xe:"400",F=he=>{switch(he){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'}};de.style.fontFamily=F(p),de.style.fontWeight=T};E=new en(e,{onMessagesChanged(a){Dt(Q,a,W),E&&(a.some(F=>F.role==="user")?ot.render([],E,de,a):ot.render(e.suggestionChips,E,de,a,e.suggestionChipsConfig)),Ot(!$e),cn(a);let p=[...a].reverse().find(T=>T.role==="user");Z.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Qt(a)},onStatusChanged(a){var F;let p=(F=e.statusIndicator)!=null?F:{},T=B=>{var ne,pe,h,ee;return B==="idle"?(ne=p.idleText)!=null?ne:Ve.idle:B==="connecting"?(pe=p.connectingText)!=null?pe:Ve.connecting:B==="connected"?(h=p.connectedText)!=null?h:Ve.connected:B==="error"?(ee=p.errorText)!=null?ee:Ve.error:Ve[B]};nt.textContent=T(a)},onStreamingChanged(a){$e=a,Jt(a),E&&Dt(Q,E.getMessages(),W),a||Ot(!0)}}),d&&d.then(a=>{var p;a&&(a.metadata&&(l=ns(a.metadata),C.syncFromMetadata()),(p=a.messages)!=null&&p.length&&E.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let k=a=>{a.preventDefault();let p=de.value.trim();p&&(de.value="",E.sendMessage(p))},ce=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),_.click())},se=null,me=!1,Se=null,Te=null,Ee=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,L=(a="user")=>{var ne,pe,h,ee;if(me||E.isStreaming())return;let p=Ee();if(!p)return;se=new p;let F=(pe=((ne=e.voiceRecognition)!=null?ne:{}).pauseDuration)!=null?pe:2e3;se.continuous=!0,se.interimResults=!0,se.lang="en-US";let B=de.value;se.onresult=J=>{let oe="",P="";for(let we=0;we<J.results.length;we++){let ue=J.results[we],Pe=ue[0].transcript;ue.isFinal?oe+=Pe+" ":P=Pe}let te=B+oe+P;de.value=te,Se&&clearTimeout(Se),(oe||P)&&(Se=window.setTimeout(()=>{let we=de.value.trim();we&&se&&me&&(Oe(),de.value="",E.sendMessage(we,{viaVoice:!0}))},F))},se.onerror=J=>{J.error!=="no-speech"&&Oe()},se.onend=()=>{if(me){let J=de.value.trim();J&&J!==B.trim()&&(de.value="",E.sendMessage(J,{viaVoice:!0})),Oe()}};try{if(se.start(),me=!0,Z.active=!0,a!=="system"&&(Z.manuallyDeactivated=!1),bt(a),gt(),I){Te={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor};let J=(h=e.voiceRecognition)!=null?h:{},oe=(ee=J.recordingBackgroundColor)!=null?ee:"#ef4444",P=J.recordingIconColor,te=J.recordingBorderColor;if(I.classList.add("tvw-voice-recording"),I.style.backgroundColor=oe,P){I.style.color=P;let we=I.querySelector("svg");we&&we.setAttribute("stroke",P)}te&&(I.style.borderColor=te),I.setAttribute("aria-label","Stop voice recognition")}}catch{Oe("system")}},Oe=(a="user")=>{if(me){if(me=!1,Se&&(clearTimeout(Se),Se=null),se){try{se.stop()}catch{}se=null}if(Z.active=!1,bt(a),gt(),I){if(I.classList.remove("tvw-voice-recording"),Te){I.style.backgroundColor=Te.backgroundColor,I.style.color=Te.color,I.style.borderColor=Te.borderColor;let p=I.querySelector("svg");p&&p.setAttribute("stroke",Te.color||"currentColor"),Te=null}I.setAttribute("aria-label","Start voice recognition")}}},ae=(a,p)=>{var Pe,it,Xe,he,jt,Ht,Rt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let F=f("div","tvw-send-button-wrapper"),B=f("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let ne=(Pe=a==null?void 0:a.iconName)!=null?Pe:"mic",pe=(it=p==null?void 0:p.size)!=null?it:"40px",h=(Xe=a==null?void 0:a.iconSize)!=null?Xe:pe,ee=parseFloat(h)||24,J=(he=a==null?void 0:a.backgroundColor)!=null?he:p==null?void 0:p.backgroundColor,oe=(jt=a==null?void 0:a.iconColor)!=null?jt:p==null?void 0:p.textColor;B.style.width=h,B.style.height=h,B.style.minWidth=h,B.style.minHeight=h,B.style.fontSize="18px",B.style.lineHeight="1";let P=oe||"currentColor",te=ge(ne,ee,P,1.5);te?(B.appendChild(te),B.style.color=P):(B.textContent="\u{1F3A4}",B.style.color=P),J?B.style.backgroundColor=J:B.classList.add("tvw-bg-cw-primary"),oe?B.style.color=oe:!oe&&!(p!=null&&p.textColor)&&B.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(B.style.borderWidth=a.borderWidth,B.style.borderStyle="solid"),a!=null&&a.borderColor&&(B.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(B.style.paddingLeft=a.paddingX,B.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(B.style.paddingTop=a.paddingY,B.style.paddingBottom=a.paddingY),F.appendChild(B);let we=(Ht=a==null?void 0:a.tooltipText)!=null?Ht:"Start voice recognition";if(((Rt=a==null?void 0:a.showTooltip)!=null?Rt:!1)&&we){let Mt=f("div","tvw-send-button-tooltip");Mt.textContent=we,F.appendChild(Mt)}return{micButton:B,micButtonWrapper:F}},M=()=>{if(me){let a=de.value.trim();Z.manuallyDeactivated=!0,gt(),Oe("user"),a&&(de.value="",E.sendMessage(a))}else Z.manuallyDeactivated=!1,gt(),L("user")};I&&(I.addEventListener("click",M),He.push(()=>{Oe("system"),I&&I.removeEventListener("click",M)}));let A=o.on("assistant:complete",()=>{pt&&(Z.active||Z.manuallyDeactivated||pt==="assistant"&&!Z.lastUserMessageWasVoice||setTimeout(()=>{!Z.active&&!Z.manuallyDeactivated&&L("auto")},600))});He.push(A);let z=()=>{Ke(!b,"user")},K=null,X=null;if(g){let a=r.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:e,defaultRenderer:()=>tn(e,z).element,onToggle:z});p&&(X=p)}X||(K=tn(e,z))}K?n.appendChild(K.element):X&&n.appendChild(X),_t(),ot.render(e.suggestionChips,E,de,void 0,e.suggestionChipsConfig),Zt(),Jt(E.isStreaming()),Ot(!0),Bt();let je=()=>{var T,F,B,ne,pe,h,ee,J;let a=(F=(T=e.launcher)==null?void 0:T.sidebarMode)!=null?F:!1,p=a||((ne=(B=e.launcher)==null?void 0:B.fullHeight)!=null?ne:!1);if(!g){O.style.height="",O.style.width="";return}if(!a){let oe=(h=(pe=e==null?void 0:e.launcher)==null?void 0:pe.width)!=null?h:e==null?void 0:e.launcherWidth,P=oe!=null?oe:"min(400px, calc(100vw - 24px))";O.style.width=P,O.style.maxWidth=P}if(!p){let oe=window.innerHeight,P=64,te=(J=(ee=e.launcher)==null?void 0:ee.heightOffset)!=null?J:0,we=Math.max(200,oe-P),ue=Math.min(640,we),Pe=Math.max(200,ue-te);O.style.height=`${Pe}px`}};je(),window.addEventListener("resize",je),He.push(()=>window.removeEventListener("resize",je)),Le=U.scrollTop;let ke=()=>{let a=U.scrollTop,p=U.scrollHeight,T=U.clientHeight,F=p-a-T,B=Math.abs(a-Le);if(Le=a,!At&&!(B<=Lt)){if(!V&&F<Nt){Ne=!1,V=!0;return}V&&F>Nt&&(Ne=!0,ut=Date.now()+Wt,V=!1)}};U.addEventListener("scroll",ke,{passive:!0}),He.push(()=>U.removeEventListener("scroll",ke)),He.push(()=>{Fe&&cancelAnimationFrame(Fe)});let De=()=>{q&&(Ye&&(q.removeEventListener("click",Ye),Ye=null),g?(q.style.display="",Ye=()=>{b=!1,_t()},q.addEventListener("click",Ye)):q.style.display="none")};De(),(()=>{let{clearChatButton:a}=G;a&&a.addEventListener("click",()=>{E.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(F=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",F)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}l={},C.syncFromMetadata()})})(),Ge.addEventListener("submit",k),de.addEventListener("keydown",ce),He.push(()=>{Ge.removeEventListener("submit",k),de.removeEventListener("keydown",ce)}),He.push(()=>{E.cancel()}),K?He.push(()=>{K==null||K.destroy()}):X&&He.push(()=>{X==null||X.remove()});let re={update(a){var Ut,Yt,ms,hs,fs,ws,ys,vs,bs,Cs,xs,Ss,As,Ts,Es,ks,Ms,Ws,Ls,Bs,Hs,Rs,Ps,Is,$s,Fs,Ns,Os,Ds,_s,js,qs,Us,zs,Js,Ys,Ks,Xs,Vs,Gs,Qs,Zs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho;let p=e.toolCall,T=e.colorScheme;e={...e,...a},wt(),wn(n,e),e.colorScheme!==T&&yt();let F=vn.getForInstance(e.plugins);if(r.length=0,r.push(...F),g=(Yt=(Ut=e.launcher)==null?void 0:Ut.enabled)!=null?Yt:!0,j=(hs=(ms=e.launcher)==null?void 0:ms.autoExpand)!=null?hs:!1,v=(ws=(fs=e.features)==null?void 0:fs.showReasoning)!=null?ws:!0,N=(vs=(ys=e.features)==null?void 0:ys.showToolCalls)!=null?vs:!0,((bs=e.launcher)==null?void 0:bs.enabled)===!1&&K&&(K.destroy(),K=null),((Cs=e.launcher)==null?void 0:Cs.enabled)===!1&&X&&(X.remove(),X=null),((xs=e.launcher)==null?void 0:xs.enabled)!==!1&&!K&&!X){let H=r.find(be=>be.renderLauncher);if(H!=null&&H.renderLauncher){let be=H.renderLauncher({config:e,defaultRenderer:()=>tn(e,z).element,onToggle:z});be&&(X=be,n.appendChild(X))}X||(K=tn(e,z),n.appendChild(K.element))}K&&K.update(e),ht&&((Ss=e.launcher)==null?void 0:Ss.title)!==void 0&&(ht.textContent=e.launcher.title),ft&&((As=e.launcher)==null?void 0:As.subtitle)!==void 0&&(ft.textContent=e.launcher.subtitle),g!==m?g?Ke(j,"auto"):(b=!0,_t()):j!==$&&Ke(j,"auto"),$=j,m=g,je(),De(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&E&&Dt(Q,E.getMessages(),W);let h=(Ts=e.launcher)!=null?Ts:{},ee=(Es=h.headerIconHidden)!=null?Es:!1,J=h.headerIconName,oe=(ks=h.headerIconSize)!=null?ks:"48px";if(ve){let H=D.querySelector(".tvw-border-b-cw-divider"),be=H==null?void 0:H.querySelector(".tvw-flex-col");if(ee)ve.style.display="none",H&&be&&!H.contains(be)&&H.insertBefore(be,H.firstChild);else{if(ve.style.display="",ve.style.height=oe,ve.style.width=oe,H&&be&&(H.contains(ve)?ve.nextSibling!==be&&(ve.remove(),H.insertBefore(ve,be)):H.insertBefore(ve,be)),J){let Me=parseFloat(oe)||24,xe=ge(J,Me*.6,"#ffffff",2);xe?ve.replaceChildren(xe):ve.textContent=(Ms=h.agentIconText)!=null?Ms:"\u{1F4AC}"}else if(h.iconUrl){let Me=ve.querySelector("img");if(Me)Me.src=h.iconUrl,Me.style.height=oe,Me.style.width=oe;else{let xe=document.createElement("img");xe.src=h.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=oe,xe.style.width=oe,ve.replaceChildren(xe)}}else{let Me=ve.querySelector("svg"),xe=ve.querySelector("img");(Me||xe)&&ve.replaceChildren(),ve.textContent=(Ws=h.agentIconText)!=null?Ws:"\u{1F4AC}"}let le=ve.querySelector("img");le&&(le.style.height=oe,le.style.width=oe)}}if(q){let H=(Ls=h.closeButtonSize)!=null?Ls:"32px",be=(Bs=h.closeButtonPlacement)!=null?Bs:"inline";q.style.height=H,q.style.width=H;let{closeButtonWrapper:le}=G,Me=be==="top-right",xe=le==null?void 0:le.classList.contains("tvw-absolute");if(le&&Me!==xe)if(le.remove(),Me)le.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",D.style.position="relative",D.appendChild(le);else{let ye=(Rs=(Hs=h.clearChat)==null?void 0:Hs.placement)!=null?Rs:"inline",et=(Is=(Ps=h.clearChat)==null?void 0:Ps.enabled)!=null?Is:!0;le.className=et&&ye==="inline"?"":"tvw-ml-auto";let tt=D.querySelector(".tvw-border-b-cw-divider");tt&&tt.appendChild(le)}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 ye=h.closeButtonBorderWidth||"0px",et=h.closeButtonBorderColor||"transparent";q.style.border=`${ye} solid ${et}`,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=($s=h.closeButtonIconName)!=null?$s:"x",Ue=(Fs=h.closeButtonIconText)!=null?Fs:"\xD7";q.innerHTML="";let ct=ge(Ze,"20px",h.closeButtonColor||"",2);ct?q.appendChild(ct):q.textContent=Ue;let Ft=(Ns=h.closeButtonTooltipText)!=null?Ns:"Close chat",Ae=(Os=h.closeButtonShowTooltip)!=null?Os:!0;if(q.setAttribute("aria-label",Ft),le&&(le._cleanupTooltip&&(le._cleanupTooltip(),delete le._cleanupTooltip),Ae&&Ft)){let ye=null,et=()=>{if(ye||!q)return;ye=f("div","tvw-clear-chat-tooltip"),ye.textContent=Ft;let Kt=f("div");Kt.className="tvw-clear-chat-tooltip-arrow",ye.appendChild(Kt);let Mn=q.getBoundingClientRect();ye.style.position="fixed",ye.style.left=`${Mn.left+Mn.width/2}px`,ye.style.top=`${Mn.top-8}px`,ye.style.transform="translate(-50%, -100%)",document.body.appendChild(ye)},tt=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};le.addEventListener("mouseenter",et),le.addEventListener("mouseleave",tt),q.addEventListener("focus",et),q.addEventListener("blur",tt),le._cleanupTooltip=()=>{tt(),le&&(le.removeEventListener("mouseenter",et),le.removeEventListener("mouseleave",tt)),q&&(q.removeEventListener("focus",et),q.removeEventListener("blur",tt))}}}let{clearChatButton:P,clearChatButtonWrapper:te}=G;if(P){let H=(Ds=h.clearChat)!=null?Ds:{},be=(_s=H.enabled)!=null?_s:!0,le=(js=H.placement)!=null?js:"inline";if(te){te.style.display=be?"":"none";let Me=le==="top-right",xe=te.classList.contains("tvw-absolute");if(Me!==xe&&be){if(te.remove(),Me)te.className="tvw-absolute tvw-top-4 tvw-z-50",te.style.right="48px",D.style.position="relative",D.appendChild(te);else{te.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",te.style.right="";let Ue=D.querySelector(".tvw-border-b-cw-divider"),ct=G.closeButtonWrapper;Ue&&ct&&ct.parentElement===Ue?Ue.insertBefore(te,ct):Ue&&Ue.appendChild(te)}let Ze=G.closeButtonWrapper;Ze&&!Ze.classList.contains("tvw-absolute")&&(Me?Ze.classList.add("tvw-ml-auto"):Ze.classList.remove("tvw-ml-auto"))}}if(be){let Me=(qs=H.size)!=null?qs:"32px";P.style.height=Me,P.style.width=Me;let xe=(Us=H.iconName)!=null?Us:"refresh-cw",Ze=(zs=H.iconColor)!=null?zs:"";P.innerHTML="";let Ue=ge(xe,"20px",Ze||"",2);if(Ue&&P.appendChild(Ue),Ze?(P.style.color=Ze,P.classList.remove("tvw-text-cw-muted")):(P.style.color="",P.classList.add("tvw-text-cw-muted")),H.backgroundColor?(P.style.backgroundColor=H.backgroundColor,P.classList.remove("hover:tvw-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:tvw-bg-gray-100")),H.borderWidth||H.borderColor){let Ae=H.borderWidth||"0px",ye=H.borderColor||"transparent";P.style.border=`${Ae} solid ${ye}`,P.classList.remove("tvw-border-none")}else P.style.border="",P.classList.add("tvw-border-none");H.borderRadius?(P.style.borderRadius=H.borderRadius,P.classList.remove("tvw-rounded-full")):(P.style.borderRadius="",P.classList.add("tvw-rounded-full")),H.paddingX?(P.style.paddingLeft=H.paddingX,P.style.paddingRight=H.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),H.paddingY?(P.style.paddingTop=H.paddingY,P.style.paddingBottom=H.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let ct=(Js=H.tooltipText)!=null?Js:"Clear chat",Ft=(Ys=H.showTooltip)!=null?Ys:!0;if(P.setAttribute("aria-label",ct),te&&(te._cleanupTooltip&&(te._cleanupTooltip(),delete te._cleanupTooltip),Ft&&ct)){let Ae=null,ye=()=>{if(Ae||!P)return;Ae=f("div","tvw-clear-chat-tooltip"),Ae.textContent=ct;let tt=f("div");tt.className="tvw-clear-chat-tooltip-arrow",Ae.appendChild(tt);let Kt=P.getBoundingClientRect();Ae.style.position="fixed",Ae.style.left=`${Kt.left+Kt.width/2}px`,Ae.style.top=`${Kt.top-8}px`,Ae.style.transform="translate(-50%, -100%)",document.body.appendChild(Ae)},et=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};te.addEventListener("mouseenter",ye),te.addEventListener("mouseleave",et),P.addEventListener("focus",ye),P.addEventListener("blur",et),te._cleanupTooltip=()=>{et(),te&&(te.removeEventListener("mouseenter",ye),te.removeEventListener("mouseleave",et)),P&&(P.removeEventListener("focus",ye),P.removeEventListener("blur",et))}}}}let we=e.actionParsers&&e.actionParsers.length?e.actionParsers:[bn],ue=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Vt.message,Vt.messageAndClick];C=Cn({parsers:we,handlers:ue,getMetadata:c,updateMetadata:w,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),W=jo(e,C),E.updateConfig(e),Dt(Q,E.getMessages(),W),ot.render(e.suggestionChips,E,de,void 0,e.suggestionChipsConfig),Zt(),Jt(E.isStreaming());let Pe=((Ks=e.voiceRecognition)==null?void 0:Ks.enabled)===!0,it=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Xe=Pe&⁢if(Ge.classList.remove("tvw-gap-1","tvw-gap-3"),Ge.classList.add(Xe?"tvw-gap-1":"tvw-gap-3"),Pe&&it)if(!I||!Be){let H=ae(e.voiceRecognition,e.sendButton);H&&(I=H.micButton,Be=H.micButtonWrapper,Ge.insertBefore(Be,ze),I.addEventListener("click",M),I.disabled=E.isStreaming())}else{let H=(Xs=e.voiceRecognition)!=null?Xs:{},be=(Vs=e.sendButton)!=null?Vs:{},le=(Gs=H.iconName)!=null?Gs:"mic",Me=(Qs=be.size)!=null?Qs:"40px",xe=(Zs=H.iconSize)!=null?Zs:Me,Ze=parseFloat(xe)||24;I.style.width=xe,I.style.height=xe,I.style.minWidth=xe,I.style.minHeight=xe;let Ue=(to=(eo=H.iconColor)!=null?eo:be.textColor)!=null?to:"currentColor";I.innerHTML="";let ct=ge(le,Ze,Ue,2);ct?I.appendChild(ct):I.textContent="\u{1F3A4}";let Ft=(no=H.backgroundColor)!=null?no:be.backgroundColor;Ft?(I.style.backgroundColor=Ft,I.classList.remove("tvw-bg-cw-primary")):(I.style.backgroundColor="",I.classList.add("tvw-bg-cw-primary")),Ue?(I.style.color=Ue,I.classList.remove("tvw-text-white")):!Ue&&!be.textColor&&(I.style.color="",I.classList.add("tvw-text-white")),H.borderWidth?(I.style.borderWidth=H.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),H.borderColor?I.style.borderColor=H.borderColor:I.style.borderColor="",H.paddingX?(I.style.paddingLeft=H.paddingX,I.style.paddingRight=H.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),H.paddingY?(I.style.paddingTop=H.paddingY,I.style.paddingBottom=H.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let Ae=Be==null?void 0:Be.querySelector(".tvw-send-button-tooltip"),ye=(so=H.tooltipText)!=null?so:"Start voice recognition";if(((oo=H.showTooltip)!=null?oo:!1)&&ye)if(Ae)Ae.textContent=ye,Ae.style.display="";else{let tt=document.createElement("div");tt.className="tvw-send-button-tooltip",tt.textContent=ye,Be==null||Be.insertBefore(tt,I)}else Ae&&(Ae.style.display="none");Be.style.display="",I.disabled=E.isStreaming()}else I&&Be&&(Be.style.display="none",me&&Oe());let he=(ro=e.sendButton)!=null?ro:{},jt=(io=he.useIcon)!=null?io:!1,Ht=(ao=he.iconText)!=null?ao:"\u2191",Rt=he.iconName,Mt=(lo=he.tooltipText)!=null?lo:"Send message",un=(co=he.showTooltip)!=null?co:!1,Pt=(uo=he.size)!=null?uo:"40px",qt=he.backgroundColor,dt=he.textColor;if(jt){if(_.style.width=Pt,_.style.height=Pt,_.style.minWidth=Pt,_.style.minHeight=Pt,_.style.fontSize="18px",_.style.lineHeight="1",_.innerHTML="",Rt){let H=parseFloat(Pt)||24,be=dt&&typeof dt=="string"&&dt.trim()?dt.trim():"currentColor",le=ge(Rt,H,be,2);le?(_.appendChild(le),_.style.color=be):(_.textContent=Ht,dt?_.style.color=dt:_.classList.add("tvw-text-white"))}else _.textContent=Ht,dt?_.style.color=dt:_.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=(go=(po=e.copy)==null?void 0:po.sendButtonLabel)!=null?go:"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"),dt?_.style.color=dt:_.classList.add("tvw-text-white");he.borderWidth?(_.style.borderWidth=he.borderWidth,_.style.borderStyle="solid"):(_.style.borderWidth="",_.style.borderStyle=""),he.borderColor?_.style.borderColor=he.borderColor:_.style.borderColor="",he.paddingX?(_.style.paddingLeft=he.paddingX,_.style.paddingRight=he.paddingX):(_.style.paddingLeft="",_.style.paddingRight=""),he.paddingY?(_.style.paddingTop=he.paddingY,_.style.paddingBottom=he.paddingY):(_.style.paddingTop="",_.style.paddingBottom="");let It=ze==null?void 0:ze.querySelector(".tvw-send-button-tooltip");if(un&&Mt)if(It)It.textContent=Mt,It.style.display="";else{let H=document.createElement("div");H.className="tvw-send-button-tooltip",H.textContent=Mt,ze==null||ze.insertBefore(H,_)}else It&&(It.style.display="none");let $t=(mo=e.statusIndicator)!=null?mo:{},pn=(ho=$t.visible)!=null?ho:!0;if(nt.style.display=pn?"":"none",E){let H=E.getStatus(),be=le=>{var Me,xe,Ze,Ue;return le==="idle"?(Me=$t.idleText)!=null?Me:Ve.idle:le==="connecting"?(xe=$t.connectingText)!=null?xe:Ve.connecting:le==="connected"?(Ze=$t.connectedText)!=null?Ze:Ve.connected:le==="error"?(Ue=$t.errorText)!=null?Ue:Ve.error:Ve[le]};nt.textContent=be(H)}},open(){g&&Ke(!0,"api")},close(){g&&Ke(!1,"api")},toggle(){g&&Ke(!b,"api")},clearChat(){E.clearMessages();try{localStorage.removeItem(Gt),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gt}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gt)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},C.syncFromMetadata()},setMessage(a){return!de||E.isStreaming()?!1:(!b&&g&&Ke(!0,"system"),de.value=a,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(E.isStreaming())return!1;let p=(a==null?void 0:a.trim())||de.value.trim();return p?(!b&&g&&Ke(!0,"system"),de.value="",E.sendMessage(p),!0):!1},startVoiceRecognition(){return me||E.isStreaming()||!Ee()?!1:(!b&&g&&Ke(!0,"system"),Z.manuallyDeactivated=!1,gt(),L("user"),!0)},stopVoiceRecognition(){return me?(Z.manuallyDeactivated=!0,gt(),Oe("user"),!0):!1},injectTestMessage(a){!b&&g&&Ke(!0,"system"),E.injectTestEvent(a)},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){w(a)},on(a,p){return o.on(a,p)},off(a,p){o.off(a,p)},isOpen(){return g&&b},isVoiceActive(){return Z.active},getState(){return{open:g&&b,launcherEnabled:g,voiceActive:Z.active,streaming:E.isStreaming()}},showCSATFeedback(a){!b&&g&&Ke(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let T=es({onSubmit:async(F,B)=>{var ne;E.isClientTokenMode()&&await E.submitCSATFeedback(F,B),(ne=a==null?void 0:a.onSubmit)==null||ne.call(a,F,B)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!b&&g&&Ke(!0,"system");let p=Q.querySelector(".tvw-feedback-container");p&&p.remove();let T=ts({onSubmit:async(F,B)=>{var ne;E.isClientTokenMode()&&await E.submitNPSFeedback(F,B),(ne=a==null?void 0:a.onSubmit)==null||ne.call(a,F,B)},onDismiss:a==null?void 0:a.onDismiss,...a});Q.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,p){return E.submitCSATFeedback(a,p)},async submitNPSFeedback(a,p){return E.submitNPSFeedback(a,p)},destroy(){He.forEach(a=>a()),R.remove(),K==null||K.destroy(),X==null||X.remove(),Ye&&q.removeEventListener("click",Ye)}};if((((gs=s==null?void 0:s.debugTools)!=null?gs:!1)||!!e.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:re,getMessages:re.getMessages,getStatus:re.getStatus,getMetadata:re.getPersistentMetadata,updateMetadata:re.updatePersistentMetadata,clearHistory:()=>re.clearChat(),setVoiceActive:T=>T?re.startVoiceRecognition():re.stopVoiceRecognition()};window.AgentWidgetBrowser=p,He.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return re};var os={},Ar=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 t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},Tr=()=>{try{if(typeof os!="undefined"&&os.url)return new URL("../widget.css",os.url).href}catch{}return null},qo=n=>{let t=Tr(),s=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let e=document.head.querySelector("link[data-vanilla-agent]");if(!e)return;let r=e.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-vanilla-agent","true"),n.insertBefore(e,n.firstChild)}else s();else if(!document.head.querySelector("link[data-vanilla-agent]")&&t){let r=document.createElement("link");r.rel="stylesheet",r.href=t,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},Uo=n=>{var c,w,y,u;let t=Ar(n.target),s=document.createElement("div");s.className="vanilla-agent-host";let e=(y=(w=(c=n.config)==null?void 0:c.launcher)==null?void 0:w.enabled)!=null?y:!0;e||(s.style.height="100%"),t.appendChild(s);let r=n.useShadowDom===!0,o,i;if(r){let C=s.attachShadow({mode:"open"});i=C,o=document.createElement("div"),o.id="vanilla-agent-root",e||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),C.appendChild(o),qo(C)}else i=s,o=document.createElement("div"),o.id="vanilla-agent-root",e||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1",o.style.minHeight="0"),s.appendChild(o),qo(s);let l=ss(o,n.config,{debugTools:n.debugTools});(u=n.onReady)==null||u.call(n);let d={...l,host:s,destroy(){l.destroy(),s.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=d),d};function Er(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function xn(n){var t,s;return(s=(t=n.parserType)!=null?t:Er(n.streamParser))!=null?s:"plain"}function Sn(n,t){let s=[];return n.toolCall&&(s.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,r])=>{typeof r=="string"&&s.push(`${t} ${e}: "${r}",`)}),s.push(`${t}},`)),s}function An(n,t){let s=[];return n.messageActions&&Object.entries(n.messageActions).some(([r,o])=>r!=="onFeedback"&&r!=="onCopy"&&o!==void 0)&&(s.push(`${t}messageActions: {`),Object.entries(n.messageActions).forEach(([r,o])=>{r==="onFeedback"||r==="onCopy"||(typeof o=="string"?s.push(`${t} ${r}: "${o}",`):typeof o=="boolean"&&s.push(`${t} ${r}: ${o},`))}),s.push(`${t}},`)),s}function Tn(n,t){let s=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,r=n.markdown.disableDefaultStyles!==void 0;(e||r)&&(s.push(`${t}markdown: {`),e&&(s.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([o,i])=>{typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`)}),s.push(`${t} },`)),r&&s.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),s.push(`${t}},`))}return s}function En(n,t){let s=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(o=>o!=="render"),r=n.layout.messages&&Object.keys(n.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(e||r)&&(s.push(`${t}layout: {`),e&&(s.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([o,i])=>{o!=="render"&&(typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`))}),s.push(`${t} },`)),r&&(s.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([o,i])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof i=="object"&&i!==null?(s.push(`${t} avatar: {`),Object.entries(i).forEach(([l,d])=>{typeof d=="string"?s.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&s.push(`${t} ${l}: ${d},`)}),s.push(`${t} },`)):o==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(s.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?s.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&s.push(`${t} ${d}: ${c},`))}),s.push(`${t} },`)):typeof i=="string"?s.push(`${t} ${o}: "${i}",`):typeof i=="boolean"&&s.push(`${t} ${o}: ${i},`))}),s.push(`${t} },`)),s.push(`${t}},`))}return s}function kr(n,t="esm"){let s={...n};return delete s.postprocessMessage,delete s.initialMessages,t==="esm"?Mr(s):t==="script-installer"?Br(s):t==="script-advanced"?Rr(s):t==="react-component"?Wr(s):t==="react-advanced"?Lr(s):Hr(s)}function Mr(n){let t=xn(n),s=t!=="plain",e=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),s&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"?e.push(` ${r}: ${o},`):typeof o=="number"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{e.push(` ${r}: ${o},`)}),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(" },")),e.push(...Sn(n," ")),e.push(...An(n," ")),e.push(...Tn(n," ")),e.push(...En(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push("});"),e.join(`
|
|
61
61
|
`)}function Wr(n){let t=xn(n),s=t!=="plain",e=["// 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&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),s&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"?e.push(` ${r}: ${o},`):typeof o=="number"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{e.push(` ${r}: ${o},`)}),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(" },")),e.push(...Sn(n," ")),e.push(...An(n," ")),e.push(...Tn(n," ")),e.push(...En(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),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 in your app:"),e.push("// import { ChatWidget } from './components/ChatWidget';"),e.push("//"),e.push("// export default function App() {"),e.push("// return ("),e.push("// <div>"),e.push("// {/* Your app content */}"),e.push("// <ChatWidget />"),e.push("// </div>"),e.push("// );"),e.push("// }"),e.join(`
|
|
62
62
|
`)}function Lr(n){let t=["// 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&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([s,e])=>{t.push(` ${s}: "${e}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([s,e])=>{typeof e=="string"?t.push(` ${s}: "${e}",`):typeof e=="boolean"&&t.push(` ${s}: ${e},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([s,e])=>{t.push(` ${s}: "${e}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([s,e])=>{typeof e=="string"?t.push(` ${s}: "${e}",`):typeof e=="boolean"&&t.push(` ${s}: ${e},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([s,e])=>{typeof e=="string"?t.push(` ${s}: "${e}",`):typeof e=="boolean"?t.push(` ${s}: ${e},`):typeof e=="number"&&t.push(` ${s}: ${e},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([s,e])=>{typeof e=="string"?t.push(` ${s}: "${e}",`):typeof e=="boolean"&&t.push(` ${s}: ${e},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([s,e])=>{t.push(` ${s}: ${e},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(s=>{t.push(` "${s}",`)}),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(" },")),t.push(...Sn(n," ")),t.push(...An(n," ")),t.push(...Tn(n," ")),t.push(...En(n," ")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" initialMessages: loadSavedMessages(),"),t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),t.push(" if (!parsed || typeof parsed !== 'object') return null;"),t.push(" // Extract display text based on action type"),t.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),t.push(" if (parsed.action === 'message') return parsed.text || '';"),t.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),t.push(" return parsed.text || null;"),t.push(" }),"),t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Custom parser for markdown-wrapped JSON"),t.push(" ({ text, message }: any) => {"),t.push(" const jsonSource = (message as any).rawContent || text || message.content;"),t.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),t.push(" // Strip markdown code fences"),t.push(" let cleanJson = jsonSource"),t.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),t.push(" .replace(/\\n?```\\s*$/, '')"),t.push(" .trim();"),t.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),t.push(" try {"),t.push(" const parsed = JSON.parse(cleanJson);"),t.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),t.push(" } catch (e) { return null; }"),t.push(" return null;"),t.push(" }"),t.push(" ],"),t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(" (action: any, context: any) => {"),t.push(" if (action.type !== 'nav_then_click') return;"),t.push(" const payload = action.payload || action.raw || {};"),t.push(" const url = payload?.page;"),t.push(" const text = payload?.on_load_text || 'Navigating...';"),t.push(" if (!url) return { handled: true, displayText: text };"),t.push(" // Check if already processed"),t.push(" const messageId = context.message?.id;"),t.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),t.push(" const actionKey = `nav_${messageId}_${url}`;"),t.push(" if (processedActions.includes(actionKey)) {"),t.push(" return { handled: true, displayText: text };"),t.push(" }"),t.push(" processedActions.push(actionKey);"),t.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),t.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),t.push(" window.location.href = targetUrl;"),t.push(" return { handled: true, displayText: text };"),t.push(" }"),t.push(" ],"),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),t.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),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: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
|
|
63
63
|
`)}function zo(n){var r;let t=xn(n),s=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.flowId&&(e.flowId=n.flowId),s&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((r=n.suggestionChips)==null?void 0:r.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let o={};Object.entries(n.toolCall).forEach(([i,l])=>{typeof l=="string"&&(o[i]=l)}),Object.keys(o).length>0&&(e.toolCall=o)}if(n.messageActions){let o={};Object.entries(n.messageActions).forEach(([i,l])=>{i!=="onFeedback"&&i!=="onCopy"&&l!==void 0&&(typeof l=="string"||typeof l=="boolean")&&(o[i]=l)}),Object.keys(o).length>0&&(e.messageActions=o)}if(n.markdown){let o={};n.markdown.options&&(o.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(o).length>0&&(e.markdown=o)}if(n.layout){let o={};if(n.layout.header){let i={};Object.entries(n.layout.header).forEach(([l,d])=>{l!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[l]=d)}),Object.keys(i).length>0&&(o.header=i)}if(n.layout.messages){let i={};Object.entries(n.layout.messages).forEach(([l,d])=>{if(l!=="renderUserMessage"&&l!=="renderAssistantMessage")if(l==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(l==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([w,y])=>{w!=="format"&&(typeof y=="string"||typeof y=="boolean")&&(c[w]=y)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(i[l]=d)}),Object.keys(i).length>0&&(o.messages=i)}Object.keys(o).length>0&&(e.layout=o)}return e}function Br(n){let t=zo(n);return`<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js" data-config='${JSON.stringify(t,null,0).replace(/'/g,"'")}'></script>`}function Hr(n){let t=xn(n),s=t!=="plain",e=["<!-- 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&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),s&&e.push(` parserType: "${t}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([r,o])=>{e.push(` ${r}: "${o}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"?e.push(` ${r}: ${o},`):typeof o=="number"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,o])=>{typeof o=="string"?e.push(` ${r}: "${o}",`):typeof o=="boolean"&&e.push(` ${r}: ${o},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([r,o])=>{e.push(` ${r}: ${o},`)}),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(" },")),e.push(...Sn(n," ")),e.push(...An(n," ")),e.push(...Tn(n," ")),e.push(...En(n," ")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),e.push(" }"),e.push(" });"),e.push("</script>"),e.join(`
|
|
64
64
|
`)}function Rr(n){let t=zo(n);return["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
|
|
65
65
|
`).map((r,o)=>o===0?r:" "+r).join(`
|
|
66
|
-
`)};`,""," // Constants"," var CDN_BASE = 'https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist';"," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var 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();",""," var elementData = {"," type: 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);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," 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()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-vanilla-agent]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-vanilla-agent', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""," // Flexible JSON stream parser for handling structured actions"," widgetConfig.streamParser = function() {"," return agentWidget.createFlexibleJsonStreamParser(function(parsed) {"," if (!parsed || typeof parsed !== 'object') return null;"," if (parsed.action === 'nav_then_click') return 'Navigating...';"," if (parsed.action === 'message') return parsed.text || '';"," if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"," return parsed.text || null;"," });"," };",""," // Action parsers to detect JSON actions in responses"," widgetConfig.actionParsers = ["," agentWidget.defaultJsonActionParser,"," function(ctx) {"," var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;"," if (!jsonSource || typeof jsonSource !== 'string') return null;"," var cleanJson = jsonSource"," .replace(/^```(?:json)?\\s*\\n?/, '')"," .replace(/\\n?```\\s*$/, '')"," .trim();"," if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"," try {"," var parsed = JSON.parse(cleanJson);"," if (parsed.action) return { type: parsed.action, payload: parsed };"," } catch (e) { return null; }"," return null;"," }"," ];",""," // Action handlers for navigation and other actions"," widgetConfig.actionHandlers = ["," agentWidget.defaultActionHandlers.message,"," agentWidget.defaultActionHandlers.messageAndClick,"," function(action, context) {"," if (action.type !== 'nav_then_click') return;"," var payload = action.payload || action.raw || {};"," var url = payload.page;"," var text = payload.on_load_text || 'Navigating...';"," if (!url) return { handled: true, displayText: text };"," var messageId = context.message ? context.message.id : null;"," var processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"," var actionKey = 'nav_' + messageId + '_' + url;"," if (processedActions.includes(actionKey)) {"," return { handled: true, displayText: text };"," }"," processedActions.push(actionKey);"," localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"," var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"," window.location.href = targetUrl;"," return { handled: true, displayText: text };"," }"," ];",""," // Send DOM context with each request"," widgetConfig.requestMiddleware = function(ctx) {"," return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"," };",""," // Markdown postprocessor"," widgetConfig.postprocessMessage = function(ctx) {"," return agentWidget.markdownPostprocessor(ctx.text);"," };",""," return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('vanilla-agent:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('vanilla-agent:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," //
|
|
67
|
-
`)}var Sa=Uo;export{Xt as AgentWidgetClient,en as AgentWidgetSession,No as DEFAULT_DARK_THEME,Fo as DEFAULT_LIGHT_THEME,We as DEFAULT_WIDGET_CONFIG,nn as attachHeaderToContainer,sn as buildComposer,
|
|
66
|
+
`)};`,""," // Constants"," var CDN_BASE = 'https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist';"," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var 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();",""," var elementData = {"," type: 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);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," 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()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-vanilla-agent]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-vanilla-agent', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""," // Flexible JSON stream parser for handling structured actions"," widgetConfig.streamParser = function() {"," return agentWidget.createFlexibleJsonStreamParser(function(parsed) {"," if (!parsed || typeof parsed !== 'object') return null;"," if (parsed.action === 'nav_then_click') return 'Navigating...';"," if (parsed.action === 'message') return parsed.text || '';"," if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"," return parsed.text || null;"," });"," };",""," // Action parsers to detect JSON actions in responses"," widgetConfig.actionParsers = ["," agentWidget.defaultJsonActionParser,"," function(ctx) {"," var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;"," if (!jsonSource || typeof jsonSource !== 'string') return null;"," var cleanJson = jsonSource"," .replace(/^```(?:json)?\\s*\\n?/, '')"," .replace(/\\n?```\\s*$/, '')"," .trim();"," if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"," try {"," var parsed = JSON.parse(cleanJson);"," if (parsed.action) return { type: parsed.action, payload: parsed };"," } catch (e) { return null; }"," return null;"," }"," ];",""," // Action handlers for navigation and other actions"," widgetConfig.actionHandlers = ["," agentWidget.defaultActionHandlers.message,"," agentWidget.defaultActionHandlers.messageAndClick,"," function(action, context) {"," if (action.type !== 'nav_then_click') return;"," var payload = action.payload || action.raw || {};"," var url = payload.page;"," var text = payload.on_load_text || 'Navigating...';"," if (!url) return { handled: true, displayText: text };"," var messageId = context.message ? context.message.id : null;"," var processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"," var actionKey = 'nav_' + messageId + '_' + url;"," if (processedActions.includes(actionKey)) {"," return { handled: true, displayText: text };"," }"," processedActions.push(actionKey);"," localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"," var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"," window.location.href = targetUrl;"," return { handled: true, displayText: text };"," }"," ];",""," // Send DOM context with each request"," widgetConfig.requestMiddleware = function(ctx) {"," return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"," };",""," // Markdown postprocessor"," widgetConfig.postprocessMessage = function(ctx) {"," return agentWidget.markdownPostprocessor(ctx.text);"," };",""," return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('vanilla-agent:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('vanilla-agent:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: load CSS, then JS, then wait for hydration, then initialize"," loadCSS();"," loadJS(function() {"," waitForHydration(init);"," });","})();","</script>"].join(`
|
|
67
|
+
`)}var Sa=Uo;export{Xt as AgentWidgetClient,en as AgentWidgetSession,No as DEFAULT_DARK_THEME,Fo as DEFAULT_LIGHT_THEME,We as DEFAULT_WIDGET_CONFIG,nn as attachHeaderToContainer,sn as buildComposer,ko as buildDefaultHeader,Wo as buildExpandedHeader,zt as buildHeader,On as buildHeaderWithLayout,Mo as buildMinimalHeader,rn as componentRegistry,Cn as createActionManager,ss as createAgentExperience,cr as createBubbleWithLayout,es as createCSATFeedback,Cr as createComponentMiddleware,Vn as createComponentStreamParser,Xo as createDirectivePostprocessor,er as createFlexibleJsonStreamParser,Rn as createJsonStreamParser,Kn as createLocalStorageAdapter,gn as createMarkdownProcessor,mn as createMarkdownProcessorFromConfig,Po as createMessageActions,ts as createNPSFeedback,Bn as createPlainTextParser,Hn as createRegexJsonParser,on as createStandardBubble,yn as createTypingIndicator,Pn as createXmlParser,Sa as default,Vt as defaultActionHandlers,bn as defaultJsonActionParser,Vo as directivePostprocessor,Wn as escapeHtml,Zn as extractComponentDirectiveFromMessage,$n as generateAssistantMessageId,kr as generateCodeSnippet,sr as generateMessageId,In as generateUserMessageId,Lo as getHeaderLayout,Qn as hasComponentDirective,Nn as headerLayouts,Uo as initAgentWidget,br as isComponentDirectiveType,wo as markdownPostprocessor,Jn as mergeWithDefaults,vn as pluginRegistry,Gn as renderComponentDirective};
|
|
68
68
|
//# sourceMappingURL=index.js.map
|