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