@runtypelabs/persona 1.37.0 → 1.37.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var bi=Object.create;var $n=Object.defineProperty;var Ci=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Si=Object.getPrototypeOf,Ai=Object.prototype.hasOwnProperty;var Ti=(e,n)=>{for(var o in n)$n(e,o,{get:n[o],enumerable:!0})},Tr=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of xi(n))!Ai.call(e,r)&&r!==o&&$n(e,r,{get:()=>n[r],enumerable:!(t=Ci(n,r))||t.enumerable});return e};var Mi=(e,n,o)=>(o=e!=null?bi(Si(e)):{},Tr(n||!e||!e.__esModule?$n(o,"default",{value:e,enumerable:!0}):o,e)),Ei=e=>Tr($n({},"__esModule",{value:!0}),e);var ga={};Ti(ga,{AgentWidgetClient:()=>Gt,AgentWidgetSession:()=>nn,AttachmentManager:()=>Qt,DEFAULT_DARK_THEME:()=>As,DEFAULT_LIGHT_THEME:()=>Ss,DEFAULT_WIDGET_CONFIG:()=>Be,attachHeaderToContainer:()=>Zt,buildComposer:()=>on,buildDefaultHeader:()=>ms,buildExpandedHeader:()=>fs,buildHeader:()=>qt,buildHeaderWithLayout:()=>sn,buildMinimalHeader:()=>hs,componentRegistry:()=>dn,createActionManager:()=>Ln,createAgentExperience:()=>os,createBubbleWithLayout:()=>ti,createCSATFeedback:()=>ns,createComponentMiddleware:()=>di,createComponentStreamParser:()=>Qn,createDirectivePostprocessor:()=>Lr,createFlexibleJsonStreamParser:()=>Ir,createImagePart:()=>_r,createJsonStreamParser:()=>qn,createLocalStorageAdapter:()=>Gn,createMarkdownProcessor:()=>xn,createMarkdownProcessorFromConfig:()=>Sn,createMessageActions:()=>ys,createNPSFeedback:()=>ss,createPlainTextParser:()=>Dn,createRegexJsonParser:()=>_n,createStandardBubble:()=>rn,createTextPart:()=>zn,createTypingIndicator:()=>En,createXmlParser:()=>Un,default:()=>pa,defaultActionHandlers:()=>en,defaultJsonActionParser:()=>kn,directivePostprocessor:()=>Pr,escapeHtml:()=>On,extractComponentDirectiveFromMessage:()=>ts,fileToImagePart:()=>qr,generateAssistantMessageId:()=>Tn,generateCodeSnippet:()=>wi,generateMessageId:()=>$r,generateUserMessageId:()=>An,getDisplayText:()=>Nr,getHeaderLayout:()=>ws,getImageParts:()=>Dr,hasComponentDirective:()=>es,hasImages:()=>jr,headerLayouts:()=>Xn,initAgentWidget:()=>ks,isComponentDirectiveType:()=>li,markdownPostprocessor:()=>us,mergeWithDefaults:()=>Vn,normalizeContent:()=>Or,pluginRegistry:()=>Wn,renderComponentDirective:()=>Zn,validateImageFile:()=>Ur});module.exports=Ei(ga);var Er=require("marked"),Wi=e=>{if(e)return e},xn=e=>{var r,s;let n=e==null?void 0:e.markedOptions,o=new Er.Marked({gfm:(r=n==null?void 0:n.gfm)!=null?r:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),t=Wi(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},Sn=e=>e?xn({markedOptions:e.options,renderer:e.renderer}):xn(),ki=xn(),us=e=>ki(e),On=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Wr=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Mr=e=>`%%FORM_PLACEHOLDER_${e}%%`,kr=(e,n)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Mr(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let s=Mr(n.length);return n.push({token:s,type:r}),s}),o},Lr=e=>{let n=Sn(e);return o=>{let t=[],r=kr(o,t),s=n(r);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${Wr(a)}"></div>`;s=s.replace(d,f)}),s}},Pr=e=>{let n=[],o=kr(e,n),t=us(o);return n.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Wr(s)}"></div>`;t=t.replace(i,d)}),t};var _t=require("partial-json"),Nn=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ps=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Li=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),o=(a=e.startedAt)!=null?a:n,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Hr=e=>e.status==="complete"?Li(e):e.status==="pending"?"Waiting":"",Pi=e=>{var r,s,i;let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((i=(s=e.startedAt)!=null?s:e.completedAt)!=null?i:Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Br=e=>e.status==="complete"?Pi(e):"Using tool...",Hi=()=>{let e=null,n=0,o=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1
+ "use strict";var xi=Object.create;var On=Object.defineProperty;var Si=Object.getOwnPropertyDescriptor;var Ai=Object.getOwnPropertyNames;var Ti=Object.getPrototypeOf,Mi=Object.prototype.hasOwnProperty;var Ei=(e,n)=>{for(var o in n)On(e,o,{get:n[o],enumerable:!0})},Mr=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Ai(n))!Mi.call(e,r)&&r!==o&&On(e,r,{get:()=>n[r],enumerable:!(t=Si(n,r))||t.enumerable});return e};var Wi=(e,n,o)=>(o=e!=null?xi(Ti(e)):{},Mr(n||!e||!e.__esModule?On(o,"default",{value:e,enumerable:!0}):o,e)),ki=e=>Mr(On({},"__esModule",{value:!0}),e);var fa={};Ei(fa,{AgentWidgetClient:()=>Gt,AgentWidgetSession:()=>sn,AttachmentManager:()=>Qt,DEFAULT_DARK_THEME:()=>Ts,DEFAULT_LIGHT_THEME:()=>As,DEFAULT_WIDGET_CONFIG:()=>Be,VERSION:()=>tn,attachHeaderToContainer:()=>Zt,buildComposer:()=>rn,buildDefaultHeader:()=>hs,buildExpandedHeader:()=>ws,buildHeader:()=>qt,buildHeaderWithLayout:()=>on,buildMinimalHeader:()=>fs,componentRegistry:()=>cn,createActionManager:()=>Pn,createAgentExperience:()=>rs,createBubbleWithLayout:()=>ni,createCSATFeedback:()=>ss,createComponentMiddleware:()=>ci,createComponentStreamParser:()=>Zn,createDirectivePostprocessor:()=>Pr,createFlexibleJsonStreamParser:()=>Rr,createImagePart:()=>qr,createJsonStreamParser:()=>Un,createLocalStorageAdapter:()=>Qn,createMarkdownProcessor:()=>Sn,createMarkdownProcessorFromConfig:()=>An,createMessageActions:()=>vs,createNPSFeedback:()=>os,createPlainTextParser:()=>_n,createRegexJsonParser:()=>qn,createStandardBubble:()=>an,createTextPart:()=>Jn,createTypingIndicator:()=>Wn,createXmlParser:()=>zn,default:()=>ha,defaultActionHandlers:()=>en,defaultJsonActionParser:()=>Ln,directivePostprocessor:()=>Hr,escapeHtml:()=>Nn,extractComponentDirectiveFromMessage:()=>ns,fileToImagePart:()=>Ur,generateAssistantMessageId:()=>Mn,generateCodeSnippet:()=>vi,generateMessageId:()=>Or,generateUserMessageId:()=>Tn,getDisplayText:()=>jr,getHeaderLayout:()=>ys,getImageParts:()=>_r,hasComponentDirective:()=>ts,hasImages:()=>Dr,headerLayouts:()=>Xn,initAgentWidget:()=>Ls,isComponentDirectiveType:()=>di,markdownPostprocessor:()=>ps,mergeWithDefaults:()=>Gn,normalizeContent:()=>Nr,pluginRegistry:()=>kn,renderComponentDirective:()=>es,validateImageFile:()=>zr});module.exports=ki(fa);var Wr=require("marked"),Li=e=>{if(e)return e},Sn=e=>{var r,s;let n=e==null?void 0:e.markedOptions,o=new Wr.Marked({gfm:(r=n==null?void 0:n.gfm)!=null?r:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),t=Li(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},An=e=>e?Sn({markedOptions:e.options,renderer:e.renderer}):Sn(),Pi=Sn(),ps=e=>Pi(e),Nn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),kr=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Er=e=>`%%FORM_PLACEHOLDER_${e}%%`,Lr=(e,n)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Er(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let s=Er(n.length);return n.push({token:s,type:r}),s}),o},Pr=e=>{let n=An(e);return o=>{let t=[],r=Lr(o,t),s=n(r);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${kr(a)}"></div>`;s=s.replace(d,f)}),s}},Hr=e=>{let n=[],o=Lr(e,n),t=ps(o);return n.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${kr(s)}"></div>`;t=t.replace(i,d)}),t};var _t=require("partial-json"),jn=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),gs=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Hi=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),o=(a=e.startedAt)!=null?a:n,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Br=e=>e.status==="complete"?Hi(e):e.status==="pending"?"Waiting":"",Bi=e=>{var r,s,i;let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((i=(s=e.startedAt)!=null?s:e.completedAt)!=null?i:Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Ir=e=>e.status==="complete"?Bi(e):"Using tool...",Ii=()=>{let e=null,n=0,o=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=t.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},jn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Dn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},_n=()=>{var n;let e=Hi();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(o)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},qn=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,_t.parse)(o,_t.STR|_t.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Nn(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Nn(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Ir=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Nn(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Nn(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=o)return n!==null?{text:n,raw:s}:null;try{let a=(0,_t.parse)(s,_t.STR|_t.OBJ),d=r(a);d!==null&&(n=d)}catch{}return o=s.length,{text:n||"",raw:s}},close:()=>{}}},Un=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Bi="https://api.runtype.com/v1/dispatch",Rr="https://api.runtype.com",Fr=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Ii(e){switch(e){case"json":return qn;case"regex-json":return _n;case"xml":return Un;case"plain":default:return Dn}}var Gt=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=n.apiUrl)!=null?o:Bi,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Ii(n.parserType),this.contextProviders=(r=n.contextProviders)!=null?r:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(n){var t;let o=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Rr;return n==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,o;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(o=(n=this.config).onSessionInit)==null||o.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,o={token:this.config.clientToken,...this.config.flowId&&{flow_id:this.config.flowId},...n&&{session_id:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let r=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.session_id),{sessionId:r.session_id,expiresAt:new Date(r.expires_at),flow:r.flow,config:{welcomeMessage:r.config.welcome_message,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Rr}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.message_id)throw new Error(`message_id is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:n,type:o})}async submitCSATFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:n,comment:o})}async submitNPSFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:n,comment:o})}async dispatch(n,o){return this.isClientTokenMode()?this.dispatchClientToken(n,o):this.dispatchProxy(n,o)}async dispatchClientToken(n,o){var r,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let w=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:w}),w}let u=await this.buildPayload(n.messages),f=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([w])=>w!=="session_id")):void 0,g={session_id:d.sessionId,messages:n.messages.filter(Fr).map(w=>{var h,F;return{id:w.id,role:w.role,content:(F=(h=w.contentParts)!=null?h:w.rawContent)!=null?F:w.content}}),...n.assistantMessageId&&{assistant_message_id:n.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...u.context&&{context:u.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g),signal:t.signal});if(!m.ok){let w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let F=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:F}),F}if(m.status===429){let F=new Error(w.hint||"Message limit reached for this session.");throw o({type:"error",error:F}),F}let h=new Error(w.error||"Failed to send message");throw o({type:"error",error:h}),h}if(!m.body){let w=new Error("No response body received");throw o({type:"error",error:w}),w}o({type:"status",status:"connected"});try{await this.streamResponse(m.body,o,n.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&o({type:"error",error:u}),u}}async dispatchProxy(n,o){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal},r)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:a}),a}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(n){let t={messages:n.slice().filter(Fr).sort((r,s)=>{let i=new Date(r.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(r=>{var s,i,a;return{role:r.role,content:(a=(i=(s=r.contentParts)!=null?s:r.llmContent)!=null?i:r.rawContent)!=null?a:r.content,createdAt:r.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(n,o,t,r,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,r(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,o,t){var Pe,V,D,tt,at,lt,Lt,Ft,q,we,dt,ct,ze,ut,$t,Pt,Ht,$,Ne,me,nt,he,st,Te,xt,St,ae,Je,Qe,He,Ye,Wt,ft,ot,R,wt,yt,At,te,ye,Re,vt,Ze,Bt,It,Ot,tn,Nt,ke,pn,gn,jt,Pn,Hn,mn,Yt;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=L=>{let le=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,Se=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,je=L.tools?L.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...L,reasoning:le,toolCall:Se,tools:je}},g=L=>{o({type:"message",message:f(L)})},m=null,w={current:null},h=new Map,F=new Map,W={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},S=L=>{if(L==null)return null;try{return String(L)}catch{return null}},I=L=>{var le,Se,je,et,Ke;return S((Ke=(et=(je=(Se=(le=L.stepId)!=null?le:L.step_id)!=null?Se:L.step)!=null?je:L.parentId)!=null?et:L.flowStepId)!=null?Ke:L.flow_step_id)},v=L=>{var le,Se,je,et,Ke,Le,M;return S((M=(Le=(Ke=(et=(je=(Se=(le=L.callId)!=null?le:L.call_id)!=null?Se:L.requestId)!=null?je:L.request_id)!=null?et:L.toolCallId)!=null?Ke:L.tool_call_id)!=null?Le:L.stepId)!=null?M:L.step_id)},N=()=>m||(m={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},g(m),m),C=(L,le)=>{W.lastId=le,L&&W.byStep.set(L,le)},k=(L,le)=>{var Ke;let Se=(Ke=L.reasoningId)!=null?Ke:L.id,je=I(L);if(Se){let Le=String(Se);return C(je,Le),Le}if(je){let Le=W.byStep.get(je);if(Le)return W.lastId=Le,Le}if(W.lastId&&!le)return W.lastId;if(!le)return null;let et=`reason-${u()}`;return C(je,et),et},K=L=>{let le=h.get(L);if(le)return le;let Se={id:`reason-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:L,status:"streaming",chunks:[]}};return h.set(L,Se),g(Se),Se},J=(L,le)=>{y.lastId=le,L&&y.byCall.set(L,le)},z=(L,le)=>{var Ke;let Se=(Ke=L.toolId)!=null?Ke:L.id,je=v(L);if(Se){let Le=String(Se);return J(je,Le),Le}if(je){let Le=y.byCall.get(je);if(Le)return y.lastId=Le,Le}if(y.lastId&&!le)return y.lastId;if(!le)return null;let et=`tool-${u()}`;return J(je,et),et},_=L=>{let le=F.get(L);if(le)return le;let Se={id:`tool-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:L,status:"pending"}};return F.set(L,Se),g(Se),Se},j=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let le=Number(L);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let Se=Date.parse(L);if(!Number.isNaN(Se))return Se}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},H=new Map,X=new Map;for(;;){let{done:L,value:le}=await r.read();if(L)break;i+=s.decode(le,{stream:!0});let Se=i.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},Dn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},_n=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},qn=()=>{var n;let e=Ii();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(o)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Un=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,_t.parse)(o,_t.STR|_t.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?jn(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=jn(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Rr=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?jn(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?jn(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=o)return n!==null?{text:n,raw:s}:null;try{let a=(0,_t.parse)(s,_t.STR|_t.OBJ),d=r(a);d!==null&&(n=d)}catch{}return o=s.length,{text:n||"",raw:s}},close:()=>{}}},zn=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Ri="https://api.runtype.com/v1/dispatch",Fr="https://api.runtype.com",$r=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Fi(e){switch(e){case"json":return Un;case"regex-json":return qn;case"xml":return zn;case"plain":default:return _n}}var Gt=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=n.apiUrl)!=null?o:Ri,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Fi(n.parserType),this.contextProviders=(r=n.contextProviders)!=null?r:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(n){var t;let o=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Fr;return n==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,o;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(o=(n=this.config).onSessionInit)==null||o.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,o={token:this.config.clientToken,...this.config.flowId&&{flow_id:this.config.flowId},...n&&{session_id:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let r=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.session_id),{sessionId:r.session_id,expiresAt:new Date(r.expires_at),flow:r.flow,config:{welcomeMessage:r.config.welcome_message,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Fr}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.message_id)throw new Error(`message_id is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:n,type:o})}async submitCSATFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:n,comment:o})}async submitNPSFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:n,comment:o})}async dispatch(n,o){return this.isClientTokenMode()?this.dispatchClientToken(n,o):this.dispatchProxy(n,o)}async dispatchClientToken(n,o){var r,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let w=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:w}),w}let u=await this.buildPayload(n.messages),f=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([w])=>w!=="session_id")):void 0,g={session_id:d.sessionId,messages:n.messages.filter($r).map(w=>{var h,F,T;return{id:w.id,role:w.role,content:(T=(F=(h=w.contentParts)!=null?h:w.llmContent)!=null?F:w.rawContent)!=null?T:w.content}}),...n.assistantMessageId&&{assistant_message_id:n.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...u.context&&{context:u.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g),signal:t.signal});if(!m.ok){let w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let F=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:F}),F}if(m.status===429){let F=new Error(w.hint||"Message limit reached for this session.");throw o({type:"error",error:F}),F}let h=new Error(w.error||"Failed to send message");throw o({type:"error",error:h}),h}if(!m.body){let w=new Error("No response body received");throw o({type:"error",error:w}),w}o({type:"status",status:"connected"});try{await this.streamResponse(m.body,o,n.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&o({type:"error",error:u}),u}}async dispatchProxy(n,o){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal},r)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:a}),a}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(n){let t={messages:n.slice().filter($r).sort((r,s)=>{let i=new Date(r.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(r=>{var s,i,a;return{role:r.role,content:(a=(i=(s=r.contentParts)!=null?s:r.llmContent)!=null?i:r.rawContent)!=null?a:r.content,createdAt:r.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(n,o,t,r,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,r(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,o,t){var Pe,X,D,tt,at,lt,Lt,Ft,q,we,dt,ct,ze,ut,$t,Pt,Ht,$,Ne,me,nt,he,st,Te,xt,St,ae,Je,Qe,He,Ye,Wt,ft,ot,R,wt,yt,At,te,ye,Re,vt,Ze,Bt,It,Ot,nn,Nt,ke,gn,mn,jt,Hn,Bn,hn,Yt;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=L=>{let le=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,Se=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,je=L.tools?L.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...L,reasoning:le,toolCall:Se,tools:je}},g=L=>{o({type:"message",message:f(L)})},m=null,w={current:null},h=new Map,F=new Map,T={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},S=L=>{if(L==null)return null;try{return String(L)}catch{return null}},I=L=>{var le,Se,je,et,Ke;return S((Ke=(et=(je=(Se=(le=L.stepId)!=null?le:L.step_id)!=null?Se:L.step)!=null?je:L.parentId)!=null?et:L.flowStepId)!=null?Ke:L.flow_step_id)},v=L=>{var le,Se,je,et,Ke,Le,E;return S((E=(Le=(Ke=(et=(je=(Se=(le=L.callId)!=null?le:L.call_id)!=null?Se:L.requestId)!=null?je:L.request_id)!=null?et:L.toolCallId)!=null?Ke:L.tool_call_id)!=null?Le:L.stepId)!=null?E:L.step_id)},N=()=>m||(m={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},g(m),m),C=(L,le)=>{T.lastId=le,L&&T.byStep.set(L,le)},k=(L,le)=>{var Ke;let Se=(Ke=L.reasoningId)!=null?Ke:L.id,je=I(L);if(Se){let Le=String(Se);return C(je,Le),Le}if(je){let Le=T.byStep.get(je);if(Le)return T.lastId=Le,Le}if(T.lastId&&!le)return T.lastId;if(!le)return null;let et=`reason-${u()}`;return C(je,et),et},K=L=>{let le=h.get(L);if(le)return le;let Se={id:`reason-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:L,status:"streaming",chunks:[]}};return h.set(L,Se),g(Se),Se},J=(L,le)=>{y.lastId=le,L&&y.byCall.set(L,le)},z=(L,le)=>{var Ke;let Se=(Ke=L.toolId)!=null?Ke:L.id,je=v(L);if(Se){let Le=String(Se);return J(je,Le),Le}if(je){let Le=y.byCall.get(je);if(Le)return y.lastId=Le,Le}if(y.lastId&&!le)return y.lastId;if(!le)return null;let et=`tool-${u()}`;return J(je,et),et},_=L=>{let le=F.get(L);if(le)return le;let Se={id:`tool-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:L,status:"pending"}};return F.set(L,Se),g(Se),Se},j=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let le=Number(L);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let Se=Date.parse(L);if(!Number.isNaN(Se))return Se}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},H=new Map,V=new Map;for(;;){let{done:L,value:le}=await r.read();if(L)break;i+=s.decode(le,{stream:!0});let Se=i.split(`
5
5
 
6
6
  `);i=(Pe=Se.pop())!=null?Pe:"";for(let je of Se){let et=je.split(`
7
- `),Ke="message",Le="";for(let oe of et)oe.startsWith("event:")?Ke=oe.replace("event:","").trim():oe.startsWith("data:")&&(Le+=oe.replace("data:","").trim());if(!Le)continue;let M;try{M=JSON.parse(Le)}catch(oe){o({type:"error",error:oe instanceof Error?oe:new Error("Failed to parse chat stream payload")});continue}let bt=Ke!=="message"?Ke:(V=M.type)!=null?V:"message";if(this.parseSSEEvent){w.current=m;let oe=await this.handleCustomSSEEvent(M,o,w,g,u);if(w.current&&!m&&(m=w.current),oe)continue}if(bt==="reason_start"){let oe=(D=k(M,!0))!=null?D:`reason-${u()}`,B=K(oe);B.reasoning=(tt=B.reasoning)!=null?tt:{id:oe,status:"streaming",chunks:[]},B.reasoning.startedAt=(lt=B.reasoning.startedAt)!=null?lt:j((at=M.startedAt)!=null?at:M.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",g(B)}else if(bt==="reason_chunk"){let oe=(Ft=(Lt=k(M,!1))!=null?Lt:k(M,!0))!=null?Ft:`reason-${u()}`,B=K(oe);B.reasoning=(q=B.reasoning)!=null?q:{id:oe,status:"streaming",chunks:[]},B.reasoning.startedAt=(dt=B.reasoning.startedAt)!=null?dt:j((we=M.startedAt)!=null?we:M.timestamp);let E=(ut=(ze=(ct=M.reasoningText)!=null?ct:M.text)!=null?ze:M.delta)!=null?ut:"";if(E&&M.hidden!==!0&&B.reasoning.chunks.push(String(E)),B.reasoning.status=M.done?"complete":"streaming",M.done){B.reasoning.completedAt=j(($t=M.completedAt)!=null?$t:M.timestamp);let U=(Pt=B.reasoning.startedAt)!=null?Pt:Date.now();B.reasoning.durationMs=Math.max(0,((Ht=B.reasoning.completedAt)!=null?Ht:Date.now())-U)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(bt==="reason_complete"){let oe=(Ne=($=k(M,!1))!=null?$:k(M,!0))!=null?Ne:`reason-${u()}`,B=h.get(oe);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=j((me=M.completedAt)!=null?me:M.timestamp);let U=(nt=B.reasoning.startedAt)!=null?nt:Date.now();B.reasoning.durationMs=Math.max(0,((he=B.reasoning.completedAt)!=null?he:Date.now())-U),B.streaming=!1,g(B)}let E=I(M);E&&W.byStep.delete(E)}else if(bt==="tool_start"){let oe=(st=z(M,!0))!=null?st:`tool-${u()}`,B=_(oe),E=(Te=B.toolCall)!=null?Te:{id:oe,status:"pending"};E.name=(xt=M.toolName)!=null?xt:E.name,E.status="running",M.args!==void 0&&(E.args=M.args),E.startedAt=(ae=E.startedAt)!=null?ae:j((St=M.startedAt)!=null?St:M.timestamp),E.completedAt=void 0,E.durationMs=void 0,B.toolCall=E,B.streaming=!0,g(B)}else if(bt==="tool_chunk"){let oe=(Qe=(Je=z(M,!1))!=null?Je:z(M,!0))!=null?Qe:`tool-${u()}`,B=_(oe),E=(He=B.toolCall)!=null?He:{id:oe,status:"running"};E.startedAt=(Wt=E.startedAt)!=null?Wt:j((Ye=M.startedAt)!=null?Ye:M.timestamp);let U=(R=(ot=(ft=M.text)!=null?ft:M.delta)!=null?ot:M.message)!=null?R:"";U&&(E.chunks=(wt=E.chunks)!=null?wt:[],E.chunks.push(String(U))),E.status="running",B.toolCall=E,B.streaming=!0,g(B)}else if(bt==="tool_complete"){let oe=(At=(yt=z(M,!1))!=null?yt:z(M,!0))!=null?At:`tool-${u()}`,B=_(oe),E=(te=B.toolCall)!=null?te:{id:oe,status:"running"};if(E.status="complete",M.result!==void 0&&(E.result=M.result),typeof M.duration=="number"&&(E.duration=M.duration),E.completedAt=j((ye=M.completedAt)!=null?ye:M.timestamp),typeof M.duration=="number")E.durationMs=M.duration;else{let fe=(Re=E.startedAt)!=null?Re:Date.now();E.durationMs=Math.max(0,((vt=E.completedAt)!=null?vt:Date.now())-fe)}B.toolCall=E,B.streaming=!1,g(B);let U=v(M);U&&y.byCall.delete(U)}else if(bt==="step_chunk"){let oe=M.stepType,B=M.executionType;if(oe==="tool"||B==="context")continue;let E=N(),U=(Ot=(It=(Bt=(Ze=M.text)!=null?Ze:M.delta)!=null?Bt:M.content)!=null?It:M.chunk)!=null?Ot:"";if(U){let Me=((tn=X.get(E.id))!=null?tn:"")+U;E.rawContent=Me,H.has(E.id)||H.set(E.id,this.createStreamParser());let Xe=H.get(E.id),Ie=Me.trim().startsWith("{")||Me.trim().startsWith("[");if(Ie&&X.set(E.id,Me),Xe.__isPlainTextParser===!0){E.content+=U,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,g(E);continue}let We=Xe.processChunk(Me);if(We instanceof Promise)We.then(Ce=>{var Ve;let xe=typeof Ce=="string"?Ce:(Ve=Ce==null?void 0:Ce.text)!=null?Ve:null;if(xe!==null&&xe.trim()!==""){let ce=m;ce&&ce.id===E.id&&(ce.content=xe,g(ce))}else if(!Ie&&!Me.trim().startsWith("<")){let ce=m;ce&&ce.id===E.id&&(ce.content+=U,X.delete(ce.id),H.delete(ce.id),ce.rawContent=void 0,g(ce))}}).catch(()=>{E.content+=U,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,g(E)});else{let Ce=typeof We=="string"?We:(Nt=We==null?void 0:We.text)!=null?Nt:null;Ce!==null&&Ce.trim()!==""?(E.content=Ce,g(E)):!Ie&&!Me.trim().startsWith("<")&&(E.content+=U,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,g(E))}}if(M.isComplete){let fe=(pn=(ke=M.result)==null?void 0:ke.response)!=null?pn:E.content;if(fe){let Me=X.get(E.id),Xe=Me!=null?Me:Y(fe);E.rawContent=Xe;let Ie=H.get(E.id),De=null,We=!1;if(Ie&&(De=Ie.getExtractedText(),De===null&&(De=jn(Xe)),De===null)){let Ce=Ie.processChunk(Xe);Ce instanceof Promise?(We=!0,Ce.then(xe=>{var ce;let Ve=typeof xe=="string"?xe:(ce=xe==null?void 0:xe.text)!=null?ce:null;if(Ve!==null){let se=m;se&&se.id===E.id&&(se.content=Ve,se.streaming=!1,H.delete(se.id),X.delete(se.id),g(se))}})):De=typeof Ce=="string"?Ce:(gn=Ce==null?void 0:Ce.text)!=null?gn:null}if(!We){De!==null&&De.trim()!==""?E.content=De:X.has(E.id)||(E.content=Y(fe));let Ce=H.get(E.id);if(Ce){let xe=(jt=Ce.close)==null?void 0:jt.call(Ce);xe instanceof Promise&&xe.catch(()=>{}),H.delete(E.id)}X.delete(E.id),E.streaming=!1,g(E)}}}}else if(bt==="step_complete"){let oe=M.stepType,B=M.executionType;if(oe==="tool"||B==="context")continue;let E=(Pn=M.result)==null?void 0:Pn.response,U=N();if(E!=null){let fe=H.get(U.id),Me=!1,Xe=!1;if(fe){let Ie=fe.getExtractedText(),De=X.get(U.id),We=De!=null?De:Y(E);if(U.rawContent=We,Ie!==null&&Ie.trim()!=="")U.content=Ie,Me=!0;else{let Ce=jn(We);if(Ce!==null)U.content=Ce,Me=!0;else{let xe=fe.processChunk(We);if(xe instanceof Promise)Xe=!0,xe.then(Ve=>{var se;let ce=typeof Ve=="string"?Ve:(se=Ve==null?void 0:Ve.text)!=null?se:null;if(ce!==null&&ce.trim()!==""){let de=m;de&&de.id===U.id&&(de.content=ce,de.streaming=!1,H.delete(de.id),X.delete(de.id),g(de))}else{let de=fe.getExtractedText(),mt=m;mt&&mt.id===U.id&&(de!==null&&de.trim()!==""?mt.content=de:X.has(mt.id)||(mt.content=Y(E)),mt.streaming=!1,H.delete(mt.id),X.delete(mt.id),g(mt))}});else{let Ve=typeof xe=="string"?xe:(Hn=xe==null?void 0:xe.text)!=null?Hn:null;if(Ve!==null&&Ve.trim()!=="")U.content=Ve,Me=!0;else{let ce=fe.getExtractedText();ce!==null&&ce.trim()!==""&&(U.content=ce,Me=!0)}}}}}if(!Xe){if(!U.rawContent){let Ie=X.get(U.id);U.rawContent=Ie!=null?Ie:Y(E)}if(!Me&&!X.has(U.id)&&(U.content=Y(E)),fe){let Ie=(mn=fe.close)==null?void 0:mn.call(fe);Ie instanceof Promise&&Ie.catch(()=>{})}H.delete(U.id),X.delete(U.id),U.streaming=!1,g(U)}}else H.delete(U.id),X.delete(U.id),U.streaming=!1,g(U)}else if(bt==="flow_complete"){let oe=(Yt=M.result)==null?void 0:Yt.response;if(oe!=null){let B=N(),E=X.get(B.id),U=E!=null?E:Y(oe);B.rawContent=U;let fe=Y(oe),Me=H.get(B.id);if(Me){let De=jn(U);if(De!==null)fe=De;else{let We=Me.processChunk(U);We instanceof Promise&&We.then(xe=>{var ce;let Ve=typeof xe=="string"?xe:(ce=xe==null?void 0:xe.text)!=null?ce:null;if(Ve!==null){let se=m;se&&se.id===B.id&&(se.content=Ve,se.streaming=!1,g(se))}});let Ce=Me.getExtractedText();Ce!==null&&(fe=Ce)}}H.delete(B.id),X.delete(B.id);let Xe=fe!==B.content,Ie=B.streaming!==!1;Xe&&(B.content=fe),B.streaming=!1,(Xe||Ie)&&g(B)}else if(m!==null){let B=m;H.delete(B.id),X.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}o({type:"status",status:"idle"})}else bt==="error"&&M.error&&o({type:"error",error:M.error instanceof Error?M.error:new Error(String(M.error))})}}}};function $r(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function An(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function Tn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var nn=class{constructor(n={},o){this.config=n;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=n=>{var o,t;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Gt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var n,o;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(o=(n=this.callbacks).onError)==null||o.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,o){return this.client.submitMessageFeedback(n,o)}async submitCSATFeedback(n,o){return this.client.submitCSATFeedback(n,o)}async submitNPSFeedback(n,o){return this.client.submitNPSFeedback(n,o)}updateConfig(n){this.config={...this.config,...n},this.client=new Gt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:o,content:t,llmContent:r,contentParts:s,id:i,createdAt:a,sequence:d,streaming:u=!1}=n,g={id:i!=null?i:o==="user"?An():o==="assistant"?Tn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s}};return this.upsertMessage(g),g}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}async sendMessage(n,o){var u,f,g,m,w;let t=n.trim();if(!t&&(!(o!=null&&o.contentParts)||o.contentParts.length===0))return;(u=this.abortController)==null||u.abort();let r=An(),s=Tn(),i={id:r,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1,...(o==null?void 0:o.contentParts)&&o.contentParts.length>0&&{contentParts:o.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(h){let F={id:s,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(F),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h instanceof Error?(g=(f=this.callbacks).onError)==null||g.call(f,h):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(h)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let o=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let o=this.ensureSequence(n),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((o,t)=>{var d,u;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,a=(u=t.sequence)!=null?u:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var p=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var Ri=Mi(require("lucide"),1),re=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ri[r];return s?Fi(s,n,o,t):(console.warn(`Lucide icon "${e}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${e}":`,r),null}};function Fi(e,n,o,t){if(!e||!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(n)),r.setAttribute("height",String(n)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([u,f])=>{u!=="stroke"&&d.setAttribute(u,String(f))}),r.appendChild(d)}}}),r}function Or(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Nr(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function jr(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Dr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function zn(e){return{type:"text",text:e}}function _r(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function qr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;n({type:"image",image:r,mimeType:e.type,alt:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Ur(e,n=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var zr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],$i=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Jt=[...zr,...$i];function Oi(e){return zr.includes(e)||e.startsWith("image/")}function Jn(e){return Oi(e.type)}async function Jr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Jn(e)?n({type:"image",image:r,mimeType:e.type,alt:e.name}):n({type:"file",data:r,mimeType:e.type,filename:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Yr(e,n=Jt,o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ni(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Kr(e,n){let o=Ni(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var Yn={allowedTypes:Jt,maxFileSize:10*1024*1024,maxFiles:4};function ji(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Di(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Qt=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var o,t,r;this.config={allowedTypes:(o=n.allowedTypes)!=null?o:Yn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Yn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Yn.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Yn.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,r,s,i,a,d,u;if(!n||n.length===0)return;let o=Array.from(n);for(let f of o){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,f,"count");continue}let g=Yr(f,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let m=(s=g.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,m);continue}try{let m=await Jr(f),w=Jn(f)?URL.createObjectURL(f):null,h={id:ji(),file:f,previewUrl:w,contentPart:m};this.attachments.push(h),this.renderPreview(h)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(u=(d=this.config).onAttachmentsChange)==null||u.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let o=this.attachments.findIndex(d=>d.id===n);if(o===-1)return;let t=this.attachments[o];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(o,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,o;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(o=(n=this.config).onAttachmentsChange)==null||o.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let o=Jn(n.file),t=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",o&&n.previewUrl){let i=p("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=p("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Di(n.file.type),d=re(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=p("span");u.textContent=Kr(n.file.type,n.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--cw-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",i.appendChild(u),t.appendChild(i)}let r=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="rgba(0, 0, 0, 0.6)",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=re("x",10,"#ffffff",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="#ffffff",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(r),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,o){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:o})}};var gs=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},_i=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",o=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:o;return n==="light"?o:n==="dark"||gs()==="dark"?t:o},Xr=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(gs())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(gs());o.addEventListener?(o.addEventListener("change",t),n.push(()=>o.removeEventListener("change",t))):o.addListener&&(o.addListener(t),n.push(()=>o.removeListener(t)))}return()=>{n.forEach(o=>o())}},Kn=(e,n)=>{let o=_i(n);Object.entries(o).forEach(([t,r])=>{if(r==null||r==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(r))})};var Vr=require("idiomorph"),Gr=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;Vr.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&t&&r.classList.contains("tvw-animate-typing"))return!1}}})};var gt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var kt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Mn=(e,n)=>{let o=p("button");o.type="button",o.innerHTML=`
7
+ `),Ke="message",Le="";for(let oe of et)oe.startsWith("event:")?Ke=oe.replace("event:","").trim():oe.startsWith("data:")&&(Le+=oe.replace("data:","").trim());if(!Le)continue;let E;try{E=JSON.parse(Le)}catch(oe){o({type:"error",error:oe instanceof Error?oe:new Error("Failed to parse chat stream payload")});continue}let bt=Ke!=="message"?Ke:(X=E.type)!=null?X:"message";if(this.parseSSEEvent){w.current=m;let oe=await this.handleCustomSSEEvent(E,o,w,g,u);if(w.current&&!m&&(m=w.current),oe)continue}if(bt==="reason_start"){let oe=(D=k(E,!0))!=null?D:`reason-${u()}`,B=K(oe);B.reasoning=(tt=B.reasoning)!=null?tt:{id:oe,status:"streaming",chunks:[]},B.reasoning.startedAt=(lt=B.reasoning.startedAt)!=null?lt:j((at=E.startedAt)!=null?at:E.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",g(B)}else if(bt==="reason_chunk"){let oe=(Ft=(Lt=k(E,!1))!=null?Lt:k(E,!0))!=null?Ft:`reason-${u()}`,B=K(oe);B.reasoning=(q=B.reasoning)!=null?q:{id:oe,status:"streaming",chunks:[]},B.reasoning.startedAt=(dt=B.reasoning.startedAt)!=null?dt:j((we=E.startedAt)!=null?we:E.timestamp);let W=(ut=(ze=(ct=E.reasoningText)!=null?ct:E.text)!=null?ze:E.delta)!=null?ut:"";if(W&&E.hidden!==!0&&B.reasoning.chunks.push(String(W)),B.reasoning.status=E.done?"complete":"streaming",E.done){B.reasoning.completedAt=j(($t=E.completedAt)!=null?$t:E.timestamp);let U=(Pt=B.reasoning.startedAt)!=null?Pt:Date.now();B.reasoning.durationMs=Math.max(0,((Ht=B.reasoning.completedAt)!=null?Ht:Date.now())-U)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(bt==="reason_complete"){let oe=(Ne=($=k(E,!1))!=null?$:k(E,!0))!=null?Ne:`reason-${u()}`,B=h.get(oe);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=j((me=E.completedAt)!=null?me:E.timestamp);let U=(nt=B.reasoning.startedAt)!=null?nt:Date.now();B.reasoning.durationMs=Math.max(0,((he=B.reasoning.completedAt)!=null?he:Date.now())-U),B.streaming=!1,g(B)}let W=I(E);W&&T.byStep.delete(W)}else if(bt==="tool_start"){let oe=(st=z(E,!0))!=null?st:`tool-${u()}`,B=_(oe),W=(Te=B.toolCall)!=null?Te:{id:oe,status:"pending"};W.name=(xt=E.toolName)!=null?xt:W.name,W.status="running",E.args!==void 0&&(W.args=E.args),W.startedAt=(ae=W.startedAt)!=null?ae:j((St=E.startedAt)!=null?St:E.timestamp),W.completedAt=void 0,W.durationMs=void 0,B.toolCall=W,B.streaming=!0,g(B)}else if(bt==="tool_chunk"){let oe=(Qe=(Je=z(E,!1))!=null?Je:z(E,!0))!=null?Qe:`tool-${u()}`,B=_(oe),W=(He=B.toolCall)!=null?He:{id:oe,status:"running"};W.startedAt=(Wt=W.startedAt)!=null?Wt:j((Ye=E.startedAt)!=null?Ye:E.timestamp);let U=(R=(ot=(ft=E.text)!=null?ft:E.delta)!=null?ot:E.message)!=null?R:"";U&&(W.chunks=(wt=W.chunks)!=null?wt:[],W.chunks.push(String(U))),W.status="running",B.toolCall=W,B.streaming=!0,g(B)}else if(bt==="tool_complete"){let oe=(At=(yt=z(E,!1))!=null?yt:z(E,!0))!=null?At:`tool-${u()}`,B=_(oe),W=(te=B.toolCall)!=null?te:{id:oe,status:"running"};if(W.status="complete",E.result!==void 0&&(W.result=E.result),typeof E.duration=="number"&&(W.duration=E.duration),W.completedAt=j((ye=E.completedAt)!=null?ye:E.timestamp),typeof E.duration=="number")W.durationMs=E.duration;else{let fe=(Re=W.startedAt)!=null?Re:Date.now();W.durationMs=Math.max(0,((vt=W.completedAt)!=null?vt:Date.now())-fe)}B.toolCall=W,B.streaming=!1,g(B);let U=v(E);U&&y.byCall.delete(U)}else if(bt==="step_chunk"){let oe=E.stepType,B=E.executionType;if(oe==="tool"||B==="context")continue;let W=N(),U=(Ot=(It=(Bt=(Ze=E.text)!=null?Ze:E.delta)!=null?Bt:E.content)!=null?It:E.chunk)!=null?Ot:"";if(U){let Me=((nn=V.get(W.id))!=null?nn:"")+U;W.rawContent=Me,H.has(W.id)||H.set(W.id,this.createStreamParser());let Ve=H.get(W.id),Ie=Me.trim().startsWith("{")||Me.trim().startsWith("[");if(Ie&&V.set(W.id,Me),Ve.__isPlainTextParser===!0){W.content+=U,V.delete(W.id),H.delete(W.id),W.rawContent=void 0,g(W);continue}let We=Ve.processChunk(Me);if(We instanceof Promise)We.then(Ce=>{var Xe;let xe=typeof Ce=="string"?Ce:(Xe=Ce==null?void 0:Ce.text)!=null?Xe:null;if(xe!==null&&xe.trim()!==""){let ce=m;ce&&ce.id===W.id&&(ce.content=xe,g(ce))}else if(!Ie&&!Me.trim().startsWith("<")){let ce=m;ce&&ce.id===W.id&&(ce.content+=U,V.delete(ce.id),H.delete(ce.id),ce.rawContent=void 0,g(ce))}}).catch(()=>{W.content+=U,V.delete(W.id),H.delete(W.id),W.rawContent=void 0,g(W)});else{let Ce=typeof We=="string"?We:(Nt=We==null?void 0:We.text)!=null?Nt:null;Ce!==null&&Ce.trim()!==""?(W.content=Ce,g(W)):!Ie&&!Me.trim().startsWith("<")&&(W.content+=U,V.delete(W.id),H.delete(W.id),W.rawContent=void 0,g(W))}}if(E.isComplete){let fe=(gn=(ke=E.result)==null?void 0:ke.response)!=null?gn:W.content;if(fe){let Me=V.get(W.id),Ve=Me!=null?Me:Y(fe);W.rawContent=Ve;let Ie=H.get(W.id),De=null,We=!1;if(Ie&&(De=Ie.getExtractedText(),De===null&&(De=Dn(Ve)),De===null)){let Ce=Ie.processChunk(Ve);Ce instanceof Promise?(We=!0,Ce.then(xe=>{var ce;let Xe=typeof xe=="string"?xe:(ce=xe==null?void 0:xe.text)!=null?ce:null;if(Xe!==null){let se=m;se&&se.id===W.id&&(se.content=Xe,se.streaming=!1,H.delete(se.id),V.delete(se.id),g(se))}})):De=typeof Ce=="string"?Ce:(mn=Ce==null?void 0:Ce.text)!=null?mn:null}if(!We){De!==null&&De.trim()!==""?W.content=De:V.has(W.id)||(W.content=Y(fe));let Ce=H.get(W.id);if(Ce){let xe=(jt=Ce.close)==null?void 0:jt.call(Ce);xe instanceof Promise&&xe.catch(()=>{}),H.delete(W.id)}V.delete(W.id),W.streaming=!1,g(W)}}}}else if(bt==="step_complete"){let oe=E.stepType,B=E.executionType;if(oe==="tool"||B==="context")continue;let W=(Hn=E.result)==null?void 0:Hn.response,U=N();if(W!=null){let fe=H.get(U.id),Me=!1,Ve=!1;if(fe){let Ie=fe.getExtractedText(),De=V.get(U.id),We=De!=null?De:Y(W);if(U.rawContent=We,Ie!==null&&Ie.trim()!=="")U.content=Ie,Me=!0;else{let Ce=Dn(We);if(Ce!==null)U.content=Ce,Me=!0;else{let xe=fe.processChunk(We);if(xe instanceof Promise)Ve=!0,xe.then(Xe=>{var se;let ce=typeof Xe=="string"?Xe:(se=Xe==null?void 0:Xe.text)!=null?se:null;if(ce!==null&&ce.trim()!==""){let de=m;de&&de.id===U.id&&(de.content=ce,de.streaming=!1,H.delete(de.id),V.delete(de.id),g(de))}else{let de=fe.getExtractedText(),mt=m;mt&&mt.id===U.id&&(de!==null&&de.trim()!==""?mt.content=de:V.has(mt.id)||(mt.content=Y(W)),mt.streaming=!1,H.delete(mt.id),V.delete(mt.id),g(mt))}});else{let Xe=typeof xe=="string"?xe:(Bn=xe==null?void 0:xe.text)!=null?Bn:null;if(Xe!==null&&Xe.trim()!=="")U.content=Xe,Me=!0;else{let ce=fe.getExtractedText();ce!==null&&ce.trim()!==""&&(U.content=ce,Me=!0)}}}}}if(!Ve){if(!U.rawContent){let Ie=V.get(U.id);U.rawContent=Ie!=null?Ie:Y(W)}if(!Me&&!V.has(U.id)&&(U.content=Y(W)),fe){let Ie=(hn=fe.close)==null?void 0:hn.call(fe);Ie instanceof Promise&&Ie.catch(()=>{})}H.delete(U.id),V.delete(U.id),U.streaming=!1,g(U)}}else H.delete(U.id),V.delete(U.id),U.streaming=!1,g(U)}else if(bt==="flow_complete"){let oe=(Yt=E.result)==null?void 0:Yt.response;if(oe!=null){let B=N(),W=V.get(B.id),U=W!=null?W:Y(oe);B.rawContent=U;let fe=Y(oe),Me=H.get(B.id);if(Me){let De=Dn(U);if(De!==null)fe=De;else{let We=Me.processChunk(U);We instanceof Promise&&We.then(xe=>{var ce;let Xe=typeof xe=="string"?xe:(ce=xe==null?void 0:xe.text)!=null?ce:null;if(Xe!==null){let se=m;se&&se.id===B.id&&(se.content=Xe,se.streaming=!1,g(se))}});let Ce=Me.getExtractedText();Ce!==null&&(fe=Ce)}}H.delete(B.id),V.delete(B.id);let Ve=fe!==B.content,Ie=B.streaming!==!1;Ve&&(B.content=fe),B.streaming=!1,(Ve||Ie)&&g(B)}else if(m!==null){let B=m;H.delete(B.id),V.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}o({type:"status",status:"idle"})}else bt==="error"&&E.error&&o({type:"error",error:E.error instanceof Error?E.error:new Error(String(E.error))})}}}};function Or(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Tn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function Mn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var sn=class{constructor(n={},o){this.config=n;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=n=>{var o,t;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Gt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var n,o;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(o=(n=this.callbacks).onError)==null||o.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,o){return this.client.submitMessageFeedback(n,o)}async submitCSATFeedback(n,o){return this.client.submitCSATFeedback(n,o)}async submitNPSFeedback(n,o){return this.client.submitNPSFeedback(n,o)}updateConfig(n){this.config={...this.config,...n},this.client=new Gt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:o,content:t,llmContent:r,contentParts:s,id:i,createdAt:a,sequence:d,streaming:u=!1}=n,g={id:i!=null?i:o==="user"?Tn():o==="assistant"?Mn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s}};return this.upsertMessage(g),g}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}async sendMessage(n,o){var u,f,g,m,w;let t=n.trim();if(!t&&(!(o!=null&&o.contentParts)||o.contentParts.length===0))return;(u=this.abortController)==null||u.abort();let r=Tn(),s=Mn(),i={id:r,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1,...(o==null?void 0:o.contentParts)&&o.contentParts.length>0&&{contentParts:o.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(h){let F={id:s,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(F),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h instanceof Error?(g=(f=this.callbacks).onError)==null||g.call(f,h):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(h)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let o=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let o=this.ensureSequence(n),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((o,t)=>{var d,u;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,a=(u=t.sequence)!=null?u:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var p=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var $i=Wi(require("lucide"),1),re=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=$i[r];return s?Oi(s,n,o,t):(console.warn(`Lucide icon "${e}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${e}":`,r),null}};function Oi(e,n,o,t){if(!e||!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(n)),r.setAttribute("height",String(n)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([u,f])=>{u!=="stroke"&&d.setAttribute(u,String(f))}),r.appendChild(d)}}}),r}function Nr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function jr(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Dr(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function _r(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Jn(e){return{type:"text",text:e}}function qr(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Ur(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;n({type:"image",image:r,mimeType:e.type,alt:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function zr(e,n=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Jr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ni=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Jt=[...Jr,...Ni];function ji(e){return Jr.includes(e)||e.startsWith("image/")}function Yn(e){return ji(e.type)}async function Yr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Yn(e)?n({type:"image",image:r,mimeType:e.type,alt:e.name}):n({type:"file",data:r,mimeType:e.type,filename:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Kr(e,n=Jt,o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Di(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Vr(e,n){let o=Di(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var Kn={allowedTypes:Jt,maxFileSize:10*1024*1024,maxFiles:4};function _i(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function qi(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Qt=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var o,t,r;this.config={allowedTypes:(o=n.allowedTypes)!=null?o:Kn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Kn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Kn.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Kn.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,r,s,i,a,d,u;if(!n||n.length===0)return;let o=Array.from(n);for(let f of o){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,f,"count");continue}let g=Kr(f,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let m=(s=g.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,m);continue}try{let m=await Yr(f),w=Yn(f)?URL.createObjectURL(f):null,h={id:_i(),file:f,previewUrl:w,contentPart:m};this.attachments.push(h),this.renderPreview(h)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(u=(d=this.config).onAttachmentsChange)==null||u.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let o=this.attachments.findIndex(d=>d.id===n);if(o===-1)return;let t=this.attachments[o];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(o,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,o;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(o=(n=this.config).onAttachmentsChange)==null||o.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let o=Yn(n.file),t=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",o&&n.previewUrl){let i=p("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=p("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=qi(n.file.type),d=re(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=p("span");u.textContent=Vr(n.file.type,n.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--cw-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",i.appendChild(u),t.appendChild(i)}let r=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="rgba(0, 0, 0, 0.6)",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=re("x",10,"#ffffff",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="#ffffff",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(r),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,o){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:o})}};var ms=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ui=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",o=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:o;return n==="light"?o:n==="dark"||ms()==="dark"?t:o},Xr=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(ms())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(ms());o.addEventListener?(o.addEventListener("change",t),n.push(()=>o.removeEventListener("change",t))):o.addListener&&(o.addListener(t),n.push(()=>o.removeListener(t)))}return()=>{n.forEach(o=>o())}},Vn=(e,n)=>{let o=Ui(n);Object.entries(o).forEach(([t,r])=>{if(r==null||r==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(r))})};var Gr=require("idiomorph"),Qr=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;Gr.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&t&&r.classList.contains("tvw-animate-typing"))return!1}}})};var gt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var kt={"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 En=(e,n)=>{let o=p("button");o.type="button",o.innerHTML=`
8
8
  <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
10
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -12,12 +12,12 @@
12
12
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,o.addEventListener("click",n);let t=s=>{var y,S,I,v,N,C,k,K,J,z,_,j;let i=(y=s.launcher)!=null?y:{},a=o.querySelector("[data-role='launcher-title']");a&&(a.textContent=(S=i.title)!=null?S:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(I=i.subtitle)!=null?I:"Get answers fast");let u=o.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let f=o.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let Y=(v=i.agentIconSize)!=null?v:"40px";if(f.style.height=Y,f.style.width=Y,f.innerHTML="",i.agentIconName){let H=parseFloat(Y)||24,X=re(i.agentIconName,H*.6,"#ffffff",2);X?(f.appendChild(X),f.style.display=""):(f.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(C=i.agentIconText)!=null?C:"\u{1F4AC}",f.style.display="")}let g=o.querySelector("[data-role='launcher-image']");if(g){let Y=(k=i.agentIconSize)!=null?k:"40px";g.style.height=Y,g.style.width=Y,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(g.src=i.iconUrl,g.style.display="block"):g.style.display="none"}let m=o.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Y=(K=i.callToActionIconSize)!=null?K:"32px";m.style.height=Y,m.style.width=Y,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 H=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,H=(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 X=parseFloat(Y)||24,Pe=Math.max(X-H,8),V=re(i.callToActionIconName,Pe,"currentColor",2);V?m.appendChild(V):m.textContent=(J=i.callToActionIconText)!=null?J:"\u2197"}else m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}let w=i.position&&kt[i.position]?kt[i.position]:kt["bottom-right"],h="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${h} ${w}`;let F="1px solid #e5e7eb",W="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(_=i.border)!=null?_:F,o.style.boxShadow=(j=i.shadow)!=null?j:W},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var qt=e=>{var z,_,j,Y,H,X,Pe,V,D,tt,at,lt,Lt,Ft,q,we,dt,ct,ze,ut,$t,Pt,Ht,$,Ne,me,nt,he,st,Te,xt,St;let{config:n,showClose:o=!0}=e,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(z=n==null?void 0:n.launcher)!=null?z:{},s=(_=r.headerIconSize)!=null?_:"48px",i=(j=r.closeButtonSize)!=null?j:"32px",a=(Y=r.closeButtonPlacement)!=null?Y:"inline",d=(H=r.headerIconHidden)!=null?H:!1,u=r.headerIconName,f=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=s,f.style.width=s,!d)if(u){let ae=parseFloat(s)||24,Je=re(u,ae*.6,"#ffffff",2);Je?f.replaceChildren(Je):f.textContent=(Pe=(X=n==null?void 0:n.launcher)==null?void 0:X.agentIconText)!=null?Pe:"\u{1F4AC}"}else if((V=n==null?void 0:n.launcher)!=null&&V.iconUrl){let ae=p("img");ae.src=n.launcher.iconUrl,ae.alt="",ae.className="tvw-rounded-xl tvw-object-cover",ae.style.height=s,ae.style.width=s,f.replaceChildren(ae)}else f.textContent=(tt=(D=n==null?void 0:n.launcher)==null?void 0:D.agentIconText)!=null?tt:"\u{1F4AC}";let g=p("div","tvw-flex tvw-flex-col"),m=p("span","tvw-text-base tvw-font-semibold");m.textContent=(lt=(at=n==null?void 0:n.launcher)==null?void 0:at.title)!=null?lt:"Chat Assistant";let w=p("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(Ft=(Lt=n==null?void 0:n.launcher)==null?void 0:Lt.subtitle)!=null?Ft:"Here to help you get answers fast",g.append(m,w),d?t.append(g):t.append(f,g);let h=(q=r.clearChat)!=null?q:{},F=(we=h.enabled)!=null?we:!0,W=(dt=h.placement)!=null?dt:"inline",y=null,S=null;if(F){let ae=(ct=h.size)!=null?ct:"32px",Je=(ze=h.iconName)!=null?ze:"refresh-cw",Qe=(ut=h.iconColor)!=null?ut:"",He=($t=h.backgroundColor)!=null?$t:"",Ye=(Pt=h.borderWidth)!=null?Pt:"",Wt=(Ht=h.borderColor)!=null?Ht:"",ft=($=h.borderRadius)!=null?$:"",ot=(Ne=h.paddingX)!=null?Ne:"",R=(me=h.paddingY)!=null?me:"",wt=(nt=h.tooltipText)!=null?nt:"Clear chat",yt=(he=h.showTooltip)!=null?he:!0;S=p("div",W==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),W==="top-right"&&(S.style.right="48px"),y=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"),y.style.height=ae,y.style.width=ae,y.type="button",y.setAttribute("aria-label",wt);let At=re(Je,"20px",Qe||"",2);if(At&&y.appendChild(At),Qe&&(y.style.color=Qe,y.classList.remove("tvw-text-cw-muted")),He&&(y.style.backgroundColor=He,y.classList.remove("hover:tvw-bg-gray-100")),Ye||Wt){let te=Ye||"0px",ye=Wt||"transparent";y.style.border=`${te} solid ${ye}`,y.classList.remove("tvw-border-none")}if(ft&&(y.style.borderRadius=ft,y.classList.remove("tvw-rounded-full")),ot?(y.style.paddingLeft=ot,y.style.paddingRight=ot):(y.style.paddingLeft="",y.style.paddingRight=""),R?(y.style.paddingTop=R,y.style.paddingBottom=R):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),yt&&wt&&y&&S){let te=null,ye=()=>{if(te||!y)return;te=p("div","tvw-clear-chat-tooltip"),te.textContent=wt;let vt=p("div");vt.className="tvw-clear-chat-tooltip-arrow",te.appendChild(vt);let Ze=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${Ze.left+Ze.width/2}px`,te.style.top=`${Ze.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Re=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};S.addEventListener("mouseenter",ye),S.addEventListener("mouseleave",Re),y.addEventListener("focus",ye),y.addEventListener("blur",Re),S._cleanupTooltip=()=>{Re(),S&&(S.removeEventListener("mouseenter",ye),S.removeEventListener("mouseleave",Re)),y&&(y.removeEventListener("focus",ye),y.removeEventListener("blur",Re))}}W==="inline"&&t.appendChild(S)}let I=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":F&&W==="inline"?"":"tvw-ml-auto"),v=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");v.style.height=i,v.style.width=i,v.type="button";let N=(st=r.closeButtonTooltipText)!=null?st:"Close chat",C=(Te=r.closeButtonShowTooltip)!=null?Te:!0;v.setAttribute("aria-label",N),v.style.display=o?"":"none";let k=(xt=r.closeButtonIconName)!=null?xt:"x",K=(St=r.closeButtonIconText)!=null?St:"\xD7",J=re(k,"20px",r.closeButtonColor||"",2);if(J?v.appendChild(J):v.textContent=K,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let ae=r.closeButtonBorderWidth||"0px",Je=r.closeButtonBorderColor||"transparent";v.style.border=`${ae} solid ${Je}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),I.appendChild(v),C&&N){let ae=null,Je=()=>{if(ae)return;ae=p("div","tvw-clear-chat-tooltip"),ae.textContent=N;let He=p("div");He.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(He);let Ye=v.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Ye.left+Ye.width/2}px`,ae.style.top=`${Ye.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},Qe=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};I.addEventListener("mouseenter",Je),I.addEventListener("mouseleave",Qe),v.addEventListener("focus",Je),v.addEventListener("blur",Qe),I._cleanupTooltip=()=>{Qe(),I.removeEventListener("mouseenter",Je),I.removeEventListener("mouseleave",Qe),v.removeEventListener("focus",Je),v.removeEventListener("blur",Qe)}}return a!=="top-right"&&t.appendChild(I),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:v,closeButtonWrapper:I,clearChatButton:y,clearChatButtonWrapper:S}},Zt=(e,n,o)=>{var i,a,d,u;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"inline";e.appendChild(n.header),r==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var ms=e=>qt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),hs=e=>{var h,F,W,y;let{config:n,showClose:o=!0,onClose:t}=e,r=(h=n==null?void 0:n.launcher)!=null?h:{},s=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(F=r.title)!=null?F:"Chat Assistant",s.appendChild(i);let a=(W=r.closeButtonSize)!=null?W:"32px",d=p("div",""),u=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");u.style.height=a,u.style.width=a,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=o?"":"none";let f=(y=r.closeButtonIconName)!=null?y:"x",g=re(f,"20px",r.closeButtonColor||"",2);g?u.appendChild(g):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),s.appendChild(d);let m=p("div");m.style.display="none";let w=p("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},fs=e=>{var v,N,C,k,K,J,z,_;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(v=n==null?void 0:n.launcher)!=null?v:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=p("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=s.headerIconSize)!=null?N:"56px",u=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");u.style.height=d,u.style.width=d;let f=s.headerIconName;if(f){let j=parseFloat(d)||24,Y=re(f,j*.5,"#ffffff",2);Y?u.replaceChildren(Y):u.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let j=p("img");j.src=s.iconUrl,j.alt="",j.className="tvw-rounded-xl tvw-object-cover",j.style.height=d,j.style.width=d,u.replaceChildren(j)}else u.textContent=(k=s.agentIconText)!=null?k:"\u{1F4AC}";let g=p("div","tvw-flex tvw-flex-col tvw-flex-1"),m=p("span","tvw-text-lg tvw-font-semibold");m.textContent=(K=s.title)!=null?K:"Chat Assistant";let w=p("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(J=s.subtitle)!=null?J:"Here to help you get answers fast",g.append(m,w),a.append(u,g);let h=(z=s.closeButtonSize)!=null?z:"32px",F=p("div",""),W=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");W.style.height=h,W.style.width=h,W.type="button",W.setAttribute("aria-label","Close chat"),W.style.display=o?"":"none";let y=(_=s.closeButtonIconName)!=null?_:"x",S=re(y,"20px",s.closeButtonColor||"",2);S?W.appendChild(S):W.textContent="\xD7",t&&W.addEventListener("click",t),F.appendChild(W),a.appendChild(F),i.appendChild(a);let I=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return I.textContent="Online and ready to help",i.appendChild(I),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:W,closeButtonWrapper:F,clearChatButton:null,clearChatButtonWrapper:null}},Xn={default:ms,minimal:hs,expanded:fs},ws=e=>{var n;return(n=Xn[e])!=null?n:Xn.default},sn=(e,n,o)=>{var i,a,d;if(n!=null&&n.render){let u=n.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=p("div");f.style.display="none";let g=p("span"),m=p("span"),w=p("button");w.style.display="none";let h=p("div");return h.style.display="none",{header:u,iconHolder:f,headerTitle:g,headerSubtitle:m,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=ws(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var qi=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},on=e=>{var q,we,dt,ct,ze,ut,$t,Pt,Ht,$,Ne,me,nt,he,st,Te,xt,St,ae,Je,Qe,He,Ye,Wt,ft,ot,R,wt,yt,At;let{config:n}=e,o=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=p("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");r.style.outline="none";let s=p("textarea");s.placeholder=(we=(q=n==null?void 0:n.copy)==null?void 0:q.inputPlaceholder)!=null?we:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",s.rows=1;let i=(ct=(dt=n==null?void 0:n.theme)==null?void 0:dt.inputFontFamily)!=null?ct:"sans-serif",a=(ut=(ze=n==null?void 0:n.theme)==null?void 0:ze.inputFontWeight)!=null?ut:"400";s.style.fontFamily=qi(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let g=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",g),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=($t=n==null?void 0:n.sendButton)!=null?$t:{},w=(Pt=m.useIcon)!=null?Pt:!1,h=(Ht=m.iconText)!=null?Ht:"\u2191",F=m.iconName,W=($=m.tooltipText)!=null?$:"Send message",y=(Ne=m.showTooltip)!=null?Ne:!1,S=(me=m.size)!=null?me:"40px",I=m.backgroundColor,v=m.textColor,N=p("div","tvw-send-button-wrapper"),C=p("button",w?"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(C.type="submit",w){if(C.style.width=S,C.style.height=S,C.style.minWidth=S,C.style.minHeight=S,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",F){let te=parseFloat(S)||24,ye=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Re=re(F,te,ye,2);Re?(C.appendChild(Re),C.style.color=ye):(C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white"))}else C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white");I?C.style.backgroundColor=I:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(he=(nt=n==null?void 0:n.copy)==null?void 0:nt.sendButtonLabel)!=null?he:"Send",v?C.style.color=v:C.classList.add("tvw-text-white");if(m.borderWidth&&(C.style.borderWidth=m.borderWidth,C.style.borderStyle="solid"),m.borderColor&&(C.style.borderColor=m.borderColor),m.paddingX?(C.style.paddingLeft=m.paddingX,C.style.paddingRight=m.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),m.paddingY?(C.style.paddingTop=m.paddingY,C.style.paddingBottom=m.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),y&&W){let te=p("div","tvw-send-button-tooltip");te.textContent=W,N.appendChild(te)}N.appendChild(C);let k=(st=n==null?void 0:n.voiceRecognition)!=null?st:{},K=k.enabled===!0,J=null,z=null,_=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(K&&_){z=p("div","tvw-send-button-wrapper"),J=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),J.type="button",J.setAttribute("aria-label","Start voice recognition");let te=(Te=k.iconName)!=null?Te:"mic",ye=(xt=k.iconSize)!=null?xt:S,Re=parseFloat(ye)||24,vt=(St=k.backgroundColor)!=null?St:I,Ze=(ae=k.iconColor)!=null?ae:v;J.style.width=ye,J.style.height=ye,J.style.minWidth=ye,J.style.minHeight=ye,J.style.fontSize="18px",J.style.lineHeight="1";let Bt=Ze||"currentColor",It=re(te,Re,Bt,1.5);It?(J.appendChild(It),J.style.color=Bt):(J.textContent="\u{1F3A4}",J.style.color=Bt),vt?J.style.backgroundColor=vt:J.classList.add("tvw-bg-cw-primary"),Ze?J.style.color=Ze:!Ze&&!v&&J.classList.add("tvw-text-white"),k.borderWidth&&(J.style.borderWidth=k.borderWidth,J.style.borderStyle="solid"),k.borderColor&&(J.style.borderColor=k.borderColor),k.paddingX&&(J.style.paddingLeft=k.paddingX,J.style.paddingRight=k.paddingX),k.paddingY&&(J.style.paddingTop=k.paddingY,J.style.paddingBottom=k.paddingY),z.appendChild(J);let Ot=(Je=k.tooltipText)!=null?Je:"Start voice recognition";if(((Qe=k.showTooltip)!=null?Qe:!1)&&Ot){let Nt=p("div","tvw-send-button-tooltip");Nt.textContent=Ot,z.appendChild(Nt)}}let j=(He=n==null?void 0:n.attachments)!=null?He:{},Y=j.enabled===!0,H=null,X=null,Pe=null,V=null;if(Y){V=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),V.style.display="none",Pe=p("input"),Pe.type="file",Pe.accept=((Ye=j.allowedTypes)!=null?Ye:Jt).join(","),Pe.multiple=((Wt=j.maxFiles)!=null?Wt:4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),X=p("div","tvw-send-button-wrapper"),H=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),H.type="button",H.setAttribute("aria-label",(ft=j.buttonTooltipText)!=null?ft:"Attach file");let te=(ot=j.buttonIconName)!=null?ot:"paperclip",ye=S,Re=parseFloat(ye)||40,vt=Math.round(Re*.6);H.style.width=ye,H.style.height=ye,H.style.minWidth=ye,H.style.minHeight=ye,H.style.fontSize="18px",H.style.lineHeight="1",H.style.backgroundColor="transparent",H.style.color="var(--cw-primary, #111827)",H.style.border="none",H.style.borderRadius="6px",H.style.transition="background-color 0.15s ease",H.addEventListener("mouseenter",()=>{H.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),H.addEventListener("mouseleave",()=>{H.style.backgroundColor="transparent"});let Ze=re(te,vt,"currentColor",1.5);Ze?H.appendChild(Ze):H.textContent="\u{1F4CE}",H.addEventListener("click",Ot=>{Ot.preventDefault(),Pe==null||Pe.click()}),X.appendChild(H);let Bt=(R=j.buttonTooltipText)!=null?R:"Attach file",It=p("div","tvw-send-button-tooltip");It.textContent=Bt,X.appendChild(It)}r.addEventListener("click",te=>{te.target!==C&&te.target!==N&&te.target!==J&&te.target!==z&&te.target!==H&&te.target!==X&&s.focus()}),V&&(V.style.gap="8px",r.append(V)),Pe&&r.append(Pe),r.append(s);let D=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),tt=p("div","tvw-flex tvw-items-center tvw-gap-2");X&&tt.append(X);let at=p("div","tvw-flex tvw-items-center tvw-gap-1");z&&at.append(z),at.append(N),D.append(tt,at),r.append(D);let lt=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Lt=(wt=n==null?void 0:n.statusIndicator)!=null?wt:{},Ft=(yt=Lt.visible)!=null?yt:!0;return lt.style.display=Ft?"":"none",lt.textContent=(At=Lt.idleText)!=null?At:"Online",o.append(t,r,lt),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:N,micButton:J,micButtonWrapper:z,statusText:lt,attachmentButton:H,attachmentButtonWrapper:X,attachmentInput:Pe,attachmentPreviewsContainer:V,actionsRow:D,leftActions:tt,rightActions:at}};var Qr=e=>{var d,u,f,g,m,w,h;if(!((u=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?u:!0)){let F=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),W=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?g:"100%";return F.style.width=y,W.style.width="100%",F.appendChild(W),{wrapper:F,panel:W}}let o=(m=e==null?void 0:e.launcher)!=null?m:{},t=o.position&&kt[o.position]?kt[o.position]:kt["bottom-right"],r=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(h=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?h:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,r.appendChild(s),{wrapper:r,panel:s}},Zr=(e,n=!0)=>{var w,h,F,W,y,S,I;let o=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=e==null?void 0:e.layout)==null?void 0:w.header,r=((h=e==null?void 0:e.layout)==null?void 0:h.showHeader)!==!1,s=t?sn(e,t,{showClose:n}):qt({config:e,showClose:n}),i=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(W=(F=e==null?void 0:e.copy)==null?void 0:F.welcomeTitle)!=null?W:"Hello \u{1F44B}";let u=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",a.append(d,u);let f=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let g=on({config:e}),m=((I=e==null?void 0:e.layout)==null?void 0:I.showFooter)!==!1;return r?Zt(o,s,e):(s.header.style.display="none",Zt(o,s,e)),o.append(i),m||(g.footer.style.display="none"),o.append(g.footer),{container:o,body:i,messagesWrapper:f,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:u,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions}};var En=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",e.appendChild(n),e.appendChild(o),e.appendChild(t),e.appendChild(r),e},Ui=(e,n)=>{let o=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=p("img");r.src=t,r.alt=n==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=n==="user"?"U":"A",o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},ei=(e,n)=>{let o=p("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?o.textContent=n.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},zi=(e,n="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return o},ys=(e,n,o)=>{var h,F,W,y,S,I;let t=(h=n.showCopy)!=null?h:!0,r=(F=n.showUpvote)!=null?F:!0,s=(W=n.showDownvote)!=null?W:!0,i=(y=n.visibility)!=null?y:"hover",a=(S=n.align)!=null?S:"right",d=(I=n.layout)!=null?I:"pill-inside",u={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],g=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let m=null,w=(v,N,C,k)=>{let K=document.createElement("button");K.className="tvw-message-action-btn",K.setAttribute("aria-label",N),K.setAttribute("title",N),k&&K.setAttribute("data-action",k);let J=re(v,14,"currentColor",2);return J&&K.appendChild(J),K.addEventListener("click",z=>{z.preventDefault(),z.stopPropagation(),C()}),K};if(t){let v=w("copy","Copy message",()=>{let N=e.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let C=re("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=re("copy",14,"currentColor",2);k&&(v.innerHTML="",v.appendChild(k))},2e3)}).catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",C)}),o!=null&&o.onCopy&&o.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");g.appendChild(v)}if(r){let v=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=g.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),m="upvote",v.classList.add("tvw-message-action-active");let k={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"upvote");g.appendChild(v)}if(s){let v=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=g.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),m="downvote",v.classList.add("tvw-message-action-active");let k={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"downvote");g.appendChild(v)}return g},rn=(e,n,o,t,r)=>{var I,v,N,C,k;let s=o!=null?o:{},i=(I=s.layout)!=null?I:"bubble",a=s.avatar,d=s.timestamp,u=(v=a==null?void 0:a.show)!=null?v:!1,f=(N=d==null?void 0:d.show)!=null?N:!1,g=(C=a==null?void 0:a.position)!=null?C:"left",m=(k=d==null?void 0:d.position)!=null?k:"below",w=zi(e.role,i),h=p("div",w.join(" "));h.id=`bubble-${e.id}`,h.setAttribute("data-message-id",e.id);let F=document.createElement("div");if(F.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),f&&m==="inline"&&e.createdAt){let K=ei(e,d);K.classList.add("tvw-ml-2","tvw-inline"),F.appendChild(K)}if(h.appendChild(F),f&&m==="below"&&e.createdAt){let K=ei(e,d);K.classList.add("tvw-mt-1"),h.appendChild(K)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let K=En();h.appendChild(K)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let K=ys(e,t,r);h.appendChild(K)}if(!u||e.role==="system")return h;let y=p("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),S=Ui(a,e.role);return g==="right"||g==="left"&&e.role==="user"?y.append(h,S):y.append(S,h),h.classList.remove("tvw-max-w-[85%]"),h.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},ti=(e,n,o,t,r)=>{let s=o!=null?o:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):rn(e,n,o,t,r)};var an=new Set,ni=(e,n)=>{let o=an.has(e),t=n.querySelector('button[data-expand-header="true"]'),r=n.querySelector(".tvw-border-t");if(!t||!r)return;t.setAttribute("aria-expanded",o?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=re(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},vs=e=>{let n=e.reasoning,o=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let t=an.has(e.id),r=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("data-expand-header","true"),r.setAttribute("data-bubble-type","reasoning");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=p("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Hr(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),f=re(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let g=p("div","tvw-flex tvw-items-center tvw-ml-auto");g.append(d),r.append(s,g);let m=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let w=n.chunks.join(""),h=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return h.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(h),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=re(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),o.append(r,m),o};var ln=new Set,si=(e,n,o)=>{var u;let t=ln.has(e),r=(u=o==null?void 0:o.toolCall)!=null?u:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",t?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let f=r.toggleTextColor||r.headerTextColor||"currentColor",g=re(t?"chevron-up":"chevron-down",16,f,2);g?d.appendChild(g):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},bs=(e,n)=>{var F;let o=e.toolCall,t=(F=n==null?void 0:n.toolCall)!=null?F:{},r=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!o)return r;let s=ln.has(e.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=p("div","tvw-flex tvw-flex-col tvw-text-left"),d=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Br(o),a.appendChild(d);let u=p("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",g=re(s?"chevron-up":"chevron-down",16,f,2);g?u.appendChild(g):u.textContent=s?"Hide":"Show";let m=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(a,m);let w=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",t.contentBackgroundColor&&(w.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(w.style.color=t.contentTextColor),t.contentPaddingX&&(w.style.paddingLeft=t.contentPaddingX,w.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(w.style.paddingTop=t.contentPaddingY,w.style.paddingBottom=t.contentPaddingY),o.name){let W=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?W.style.color=t.contentTextColor:t.headerTextColor&&(W.style.color=t.headerTextColor),W.textContent=o.name,w.appendChild(W)}if(o.args!==void 0){let W=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=ps(o.args),W.append(y,S),w.appendChild(W)}if(o.chunks&&o.chunks.length){let W=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=o.chunks.join(`
16
- `),W.append(y,S),w.appendChild(W)}if(o.status==="complete"&&o.result!==void 0){let W=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=ps(o.result),W.append(y,S),w.appendChild(W)}if(o.status==="complete"&&typeof o.duration=="number"){let W=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(W.style.color=t.contentTextColor),W.textContent=`Duration: ${o.duration}ms`,w.appendChild(W)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let W=t.toggleTextColor||t.headerTextColor||"currentColor",y=re(s?"chevron-up":"chevron-down",16,W,2);y?u.appendChild(y):u.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var oi=e=>{let n=[];return{buttons:n,render:(t,r,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(w=>w.role==="user"))return;let f=document.createDocumentFragment(),g=r?r.isStreaming():!1,m=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(w=>{let h=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");h.type="button",h.textContent=w,h.disabled=g,a!=null&&a.fontFamily&&(h.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(h.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(h.style.paddingLeft=a.paddingX,h.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(h.style.paddingTop=a.paddingY,h.style.paddingBottom=a.paddingY),h.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(w))}),f.appendChild(h),n.push(h)}),e.appendChild(f)}}};var ri={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"}},Cs=(e,n,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var h,F,W;if(s.dataset.enhanced==="true")return;let i=(h=s.dataset.tvForm)!=null?h:"init";s.dataset.enhanced="true";let a=(F=ri[i])!=null?F:ri.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),u=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=a.title,d.appendChild(u),a.description){let y=p("p","tvw-text-sm tvw-text-cw-muted");y.textContent=a.description,d.appendChild(y)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(y=>{var C,k;let S=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${n.id}-${i}-${y.name}`;let I=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=y.label,S.appendChild(I);let v=(C=y.type)!=null?C:"text",N;v==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=v),N.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",N.id=`${n.id}-${i}-${y.name}`,N.name=y.name,N.placeholder=(k=y.placeholder)!=null?k:"",y.required&&(N.required=!0),S.appendChild(N),f.appendChild(S)});let g=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]"),w=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");w.type="submit",w.textContent=(W=a.submitLabel)!=null?W:"Submit",g.appendChild(m),g.appendChild(w),f.appendChild(g),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var N,C;y.preventDefault();let S=(N=o.formEndpoint)!=null?N:"/form",I=new FormData(f),v={};I.forEach((k,K)=>{v[K]=k}),v.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let k=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let K=await k.json();m.textContent=(C=K.message)!=null?C:"Thanks! We'll be in touch soon.",K.success&&K.nextPrompt&&await t.sendMessage(String(K.nextPrompt))}catch(k){m.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var xs=class{constructor(){this.plugins=new Map}register(n){var o;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(o=n.onRegister)==null||o.call(n)}unregister(n){var t;let o=this.plugins.get(n);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=n.priority)!=null?r:0)})}getForInstance(n){let o=this.getAll();if(!n||n.length===0)return o;let t=new Set(n.map(s=>s.id));return[...o.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var o;return(o=n.onUnregister)==null?void 0:o.call(n)}),this.plugins.clear()}},Wn=new xs;var Ss={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"},As={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},Be={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ss,darkTheme:As,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Vn(e){var n,o,t,r,s,i,a,d,u,f,g,m,w,h,F,W,y,S,I;return e?{...Be,...e,theme:{...Be.theme,...e.theme},darkTheme:{...Be.darkTheme,...e.darkTheme},launcher:{...Be.launcher,...e.launcher,clearChat:{...(n=Be.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Be.copy,...e.copy},sendButton:{...Be.sendButton,...e.sendButton},statusIndicator:{...Be.statusIndicator,...e.statusIndicator},voiceRecognition:{...Be.voiceRecognition,...e.voiceRecognition},features:{...Be.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Be.suggestionChips,suggestionChipsConfig:{...Be.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Be.layout,...e.layout,header:{...(r=Be.layout)==null?void 0:r.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Be.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(u=(d=Be.layout)==null?void 0:d.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(w=(m=Be.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(F=(h=e.layout)==null?void 0:h.messages)==null?void 0:F.timestamp}},slots:{...(W=Be.layout)==null?void 0:W.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Be.markdown,...e.markdown,options:{...(S=Be.markdown)==null?void 0:S.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var ii=()=>{let e=new Map,n=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=e.get(r))==null||i.delete(s)};return{on:n,off:o,emit:(r,s)=>{var i;(i=e.get(r))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ji=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Yi=e=>{let n=e.trim(),o=n.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<n.length;r+=1){let s=n[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(o,r+1)}return null},kn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Ji(e),o=Yi(n);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Ts=e=>typeof e=="string"?e:e==null?"":String(e),en={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ts(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Ts(o.element);if(t&&((r=n.document)!=null&&r.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Ts(o.text)}}},ai=e=>Array.isArray(e)?e.map(n=>String(n)):[],Ln=e=>{let n=new Set(ai(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(ai(e.getSessionMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(n);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?e.parsers.reduce((u,f)=>u||(f==null?void 0:f({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),t();let d={action:a,message:s.message};e.emit("action:detected",d);for(let u of e.handlers)if(u)try{let f=u(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var Ki=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Xi=e=>e.map(n=>({...n,streaming:!1})),Gn=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?Ki(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?Xi(o.messages):void 0};t.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=n();if(o)try{o.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Ms=class{constructor(){this.components=new Map}register(n,o){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,o)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([o,t])=>{this.register(o,t)})}},dn=new Ms;var cn=require("partial-json");function Vi(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Gi(e,n){if(!Vi(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:n}}function Qn(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e;try{let r=(0,cn.parse)(o,cn.STR|cn.OBJ),s=Gi(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function li(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Zn(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=dn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:o,updateProps:a=>{r&&r(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function di(){let e=Qn();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function es(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ts(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var Qi=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ns(e){let{onSubmit:n,onDismiss:o,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:u=Qi}=e,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let g=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let h=document.createElement("h3");h.className="tvw-feedback-title",h.textContent=t,w.appendChild(h);let F=document.createElement("p");F.className="tvw-feedback-subtitle",F.textContent=r,w.appendChild(F),m.appendChild(w);let W=document.createElement("div");W.className="tvw-feedback-rating tvw-feedback-rating-csat",W.setAttribute("role","radiogroup"),W.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let C=1;C<=5;C++){let k=document.createElement("button");k.type="button",k.className="tvw-feedback-rating-btn tvw-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),k.title=u[C-1],k.dataset.rating=String(C),k.innerHTML=`
15
+ `,o.addEventListener("click",n);let t=s=>{var y,S,I,v,N,C,k,K,J,z,_,j;let i=(y=s.launcher)!=null?y:{},a=o.querySelector("[data-role='launcher-title']");a&&(a.textContent=(S=i.title)!=null?S:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(I=i.subtitle)!=null?I:"Get answers fast");let u=o.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let f=o.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let Y=(v=i.agentIconSize)!=null?v:"40px";if(f.style.height=Y,f.style.width=Y,f.innerHTML="",i.agentIconName){let H=parseFloat(Y)||24,V=re(i.agentIconName,H*.6,"#ffffff",2);V?(f.appendChild(V),f.style.display=""):(f.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(C=i.agentIconText)!=null?C:"\u{1F4AC}",f.style.display="")}let g=o.querySelector("[data-role='launcher-image']");if(g){let Y=(k=i.agentIconSize)!=null?k:"40px";g.style.height=Y,g.style.width=Y,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(g.src=i.iconUrl,g.style.display="block"):g.style.display="none"}let m=o.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Y=(K=i.callToActionIconSize)!=null?K:"32px";m.style.height=Y,m.style.width=Y,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 H=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,H=(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 V=parseFloat(Y)||24,Pe=Math.max(V-H,8),X=re(i.callToActionIconName,Pe,"currentColor",2);X?m.appendChild(X):m.textContent=(J=i.callToActionIconText)!=null?J:"\u2197"}else m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}let w=i.position&&kt[i.position]?kt[i.position]:kt["bottom-right"],h="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${h} ${w}`;let F="1px solid #e5e7eb",T="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(_=i.border)!=null?_:F,o.style.boxShadow=(j=i.shadow)!=null?j:T},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var qt=e=>{var z,_,j,Y,H,V,Pe,X,D,tt,at,lt,Lt,Ft,q,we,dt,ct,ze,ut,$t,Pt,Ht,$,Ne,me,nt,he,st,Te,xt,St;let{config:n,showClose:o=!0}=e,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(z=n==null?void 0:n.launcher)!=null?z:{},s=(_=r.headerIconSize)!=null?_:"48px",i=(j=r.closeButtonSize)!=null?j:"32px",a=(Y=r.closeButtonPlacement)!=null?Y:"inline",d=(H=r.headerIconHidden)!=null?H:!1,u=r.headerIconName,f=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=s,f.style.width=s,!d)if(u){let ae=parseFloat(s)||24,Je=re(u,ae*.6,"#ffffff",2);Je?f.replaceChildren(Je):f.textContent=(Pe=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?Pe:"\u{1F4AC}"}else if((X=n==null?void 0:n.launcher)!=null&&X.iconUrl){let ae=p("img");ae.src=n.launcher.iconUrl,ae.alt="",ae.className="tvw-rounded-xl tvw-object-cover",ae.style.height=s,ae.style.width=s,f.replaceChildren(ae)}else f.textContent=(tt=(D=n==null?void 0:n.launcher)==null?void 0:D.agentIconText)!=null?tt:"\u{1F4AC}";let g=p("div","tvw-flex tvw-flex-col"),m=p("span","tvw-text-base tvw-font-semibold");m.textContent=(lt=(at=n==null?void 0:n.launcher)==null?void 0:at.title)!=null?lt:"Chat Assistant";let w=p("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(Ft=(Lt=n==null?void 0:n.launcher)==null?void 0:Lt.subtitle)!=null?Ft:"Here to help you get answers fast",g.append(m,w),d?t.append(g):t.append(f,g);let h=(q=r.clearChat)!=null?q:{},F=(we=h.enabled)!=null?we:!0,T=(dt=h.placement)!=null?dt:"inline",y=null,S=null;if(F){let ae=(ct=h.size)!=null?ct:"32px",Je=(ze=h.iconName)!=null?ze:"refresh-cw",Qe=(ut=h.iconColor)!=null?ut:"",He=($t=h.backgroundColor)!=null?$t:"",Ye=(Pt=h.borderWidth)!=null?Pt:"",Wt=(Ht=h.borderColor)!=null?Ht:"",ft=($=h.borderRadius)!=null?$:"",ot=(Ne=h.paddingX)!=null?Ne:"",R=(me=h.paddingY)!=null?me:"",wt=(nt=h.tooltipText)!=null?nt:"Clear chat",yt=(he=h.showTooltip)!=null?he:!0;S=p("div",T==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),T==="top-right"&&(S.style.right="48px"),y=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"),y.style.height=ae,y.style.width=ae,y.type="button",y.setAttribute("aria-label",wt);let At=re(Je,"20px",Qe||"",2);if(At&&y.appendChild(At),Qe&&(y.style.color=Qe,y.classList.remove("tvw-text-cw-muted")),He&&(y.style.backgroundColor=He,y.classList.remove("hover:tvw-bg-gray-100")),Ye||Wt){let te=Ye||"0px",ye=Wt||"transparent";y.style.border=`${te} solid ${ye}`,y.classList.remove("tvw-border-none")}if(ft&&(y.style.borderRadius=ft,y.classList.remove("tvw-rounded-full")),ot?(y.style.paddingLeft=ot,y.style.paddingRight=ot):(y.style.paddingLeft="",y.style.paddingRight=""),R?(y.style.paddingTop=R,y.style.paddingBottom=R):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),yt&&wt&&y&&S){let te=null,ye=()=>{if(te||!y)return;te=p("div","tvw-clear-chat-tooltip"),te.textContent=wt;let vt=p("div");vt.className="tvw-clear-chat-tooltip-arrow",te.appendChild(vt);let Ze=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${Ze.left+Ze.width/2}px`,te.style.top=`${Ze.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Re=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};S.addEventListener("mouseenter",ye),S.addEventListener("mouseleave",Re),y.addEventListener("focus",ye),y.addEventListener("blur",Re),S._cleanupTooltip=()=>{Re(),S&&(S.removeEventListener("mouseenter",ye),S.removeEventListener("mouseleave",Re)),y&&(y.removeEventListener("focus",ye),y.removeEventListener("blur",Re))}}T==="inline"&&t.appendChild(S)}let I=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":F&&T==="inline"?"":"tvw-ml-auto"),v=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");v.style.height=i,v.style.width=i,v.type="button";let N=(st=r.closeButtonTooltipText)!=null?st:"Close chat",C=(Te=r.closeButtonShowTooltip)!=null?Te:!0;v.setAttribute("aria-label",N),v.style.display=o?"":"none";let k=(xt=r.closeButtonIconName)!=null?xt:"x",K=(St=r.closeButtonIconText)!=null?St:"\xD7",J=re(k,"20px",r.closeButtonColor||"",2);if(J?v.appendChild(J):v.textContent=K,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let ae=r.closeButtonBorderWidth||"0px",Je=r.closeButtonBorderColor||"transparent";v.style.border=`${ae} solid ${Je}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),I.appendChild(v),C&&N){let ae=null,Je=()=>{if(ae)return;ae=p("div","tvw-clear-chat-tooltip"),ae.textContent=N;let He=p("div");He.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(He);let Ye=v.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Ye.left+Ye.width/2}px`,ae.style.top=`${Ye.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},Qe=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};I.addEventListener("mouseenter",Je),I.addEventListener("mouseleave",Qe),v.addEventListener("focus",Je),v.addEventListener("blur",Qe),I._cleanupTooltip=()=>{Qe(),I.removeEventListener("mouseenter",Je),I.removeEventListener("mouseleave",Qe),v.removeEventListener("focus",Je),v.removeEventListener("blur",Qe)}}return a!=="top-right"&&t.appendChild(I),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:v,closeButtonWrapper:I,clearChatButton:y,clearChatButtonWrapper:S}},Zt=(e,n,o)=>{var i,a,d,u;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"inline";e.appendChild(n.header),r==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var hs=e=>qt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),fs=e=>{var h,F,T,y;let{config:n,showClose:o=!0,onClose:t}=e,r=(h=n==null?void 0:n.launcher)!=null?h:{},s=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(F=r.title)!=null?F:"Chat Assistant",s.appendChild(i);let a=(T=r.closeButtonSize)!=null?T:"32px",d=p("div",""),u=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");u.style.height=a,u.style.width=a,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=o?"":"none";let f=(y=r.closeButtonIconName)!=null?y:"x",g=re(f,"20px",r.closeButtonColor||"",2);g?u.appendChild(g):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),s.appendChild(d);let m=p("div");m.style.display="none";let w=p("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},ws=e=>{var v,N,C,k,K,J,z,_;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(v=n==null?void 0:n.launcher)!=null?v:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=p("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=s.headerIconSize)!=null?N:"56px",u=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");u.style.height=d,u.style.width=d;let f=s.headerIconName;if(f){let j=parseFloat(d)||24,Y=re(f,j*.5,"#ffffff",2);Y?u.replaceChildren(Y):u.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let j=p("img");j.src=s.iconUrl,j.alt="",j.className="tvw-rounded-xl tvw-object-cover",j.style.height=d,j.style.width=d,u.replaceChildren(j)}else u.textContent=(k=s.agentIconText)!=null?k:"\u{1F4AC}";let g=p("div","tvw-flex tvw-flex-col tvw-flex-1"),m=p("span","tvw-text-lg tvw-font-semibold");m.textContent=(K=s.title)!=null?K:"Chat Assistant";let w=p("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(J=s.subtitle)!=null?J:"Here to help you get answers fast",g.append(m,w),a.append(u,g);let h=(z=s.closeButtonSize)!=null?z:"32px",F=p("div",""),T=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");T.style.height=h,T.style.width=h,T.type="button",T.setAttribute("aria-label","Close chat"),T.style.display=o?"":"none";let y=(_=s.closeButtonIconName)!=null?_:"x",S=re(y,"20px",s.closeButtonColor||"",2);S?T.appendChild(S):T.textContent="\xD7",t&&T.addEventListener("click",t),F.appendChild(T),a.appendChild(F),i.appendChild(a);let I=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return I.textContent="Online and ready to help",i.appendChild(I),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:T,closeButtonWrapper:F,clearChatButton:null,clearChatButtonWrapper:null}},Xn={default:hs,minimal:fs,expanded:ws},ys=e=>{var n;return(n=Xn[e])!=null?n:Xn.default},on=(e,n,o)=>{var i,a,d;if(n!=null&&n.render){let u=n.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=p("div");f.style.display="none";let g=p("span"),m=p("span"),w=p("button");w.style.display="none";let h=p("div");return h.style.display="none",{header:u,iconHolder:f,headerTitle:g,headerSubtitle:m,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=ys(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var zi=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},rn=e=>{var q,we,dt,ct,ze,ut,$t,Pt,Ht,$,Ne,me,nt,he,st,Te,xt,St,ae,Je,Qe,He,Ye,Wt,ft,ot,R,wt,yt,At;let{config:n}=e,o=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=p("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");r.style.outline="none";let s=p("textarea");s.placeholder=(we=(q=n==null?void 0:n.copy)==null?void 0:q.inputPlaceholder)!=null?we:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",s.rows=1;let i=(ct=(dt=n==null?void 0:n.theme)==null?void 0:dt.inputFontFamily)!=null?ct:"sans-serif",a=(ut=(ze=n==null?void 0:n.theme)==null?void 0:ze.inputFontWeight)!=null?ut:"400";s.style.fontFamily=zi(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let g=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",g),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=($t=n==null?void 0:n.sendButton)!=null?$t:{},w=(Pt=m.useIcon)!=null?Pt:!1,h=(Ht=m.iconText)!=null?Ht:"\u2191",F=m.iconName,T=($=m.tooltipText)!=null?$:"Send message",y=(Ne=m.showTooltip)!=null?Ne:!1,S=(me=m.size)!=null?me:"40px",I=m.backgroundColor,v=m.textColor,N=p("div","tvw-send-button-wrapper"),C=p("button",w?"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(C.type="submit",w){if(C.style.width=S,C.style.height=S,C.style.minWidth=S,C.style.minHeight=S,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",F){let te=parseFloat(S)||24,ye=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Re=re(F,te,ye,2);Re?(C.appendChild(Re),C.style.color=ye):(C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white"))}else C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white");I?C.style.backgroundColor=I:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(he=(nt=n==null?void 0:n.copy)==null?void 0:nt.sendButtonLabel)!=null?he:"Send",v?C.style.color=v:C.classList.add("tvw-text-white");if(m.borderWidth&&(C.style.borderWidth=m.borderWidth,C.style.borderStyle="solid"),m.borderColor&&(C.style.borderColor=m.borderColor),m.paddingX?(C.style.paddingLeft=m.paddingX,C.style.paddingRight=m.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),m.paddingY?(C.style.paddingTop=m.paddingY,C.style.paddingBottom=m.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),y&&T){let te=p("div","tvw-send-button-tooltip");te.textContent=T,N.appendChild(te)}N.appendChild(C);let k=(st=n==null?void 0:n.voiceRecognition)!=null?st:{},K=k.enabled===!0,J=null,z=null,_=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(K&&_){z=p("div","tvw-send-button-wrapper"),J=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),J.type="button",J.setAttribute("aria-label","Start voice recognition");let te=(Te=k.iconName)!=null?Te:"mic",ye=(xt=k.iconSize)!=null?xt:S,Re=parseFloat(ye)||24,vt=(St=k.backgroundColor)!=null?St:I,Ze=(ae=k.iconColor)!=null?ae:v;J.style.width=ye,J.style.height=ye,J.style.minWidth=ye,J.style.minHeight=ye,J.style.fontSize="18px",J.style.lineHeight="1";let Bt=Ze||"currentColor",It=re(te,Re,Bt,1.5);It?(J.appendChild(It),J.style.color=Bt):(J.textContent="\u{1F3A4}",J.style.color=Bt),vt?J.style.backgroundColor=vt:J.classList.add("tvw-bg-cw-primary"),Ze?J.style.color=Ze:!Ze&&!v&&J.classList.add("tvw-text-white"),k.borderWidth&&(J.style.borderWidth=k.borderWidth,J.style.borderStyle="solid"),k.borderColor&&(J.style.borderColor=k.borderColor),k.paddingX&&(J.style.paddingLeft=k.paddingX,J.style.paddingRight=k.paddingX),k.paddingY&&(J.style.paddingTop=k.paddingY,J.style.paddingBottom=k.paddingY),z.appendChild(J);let Ot=(Je=k.tooltipText)!=null?Je:"Start voice recognition";if(((Qe=k.showTooltip)!=null?Qe:!1)&&Ot){let Nt=p("div","tvw-send-button-tooltip");Nt.textContent=Ot,z.appendChild(Nt)}}let j=(He=n==null?void 0:n.attachments)!=null?He:{},Y=j.enabled===!0,H=null,V=null,Pe=null,X=null;if(Y){X=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),X.style.display="none",Pe=p("input"),Pe.type="file",Pe.accept=((Ye=j.allowedTypes)!=null?Ye:Jt).join(","),Pe.multiple=((Wt=j.maxFiles)!=null?Wt:4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),V=p("div","tvw-send-button-wrapper"),H=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),H.type="button",H.setAttribute("aria-label",(ft=j.buttonTooltipText)!=null?ft:"Attach file");let te=(ot=j.buttonIconName)!=null?ot:"paperclip",ye=S,Re=parseFloat(ye)||40,vt=Math.round(Re*.6);H.style.width=ye,H.style.height=ye,H.style.minWidth=ye,H.style.minHeight=ye,H.style.fontSize="18px",H.style.lineHeight="1",H.style.backgroundColor="transparent",H.style.color="var(--cw-primary, #111827)",H.style.border="none",H.style.borderRadius="6px",H.style.transition="background-color 0.15s ease",H.addEventListener("mouseenter",()=>{H.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),H.addEventListener("mouseleave",()=>{H.style.backgroundColor="transparent"});let Ze=re(te,vt,"currentColor",1.5);Ze?H.appendChild(Ze):H.textContent="\u{1F4CE}",H.addEventListener("click",Ot=>{Ot.preventDefault(),Pe==null||Pe.click()}),V.appendChild(H);let Bt=(R=j.buttonTooltipText)!=null?R:"Attach file",It=p("div","tvw-send-button-tooltip");It.textContent=Bt,V.appendChild(It)}r.addEventListener("click",te=>{te.target!==C&&te.target!==N&&te.target!==J&&te.target!==z&&te.target!==H&&te.target!==V&&s.focus()}),X&&(X.style.gap="8px",r.append(X)),Pe&&r.append(Pe),r.append(s);let D=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),tt=p("div","tvw-flex tvw-items-center tvw-gap-2");V&&tt.append(V);let at=p("div","tvw-flex tvw-items-center tvw-gap-1");z&&at.append(z),at.append(N),D.append(tt,at),r.append(D);let lt=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Lt=(wt=n==null?void 0:n.statusIndicator)!=null?wt:{},Ft=(yt=Lt.visible)!=null?yt:!0;return lt.style.display=Ft?"":"none",lt.textContent=(At=Lt.idleText)!=null?At:"Online",o.append(t,r,lt),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:N,micButton:J,micButtonWrapper:z,statusText:lt,attachmentButton:H,attachmentButtonWrapper:V,attachmentInput:Pe,attachmentPreviewsContainer:X,actionsRow:D,leftActions:tt,rightActions:at}};var Zr=e=>{var d,u,f,g,m,w,h;if(!((u=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?u:!0)){let F=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),T=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?g:"100%";return F.style.width=y,T.style.width="100%",F.appendChild(T),{wrapper:F,panel:T}}let o=(m=e==null?void 0:e.launcher)!=null?m:{},t=o.position&&kt[o.position]?kt[o.position]:kt["bottom-right"],r=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(h=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?h:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,r.appendChild(s),{wrapper:r,panel:s}},ei=(e,n=!0)=>{var w,h,F,T,y,S,I;let o=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=e==null?void 0:e.layout)==null?void 0:w.header,r=((h=e==null?void 0:e.layout)==null?void 0:h.showHeader)!==!1,s=t?on(e,t,{showClose:n}):qt({config:e,showClose:n}),i=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(T=(F=e==null?void 0:e.copy)==null?void 0:F.welcomeTitle)!=null?T:"Hello \u{1F44B}";let u=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",a.append(d,u);let f=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let g=rn({config:e}),m=((I=e==null?void 0:e.layout)==null?void 0:I.showFooter)!==!1;return r?Zt(o,s,e):(s.header.style.display="none",Zt(o,s,e)),o.append(i),m||(g.footer.style.display="none"),o.append(g.footer),{container:o,body:i,messagesWrapper:f,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:u,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions}};var Wn=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",e.appendChild(n),e.appendChild(o),e.appendChild(t),e.appendChild(r),e},Ji=(e,n)=>{let o=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=p("img");r.src=t,r.alt=n==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=n==="user"?"U":"A",o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},ti=(e,n)=>{let o=p("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?o.textContent=n.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Yi=(e,n="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return o},vs=(e,n,o)=>{var h,F,T,y,S,I;let t=(h=n.showCopy)!=null?h:!0,r=(F=n.showUpvote)!=null?F:!0,s=(T=n.showDownvote)!=null?T:!0,i=(y=n.visibility)!=null?y:"hover",a=(S=n.align)!=null?S:"right",d=(I=n.layout)!=null?I:"pill-inside",u={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],g=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let m=null,w=(v,N,C,k)=>{let K=document.createElement("button");K.className="tvw-message-action-btn",K.setAttribute("aria-label",N),K.setAttribute("title",N),k&&K.setAttribute("data-action",k);let J=re(v,14,"currentColor",2);return J&&K.appendChild(J),K.addEventListener("click",z=>{z.preventDefault(),z.stopPropagation(),C()}),K};if(t){let v=w("copy","Copy message",()=>{let N=e.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let C=re("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=re("copy",14,"currentColor",2);k&&(v.innerHTML="",v.appendChild(k))},2e3)}).catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",C)}),o!=null&&o.onCopy&&o.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");g.appendChild(v)}if(r){let v=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=g.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),m="upvote",v.classList.add("tvw-message-action-active");let k={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"upvote");g.appendChild(v)}if(s){let v=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=g.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),m="downvote",v.classList.add("tvw-message-action-active");let k={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"downvote");g.appendChild(v)}return g},an=(e,n,o,t,r)=>{var I,v,N,C,k;let s=o!=null?o:{},i=(I=s.layout)!=null?I:"bubble",a=s.avatar,d=s.timestamp,u=(v=a==null?void 0:a.show)!=null?v:!1,f=(N=d==null?void 0:d.show)!=null?N:!1,g=(C=a==null?void 0:a.position)!=null?C:"left",m=(k=d==null?void 0:d.position)!=null?k:"below",w=Yi(e.role,i),h=p("div",w.join(" "));h.id=`bubble-${e.id}`,h.setAttribute("data-message-id",e.id);let F=document.createElement("div");if(F.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),f&&m==="inline"&&e.createdAt){let K=ti(e,d);K.classList.add("tvw-ml-2","tvw-inline"),F.appendChild(K)}if(h.appendChild(F),f&&m==="below"&&e.createdAt){let K=ti(e,d);K.classList.add("tvw-mt-1"),h.appendChild(K)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let K=Wn();h.appendChild(K)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let K=vs(e,t,r);h.appendChild(K)}if(!u||e.role==="system")return h;let y=p("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),S=Ji(a,e.role);return g==="right"||g==="left"&&e.role==="user"?y.append(h,S):y.append(S,h),h.classList.remove("tvw-max-w-[85%]"),h.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},ni=(e,n,o,t,r)=>{let s=o!=null?o:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):an(e,n,o,t,r)};var ln=new Set,si=(e,n)=>{let o=ln.has(e),t=n.querySelector('button[data-expand-header="true"]'),r=n.querySelector(".tvw-border-t");if(!t||!r)return;t.setAttribute("aria-expanded",o?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=re(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},bs=e=>{let n=e.reasoning,o=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let t=ln.has(e.id),r=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("data-expand-header","true"),r.setAttribute("data-bubble-type","reasoning");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=p("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Br(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),f=re(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let g=p("div","tvw-flex tvw-items-center tvw-ml-auto");g.append(d),r.append(s,g);let m=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let w=n.chunks.join(""),h=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return h.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(h),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=re(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),o.append(r,m),o};var dn=new Set,oi=(e,n,o)=>{var u;let t=dn.has(e),r=(u=o==null?void 0:o.toolCall)!=null?u:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",t?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let f=r.toggleTextColor||r.headerTextColor||"currentColor",g=re(t?"chevron-up":"chevron-down",16,f,2);g?d.appendChild(g):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Cs=(e,n)=>{var F;let o=e.toolCall,t=(F=n==null?void 0:n.toolCall)!=null?F:{},r=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!o)return r;let s=dn.has(e.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=p("div","tvw-flex tvw-flex-col tvw-text-left"),d=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Ir(o),a.appendChild(d);let u=p("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",g=re(s?"chevron-up":"chevron-down",16,f,2);g?u.appendChild(g):u.textContent=s?"Hide":"Show";let m=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(a,m);let w=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",t.contentBackgroundColor&&(w.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(w.style.color=t.contentTextColor),t.contentPaddingX&&(w.style.paddingLeft=t.contentPaddingX,w.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(w.style.paddingTop=t.contentPaddingY,w.style.paddingBottom=t.contentPaddingY),o.name){let T=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?T.style.color=t.contentTextColor:t.headerTextColor&&(T.style.color=t.headerTextColor),T.textContent=o.name,w.appendChild(T)}if(o.args!==void 0){let T=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=gs(o.args),T.append(y,S),w.appendChild(T)}if(o.chunks&&o.chunks.length){let T=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=o.chunks.join(`
16
+ `),T.append(y,S),w.appendChild(T)}if(o.status==="complete"&&o.result!==void 0){let T=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=gs(o.result),T.append(y,S),w.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(T.style.color=t.contentTextColor),T.textContent=`Duration: ${o.duration}ms`,w.appendChild(T)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let T=t.toggleTextColor||t.headerTextColor||"currentColor",y=re(s?"chevron-up":"chevron-down",16,T,2);y?u.appendChild(y):u.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var ri=e=>{let n=[];return{buttons:n,render:(t,r,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(w=>w.role==="user"))return;let f=document.createDocumentFragment(),g=r?r.isStreaming():!1,m=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(w=>{let h=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");h.type="button",h.textContent=w,h.disabled=g,a!=null&&a.fontFamily&&(h.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(h.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(h.style.paddingLeft=a.paddingX,h.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(h.style.paddingTop=a.paddingY,h.style.paddingBottom=a.paddingY),h.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(w))}),f.appendChild(h),n.push(h)}),e.appendChild(f)}}};var ii={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"}},xs=(e,n,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var h,F,T;if(s.dataset.enhanced==="true")return;let i=(h=s.dataset.tvForm)!=null?h:"init";s.dataset.enhanced="true";let a=(F=ii[i])!=null?F:ii.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),u=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=a.title,d.appendChild(u),a.description){let y=p("p","tvw-text-sm tvw-text-cw-muted");y.textContent=a.description,d.appendChild(y)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(y=>{var C,k;let S=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${n.id}-${i}-${y.name}`;let I=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=y.label,S.appendChild(I);let v=(C=y.type)!=null?C:"text",N;v==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=v),N.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",N.id=`${n.id}-${i}-${y.name}`,N.name=y.name,N.placeholder=(k=y.placeholder)!=null?k:"",y.required&&(N.required=!0),S.appendChild(N),f.appendChild(S)});let g=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]"),w=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");w.type="submit",w.textContent=(T=a.submitLabel)!=null?T:"Submit",g.appendChild(m),g.appendChild(w),f.appendChild(g),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var N,C;y.preventDefault();let S=(N=o.formEndpoint)!=null?N:"/form",I=new FormData(f),v={};I.forEach((k,K)=>{v[K]=k}),v.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let k=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let K=await k.json();m.textContent=(C=K.message)!=null?C:"Thanks! We'll be in touch soon.",K.success&&K.nextPrompt&&await t.sendMessage(String(K.nextPrompt))}catch(k){m.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Ss=class{constructor(){this.plugins=new Map}register(n){var o;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(o=n.onRegister)==null||o.call(n)}unregister(n){var t;let o=this.plugins.get(n);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=n.priority)!=null?r:0)})}getForInstance(n){let o=this.getAll();if(!n||n.length===0)return o;let t=new Set(n.map(s=>s.id));return[...o.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var o;return(o=n.onUnregister)==null?void 0:o.call(n)}),this.plugins.clear()}},kn=new Ss;var As={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"},Ts={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},Be={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:As,darkTheme:Ts,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Gn(e){var n,o,t,r,s,i,a,d,u,f,g,m,w,h,F,T,y,S,I;return e?{...Be,...e,theme:{...Be.theme,...e.theme},darkTheme:{...Be.darkTheme,...e.darkTheme},launcher:{...Be.launcher,...e.launcher,clearChat:{...(n=Be.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Be.copy,...e.copy},sendButton:{...Be.sendButton,...e.sendButton},statusIndicator:{...Be.statusIndicator,...e.statusIndicator},voiceRecognition:{...Be.voiceRecognition,...e.voiceRecognition},features:{...Be.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Be.suggestionChips,suggestionChipsConfig:{...Be.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Be.layout,...e.layout,header:{...(r=Be.layout)==null?void 0:r.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Be.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(u=(d=Be.layout)==null?void 0:d.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(w=(m=Be.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(F=(h=e.layout)==null?void 0:h.messages)==null?void 0:F.timestamp}},slots:{...(T=Be.layout)==null?void 0:T.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Be.markdown,...e.markdown,options:{...(S=Be.markdown)==null?void 0:S.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var ai=()=>{let e=new Map,n=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=e.get(r))==null||i.delete(s)};return{on:n,off:o,emit:(r,s)=>{var i;(i=e.get(r))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ki=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Vi=e=>{let n=e.trim(),o=n.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<n.length;r+=1){let s=n[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(o,r+1)}return null},Ln=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Ki(e),o=Vi(n);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Ms=e=>typeof e=="string"?e:e==null?"":String(e),en={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ms(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Ms(o.element);if(t&&((r=n.document)!=null&&r.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Ms(o.text)}}},li=e=>Array.isArray(e)?e.map(n=>String(n)):[],Pn=e=>{let n=new Set(li(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(li(e.getSessionMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(n);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?e.parsers.reduce((u,f)=>u||(f==null?void 0:f({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),t();let d={action:a,message:s.message};e.emit("action:detected",d);for(let u of e.handlers)if(u)try{let f=u(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var Xi=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Gi=e=>e.map(n=>({...n,streaming:!1})),Qn=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?Xi(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?Gi(o.messages):void 0};t.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=n();if(o)try{o.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Es=class{constructor(){this.components=new Map}register(n,o){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,o)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([o,t])=>{this.register(o,t)})}},cn=new Es;var un=require("partial-json");function Qi(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Zi(e,n){if(!Qi(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:n}}function Zn(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e;try{let r=(0,un.parse)(o,un.STR|un.OBJ),s=Zi(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function di(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function es(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=cn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:o,updateProps:a=>{r&&r(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function ci(){let e=Zn();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ts(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ns(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var ea=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ss(e){let{onSubmit:n,onDismiss:o,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:u=ea}=e,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let g=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let h=document.createElement("h3");h.className="tvw-feedback-title",h.textContent=t,w.appendChild(h);let F=document.createElement("p");F.className="tvw-feedback-subtitle",F.textContent=r,w.appendChild(F),m.appendChild(w);let T=document.createElement("div");T.className="tvw-feedback-rating tvw-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let C=1;C<=5;C++){let k=document.createElement("button");k.type="button",k.className="tvw-feedback-rating-btn tvw-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),k.title=u[C-1],k.dataset.rating=String(C),k.innerHTML=`
17
17
  <svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
18
18
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
19
19
  </svg>
20
- `,k.addEventListener("click",()=>{g=C,y.forEach((K,J)=>{let z=J<C;K.classList.toggle("selected",z),K.setAttribute("aria-checked",J===C-1?"true":"false")})}),y.push(k),W.appendChild(k)}m.appendChild(W);let S=null;if(d){let C=document.createElement("div");C.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),C.appendChild(S),m.appendChild(C)}let I=document.createElement("div");I.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=a,v.addEventListener("click",()=>{o==null||o(),f.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(g===null){W.classList.add("tvw-feedback-shake"),setTimeout(()=>W.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let C=(S==null?void 0:S.value.trim())||void 0;await n(g,C),f.remove()}catch(C){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(v),I.appendChild(N),m.appendChild(I),f.appendChild(m),f}function ss(e){let{onSubmit:n,onDismiss:o,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:f="Very likely"}=e,g=document.createElement("div");g.className="tvw-feedback-container tvw-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let F=document.createElement("h3");F.className="tvw-feedback-title",F.textContent=t,h.appendChild(F);let W=document.createElement("p");W.className="tvw-feedback-subtitle",W.textContent=r,h.appendChild(W),w.appendChild(h);let y=document.createElement("div");y.className="tvw-feedback-rating tvw-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="tvw-feedback-labels";let I=document.createElement("span");I.className="tvw-feedback-label-low",I.textContent=u;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,S.appendChild(I),S.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let C=[];for(let _=0;_<=10;_++){let j=document.createElement("button");j.type="button",j.className="tvw-feedback-rating-btn tvw-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${_} out of 10`),j.textContent=String(_),j.dataset.rating=String(_),_<=6?j.classList.add("tvw-feedback-detractor"):_<=8?j.classList.add("tvw-feedback-passive"):j.classList.add("tvw-feedback-promoter"),j.addEventListener("click",()=>{m=_,C.forEach((Y,H)=>{Y.classList.toggle("selected",H===_),Y.setAttribute("aria-checked",H===_?"true":"false")})}),C.push(j),N.appendChild(j)}y.appendChild(S),y.appendChild(N),w.appendChild(y);let k=null;if(d){let _=document.createElement("div");_.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),_.appendChild(k),w.appendChild(_)}let K=document.createElement("div");K.className="tvw-feedback-actions";let J=document.createElement("button");J.type="button",J.className="tvw-feedback-btn tvw-feedback-btn-skip",J.textContent=a,J.addEventListener("click",()=>{o==null||o(),g.remove()});let z=document.createElement("button");return z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-submit",z.textContent=i,z.addEventListener("click",async()=>{if(m===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let _=(k==null?void 0:k.value.trim())||void 0;await n(m,_),g.remove()}catch(_){z.disabled=!1,z.textContent=i,console.error("[NPS Feedback] Failed to submit:",_)}}),K.appendChild(J),K.appendChild(z),w.appendChild(K),g.appendChild(w),g}var un="persona-chat-history",Zi=30*1e3,Es=e=>!e||typeof e!="object"?{}:{...e},ci=e=>e.map(n=>({...n,streaming:!1})),ui=(e,n)=>{let o=e!=null&&e.markdown?Sn(e.markdown):null;return t=>{var i,a,d;let r=(i=t.text)!=null?i:"",s=(a=t.message.rawContent)!=null?a:null;if(n){let u=n.process({text:r,raw:s!=null?s:r,message:t.message,streaming:t.streaming});u!==null&&(r=u.text,u.persist||(t.message.__skipPersist=!0))}return e!=null&&e.postprocessMessage?e.postprocessMessage({...t,text:r,raw:(d=s!=null?s:t.text)!=null?d:""}):o?o(r):On(r)}},os=(e,n,o)=>{var Bs,Is,Rs,Fs,$s,Os,Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Xs;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=Vn(n),r=Wn.getForInstance(t.plugins);t.components&&dn.registerAll(t.components);let s=ii(),i=(Bs=t.storageAdapter)!=null?Bs:Gn(),a={},d=null;if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l;else if(l){let c=l;c.metadata&&(a=Es(c.metadata)),(Is=c.messages)!=null&&Is.length&&(t={...t,initialMessages:c.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let u=()=>a,f=l=>{var A;a=(A=l({...a}))!=null?A:{},mn()},g=t.actionParsers&&t.actionParsers.length?t.actionParsers:[kn],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick],w=Ln({parsers:g,handlers:m,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Fs=(Rs=t.launcher)==null?void 0:Rs.enabled)!=null?Fs:!0,F=(Os=($s=t.launcher)==null?void 0:$s.autoExpand)!=null?Os:!1,W=F,y=h,S=(js=(Ns=t.layout)==null?void 0:Ns.header)==null?void 0:js.layout,I=h?F:!0,v=ui(t,w),N=(_s=(Ds=t.features)==null?void 0:Ds.showReasoning)!=null?_s:!0,C=(Us=(qs=t.features)==null?void 0:qs.showToolCalls)!=null?Us:!0,k={onCopy:l=>{var c,A;s.emit("message:copy",l),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(l.id,"copy").catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",P)}),(A=(c=t.messageActions)==null?void 0:c.onCopy)==null||A.call(c,l)},onFeedback:l=>{var c,A;s.emit("message:feedback",l),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(l.messageId,l.type).catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",P)}),(A=(c=t.messageActions)==null?void 0:c.onFeedback)==null||A.call(c,l)}},K=(zs=t.statusIndicator)!=null?zs:{},J=l=>{var c,A,P,b;return l==="idle"?(c=K.idleText)!=null?c:gt.idle:l==="connecting"?(A=K.connectingText)!=null?A:gt.connecting:l==="connected"?(P=K.connectedText)!=null?P:gt.connected:l==="error"?(b=K.errorText)!=null?b:gt.error:gt[l]},{wrapper:z,panel:_}=Qr(t),j=Zr(t,h),{container:Y,body:H,messagesWrapper:X,suggestions:Pe,textarea:V,sendButton:D,sendButtonWrapper:tt,composerForm:at,statusText:lt,introTitle:Lt,introSubtitle:Ft,closeButton:q,iconHolder:we,headerTitle:dt,headerSubtitle:ct,header:ze,footer:ut,actionsRow:$t,leftActions:Pt,rightActions:Ht}=j,$=j.micButton,Ne=j.micButtonWrapper,me=j.attachmentButton,nt=j.attachmentButtonWrapper,he=j.attachmentInput,st=j.attachmentPreviewsContainer,Te=null;(Js=t.attachments)!=null&&Js.enabled&&he&&st&&(Te=Qt.fromConfig(t.attachments),Te.setPreviewsContainer(st),he.addEventListener("change",l=>{let c=l.target;Te==null||Te.handleFileSelect(c.files),c.value=""}));let xt=r.find(l=>l.renderHeader);if(xt!=null&&xt.renderHeader){let l=xt.renderHeader({config:t,defaultRenderer:()=>{let c=qt({config:t,showClose:h});return Zt(Y,c,t),c.header},onClose:()=>M(!1,"user")});if(l){let c=Y.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),ze=l)}}let St=r.find(l=>l.renderComposer);if(St!=null&&St.renderComposer){let l=St.renderComposer({config:t,defaultRenderer:()=>on({config:t}).footer,onSubmit:c=>{R&&!R.isStreaming()&&R.sendMessage(c)},disabled:!1});l&&(ut.replaceWith(l),ut=l)}(()=>{var P,b;let l=(b=(P=t.layout)==null?void 0:P.slots)!=null?b:{},c=Q=>{switch(Q){case"body-top":return Y.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return X;case"footer-top":return Pe;case"composer":return at;case"footer-bottom":return lt;default:return null}},A=(Q,ue)=>{var T;switch(Q){case"header-left":case"header-center":case"header-right":if(Q==="header-left")ze.insertBefore(ue,ze.firstChild);else if(Q==="header-right")ze.appendChild(ue);else{let G=ze.querySelector(".tvw-flex-col");G?(T=G.parentNode)==null||T.insertBefore(ue,G.nextSibling):ze.appendChild(ue)}break;case"body-top":{let G=H.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(ue):H.insertBefore(ue,H.firstChild);break}case"body-bottom":H.appendChild(ue);break;case"footer-top":Pe.replaceWith(ue);break;case"footer-bottom":lt.replaceWith(ue);break;default:break}};for(let[Q,ue]of Object.entries(l))if(ue)try{let T=ue({config:t,defaultContent:()=>c(Q)});T&&A(Q,T)}catch(T){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${Q}":`,T)}})();let Je=l=>{let A=l.target.closest('button[data-expand-header="true"]');if(!A)return;let P=A.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!P)return;let b=P.getAttribute("data-message-id");if(!b)return;let Q=A.getAttribute("data-bubble-type");Q==="reasoning"?(an.has(b)?an.delete(b):an.add(b),ni(b,P)):Q==="tool"&&(ln.has(b)?ln.delete(b):ln.add(b),si(b,P,t))};X.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),X.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),_.appendChild(Y),e.appendChild(z);let Qe=()=>{var pe,_e,qe,rt,Tt,ee,Ee,Kt,Xt,Bn,In,cs,Ue,Rn,hn,fn;let l=(_e=(pe=t.launcher)==null?void 0:pe.sidebarMode)!=null?_e:!1,c=l||((rt=(qe=t.launcher)==null?void 0:qe.fullHeight)!=null?rt:!1),A=(Tt=t.theme)!=null?Tt:{},P=(Ee=(ee=t.launcher)==null?void 0:ee.position)!=null?Ee:"bottom-left",b=P==="bottom-left"||P==="top-left",Q=l?"none":"1px solid var(--tvw-cw-border)",ue=l?b?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",T=l?"0":"16px",G=(Kt=A.panelBorder)!=null?Kt:Q,Z=(Xt=A.panelShadow)!=null?Xt:ue,ve=(Bn=A.panelBorderRadius)!=null?Bn:T;e.style.cssText="",z.style.cssText="",_.style.cssText="",Y.style.cssText="",H.style.cssText="",ut.style.cssText="";let O=(cs=(In=t==null?void 0:t.launcher)==null?void 0:In.width)!=null?cs:t==null?void 0:t.launcherWidth,Fe=O!=null?O:"min(400px, calc(100vw - 24px))";l||(_.style.width=Fe,_.style.maxWidth=Fe),_.style.boxShadow=Z,_.style.borderRadius=ve,Y.style.border=G,Y.style.borderRadius=ve;let Ae=((Ue=t.launcher)==null?void 0:Ue.enabled)===!1;if(c&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.height="100%",Ae&&(z.style.overflow="hidden"),_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.height="100%",_.style.overflow="hidden",Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.overflow="hidden",H.style.flex="1 1 0%",H.style.minHeight="0",H.style.overflowY="auto",ut.style.flexShrink="0"),z.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!Ae&&((Rn=kt[P])!=null?Rn:kt["bottom-right"]).split(" ").forEach(wn=>z.classList.add(wn)),l){let zt=(fn=(hn=t.launcher)==null?void 0:hn.sidebarWidth)!=null?fn:"420px";z.style.cssText=`
20
+ `,k.addEventListener("click",()=>{g=C,y.forEach((K,J)=>{let z=J<C;K.classList.toggle("selected",z),K.setAttribute("aria-checked",J===C-1?"true":"false")})}),y.push(k),T.appendChild(k)}m.appendChild(T);let S=null;if(d){let C=document.createElement("div");C.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),C.appendChild(S),m.appendChild(C)}let I=document.createElement("div");I.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=a,v.addEventListener("click",()=>{o==null||o(),f.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(g===null){T.classList.add("tvw-feedback-shake"),setTimeout(()=>T.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let C=(S==null?void 0:S.value.trim())||void 0;await n(g,C),f.remove()}catch(C){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(v),I.appendChild(N),m.appendChild(I),f.appendChild(m),f}function os(e){let{onSubmit:n,onDismiss:o,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:f="Very likely"}=e,g=document.createElement("div");g.className="tvw-feedback-container tvw-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let F=document.createElement("h3");F.className="tvw-feedback-title",F.textContent=t,h.appendChild(F);let T=document.createElement("p");T.className="tvw-feedback-subtitle",T.textContent=r,h.appendChild(T),w.appendChild(h);let y=document.createElement("div");y.className="tvw-feedback-rating tvw-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="tvw-feedback-labels";let I=document.createElement("span");I.className="tvw-feedback-label-low",I.textContent=u;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,S.appendChild(I),S.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let C=[];for(let _=0;_<=10;_++){let j=document.createElement("button");j.type="button",j.className="tvw-feedback-rating-btn tvw-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${_} out of 10`),j.textContent=String(_),j.dataset.rating=String(_),_<=6?j.classList.add("tvw-feedback-detractor"):_<=8?j.classList.add("tvw-feedback-passive"):j.classList.add("tvw-feedback-promoter"),j.addEventListener("click",()=>{m=_,C.forEach((Y,H)=>{Y.classList.toggle("selected",H===_),Y.setAttribute("aria-checked",H===_?"true":"false")})}),C.push(j),N.appendChild(j)}y.appendChild(S),y.appendChild(N),w.appendChild(y);let k=null;if(d){let _=document.createElement("div");_.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),_.appendChild(k),w.appendChild(_)}let K=document.createElement("div");K.className="tvw-feedback-actions";let J=document.createElement("button");J.type="button",J.className="tvw-feedback-btn tvw-feedback-btn-skip",J.textContent=a,J.addEventListener("click",()=>{o==null||o(),g.remove()});let z=document.createElement("button");return z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-submit",z.textContent=i,z.addEventListener("click",async()=>{if(m===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let _=(k==null?void 0:k.value.trim())||void 0;await n(m,_),g.remove()}catch(_){z.disabled=!1,z.textContent=i,console.error("[NPS Feedback] Failed to submit:",_)}}),K.appendChild(J),K.appendChild(z),w.appendChild(K),g.appendChild(w),g}var pn="persona-chat-history",ta=30*1e3,Ws=e=>!e||typeof e!="object"?{}:{...e},ui=e=>e.map(n=>({...n,streaming:!1})),pi=(e,n)=>{let o=e!=null&&e.markdown?An(e.markdown):null;return t=>{var i,a,d;let r=(i=t.text)!=null?i:"",s=(a=t.message.rawContent)!=null?a:null;if(n){let u=n.process({text:r,raw:s!=null?s:r,message:t.message,streaming:t.streaming});u!==null&&(r=u.text,u.persist||(t.message.__skipPersist=!0))}return e!=null&&e.postprocessMessage?e.postprocessMessage({...t,text:r,raw:(d=s!=null?s:t.text)!=null?d:""}):o?o(r):Nn(r)}},rs=(e,n,o)=>{var Is,Rs,Fs,$s,Os,Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=Gn(n),r=kn.getForInstance(t.plugins);t.components&&cn.registerAll(t.components);let s=ai(),i=(Is=t.storageAdapter)!=null?Is:Qn(),a={},d=null;if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l;else if(l){let c=l;c.metadata&&(a=Ws(c.metadata)),(Rs=c.messages)!=null&&Rs.length&&(t={...t,initialMessages:c.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let u=()=>a,f=l=>{var A;a=(A=l({...a}))!=null?A:{},hn()},g=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Ln],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick],w=Pn({parsers:g,handlers:m,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=($s=(Fs=t.launcher)==null?void 0:Fs.enabled)!=null?$s:!0,F=(Ns=(Os=t.launcher)==null?void 0:Os.autoExpand)!=null?Ns:!1,T=F,y=h,S=(Ds=(js=t.layout)==null?void 0:js.header)==null?void 0:Ds.layout,I=h?F:!0,v=pi(t,w),N=(qs=(_s=t.features)==null?void 0:_s.showReasoning)!=null?qs:!0,C=(zs=(Us=t.features)==null?void 0:Us.showToolCalls)!=null?zs:!0,k={onCopy:l=>{var c,A;s.emit("message:copy",l),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(l.id,"copy").catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",P)}),(A=(c=t.messageActions)==null?void 0:c.onCopy)==null||A.call(c,l)},onFeedback:l=>{var c,A;s.emit("message:feedback",l),R!=null&&R.isClientTokenMode()&&R.submitMessageFeedback(l.messageId,l.type).catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",P)}),(A=(c=t.messageActions)==null?void 0:c.onFeedback)==null||A.call(c,l)}},K=(Js=t.statusIndicator)!=null?Js:{},J=l=>{var c,A,P,b;return l==="idle"?(c=K.idleText)!=null?c:gt.idle:l==="connecting"?(A=K.connectingText)!=null?A:gt.connecting:l==="connected"?(P=K.connectedText)!=null?P:gt.connected:l==="error"?(b=K.errorText)!=null?b:gt.error:gt[l]},{wrapper:z,panel:_}=Zr(t),j=ei(t,h),{container:Y,body:H,messagesWrapper:V,suggestions:Pe,textarea:X,sendButton:D,sendButtonWrapper:tt,composerForm:at,statusText:lt,introTitle:Lt,introSubtitle:Ft,closeButton:q,iconHolder:we,headerTitle:dt,headerSubtitle:ct,header:ze,footer:ut,actionsRow:$t,leftActions:Pt,rightActions:Ht}=j,$=j.micButton,Ne=j.micButtonWrapper,me=j.attachmentButton,nt=j.attachmentButtonWrapper,he=j.attachmentInput,st=j.attachmentPreviewsContainer,Te=null;(Ys=t.attachments)!=null&&Ys.enabled&&he&&st&&(Te=Qt.fromConfig(t.attachments),Te.setPreviewsContainer(st),he.addEventListener("change",l=>{let c=l.target;Te==null||Te.handleFileSelect(c.files),c.value=""}));let xt=r.find(l=>l.renderHeader);if(xt!=null&&xt.renderHeader){let l=xt.renderHeader({config:t,defaultRenderer:()=>{let c=qt({config:t,showClose:h});return Zt(Y,c,t),c.header},onClose:()=>E(!1,"user")});if(l){let c=Y.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),ze=l)}}let St=r.find(l=>l.renderComposer);if(St!=null&&St.renderComposer){let l=St.renderComposer({config:t,defaultRenderer:()=>rn({config:t}).footer,onSubmit:c=>{R&&!R.isStreaming()&&R.sendMessage(c)},disabled:!1});l&&(ut.replaceWith(l),ut=l)}(()=>{var P,b;let l=(b=(P=t.layout)==null?void 0:P.slots)!=null?b:{},c=Q=>{switch(Q){case"body-top":return Y.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return V;case"footer-top":return Pe;case"composer":return at;case"footer-bottom":return lt;default:return null}},A=(Q,ue)=>{var M;switch(Q){case"header-left":case"header-center":case"header-right":if(Q==="header-left")ze.insertBefore(ue,ze.firstChild);else if(Q==="header-right")ze.appendChild(ue);else{let G=ze.querySelector(".tvw-flex-col");G?(M=G.parentNode)==null||M.insertBefore(ue,G.nextSibling):ze.appendChild(ue)}break;case"body-top":{let G=H.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(ue):H.insertBefore(ue,H.firstChild);break}case"body-bottom":H.appendChild(ue);break;case"footer-top":Pe.replaceWith(ue);break;case"footer-bottom":lt.replaceWith(ue);break;default:break}};for(let[Q,ue]of Object.entries(l))if(ue)try{let M=ue({config:t,defaultContent:()=>c(Q)});M&&A(Q,M)}catch(M){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${Q}":`,M)}})();let Je=l=>{let A=l.target.closest('button[data-expand-header="true"]');if(!A)return;let P=A.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!P)return;let b=P.getAttribute("data-message-id");if(!b)return;let Q=A.getAttribute("data-bubble-type");Q==="reasoning"?(ln.has(b)?ln.delete(b):ln.add(b),si(b,P)):Q==="tool"&&(dn.has(b)?dn.delete(b):dn.add(b),oi(b,P,t))};V.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),V.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),_.appendChild(Y),e.appendChild(z);let Qe=()=>{var pe,_e,qe,rt,Tt,ee,Ee,Kt,Vt,In,Rn,us,Ue,Fn,fn,wn;let l=(_e=(pe=t.launcher)==null?void 0:pe.sidebarMode)!=null?_e:!1,c=l||((rt=(qe=t.launcher)==null?void 0:qe.fullHeight)!=null?rt:!1),A=(Tt=t.theme)!=null?Tt:{},P=(Ee=(ee=t.launcher)==null?void 0:ee.position)!=null?Ee:"bottom-left",b=P==="bottom-left"||P==="top-left",Q=l?"none":"1px solid var(--tvw-cw-border)",ue=l?b?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",M=l?"0":"16px",G=(Kt=A.panelBorder)!=null?Kt:Q,Z=(Vt=A.panelShadow)!=null?Vt:ue,ve=(In=A.panelBorderRadius)!=null?In:M;e.style.cssText="",z.style.cssText="",_.style.cssText="",Y.style.cssText="",H.style.cssText="",ut.style.cssText="";let O=(us=(Rn=t==null?void 0:t.launcher)==null?void 0:Rn.width)!=null?us:t==null?void 0:t.launcherWidth,Fe=O!=null?O:"min(400px, calc(100vw - 24px))";l||(_.style.width=Fe,_.style.maxWidth=Fe),_.style.boxShadow=Z,_.style.borderRadius=ve,Y.style.border=G,Y.style.borderRadius=ve;let Ae=((Ue=t.launcher)==null?void 0:Ue.enabled)===!1;if(c&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.height="100%",Ae&&(z.style.overflow="hidden"),_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.height="100%",_.style.overflow="hidden",Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.overflow="hidden",H.style.flex="1 1 0%",H.style.minHeight="0",H.style.overflowY="auto",ut.style.flexShrink="0"),z.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!Ae&&((Fn=kt[P])!=null?Fn:kt["bottom-right"]).split(" ").forEach(yn=>z.classList.add(yn)),l){let zt=(wn=(fn=t.launcher)==null?void 0:fn.sidebarWidth)!=null?wn:"420px";z.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
@@ -57,7 +57,7 @@
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!Ae){let zt="max-height: -moz-available !important; max-height: stretch !important;",wn=l?"":"padding-top: 1.25em !important;";z.style.cssText+=zt+wn}};Qe(),Kn(e,t);let He=[],Ye=null,Wt=()=>{Ye&&(Ye(),Ye=null),t.colorScheme==="auto"&&(Ye=Xr(()=>{Kn(e,t)}))};Wt(),He.push(()=>{Ye&&(Ye(),Ye=null)});let ft=oi(Pe),ot=null,R,wt=!1,yt=!0,At=0,te=0,ye=null,Re=!1,vt=0,Ze=!1,Bt=125,It=2e3,Ot=5,tn=50,Nt=new Map,ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},pn=(Ks=(Ys=t.voiceRecognition)==null?void 0:Ys.autoResume)!=null?Ks:!1,gn=l=>{s.emit("voice:state",{active:ke.active,source:l,timestamp:Date.now()})},jt=()=>{f(l=>({...l,voiceState:{active:ke.active,timestamp:Date.now(),manuallyDeactivated:ke.manuallyDeactivated}}))},Pn=()=>{var P,b;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let l=Es(a.voiceState),c=!!l.active,A=Number((b=l.timestamp)!=null?b:0);ke.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-A<Zi&&setTimeout(()=>{ke.active||(ke.manuallyDeactivated=!1,De("restore"))},1e3)},Hn=()=>R?ci(R.getMessages()).filter(l=>!l.__skipPersist):[];function mn(l){if(!(i!=null&&i.save))return;let A={messages:l?ci(l):R?Hn():[],metadata:a};try{let P=i.save(A);P instanceof Promise&&P.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)})}catch(P){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)}}let Yt=(l=!1)=>{if(!yt)return;let c=Date.now();Re&&c<vt&&!l||(Re&&c>=vt&&(Re=!1),!(!l&&!wt)&&(c-te<Bt||(te=c,ye&&cancelAnimationFrame(ye),ye=requestAnimationFrame(()=>{Re||!yt||(Ze=!0,H.scrollTop=H.scrollHeight,At=H.scrollTop,requestAnimationFrame(()=>{Ze=!1}),ye=null)}))))},L=null,le=()=>z.querySelector("#persona-scroll-container")||H,Se=(l,c=500)=>{let A=l.scrollTop,P=l.clientHeight,b=l.scrollHeight,Q=b-A;if(A+P>=b-2||Math.abs(Q)<5)return;L!==null&&(cancelAnimationFrame(L),L=null);let T=performance.now(),G=ve=>1-Math.pow(1-ve,3),Z=ve=>{let O=l.scrollHeight;O!==b&&(b=O,Q=b-A);let Fe=ve-T,Ae=Math.min(Fe/c,1),pe=G(Ae),_e=A+Q*pe;l.scrollTop=_e,Ae<1?L=requestAnimationFrame(Z):(l.scrollTop=l.scrollHeight,L=null)};L=requestAnimationFrame(Z)},je=l=>{let c=new Map;l.forEach(A=>{let P=Nt.get(A.id);c.set(A.id,{streaming:A.streaming,role:A.role}),!P&&A.role==="assistant"&&s.emit("assistant:message",A),A.role==="assistant"&&(P!=null&&P.streaming)&&A.streaming===!1&&s.emit("assistant:complete",A)}),Nt.clear(),c.forEach((A,P)=>{Nt.set(P,A)})},Ke=(l,c,A)=>{let P=document.createElement("div");c.forEach(T=>{var Fe,Ae;let G=null,Z=r.find(pe=>!!(T.variant==="reasoning"&&pe.renderReasoning||T.variant==="tool"&&pe.renderToolCall||!T.variant&&pe.renderMessage)),ve=(Fe=t.layout)==null?void 0:Fe.messages;if(Z)if(T.variant==="reasoning"&&T.reasoning&&Z.renderReasoning){if(!N)return;G=Z.renderReasoning({message:T,defaultRenderer:()=>vs(T),config:t})}else if(T.variant==="tool"&&T.toolCall&&Z.renderToolCall){if(!C)return;G=Z.renderToolCall({message:T,defaultRenderer:()=>bs(T,t),config:t})}else Z.renderMessage&&(G=Z.renderMessage({message:T,defaultRenderer:()=>{let pe=rn(T,A,ve,t.messageActions,k);return T.role!=="user"&&Cs(pe,T,t,R),pe},config:t}));if(!G&&T.role==="assistant"&&!T.variant&&t.enableComponentStreaming!==!1&&es(T)){let _e=ts(T);if(_e){let qe=Zn(_e,{config:t,message:T,transform:A});if(qe){let rt=document.createElement("div");if(rt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),rt.id=`bubble-${T.id}`,rt.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=A({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),rt.appendChild(Tt)}rt.appendChild(qe),G=rt}}}if(!G)if(T.variant==="reasoning"&&T.reasoning){if(!N)return;G=vs(T)}else if(T.variant==="tool"&&T.toolCall){if(!C)return;G=bs(T,t)}else{let pe=(Ae=t.layout)==null?void 0:Ae.messages;pe!=null&&pe.renderUserMessage&&T.role==="user"?G=pe.renderUserMessage({message:T,config:t,streaming:!!T.streaming}):pe!=null&&pe.renderAssistantMessage&&T.role==="assistant"?G=pe.renderAssistantMessage({message:T,config:t,streaming:!!T.streaming}):G=rn(T,A,pe,t.messageActions,k),T.role!=="user"&&G&&Cs(G,T,t,R)}let O=document.createElement("div");O.className="tvw-flex",O.id=`wrapper-${T.id}`,O.setAttribute("data-wrapper-id",T.id),T.role==="user"&&O.classList.add("tvw-justify-end"),O.appendChild(G),P.appendChild(O)});let b=c.some(T=>T.role==="assistant"&&T.streaming),Q=c[c.length-1],ue=(Q==null?void 0:Q.role)==="assistant"&&!Q.streaming;if(wt&&c.some(T=>T.role==="user")&&!b&&!ue){let T=En(),G=document.createElement("div");G.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),G.setAttribute("data-typing-indicator","true"),G.appendChild(T);let Z=document.createElement("div");Z.className="tvw-flex",Z.id="wrapper-typing-indicator",Z.setAttribute("data-wrapper-id","typing-indicator"),Z.appendChild(G),P.appendChild(Z)}Gr(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let T=le();Se(T)})})},Le=()=>{h&&(I?(z.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-95","tvw-opacity-0"),_.classList.add("tvw-scale-100","tvw-opacity-100"),se?se.element.style.display="none":de&&(de.style.display="none")):(z.classList.add("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-100","tvw-opacity-100"),_.classList.add("tvw-scale-95","tvw-opacity-0"),se?se.element.style.display="":de&&(de.style.display="")))},M=(l,c="user")=>{if(!h||I===l)return;let A=I;I=l,Le(),I&&(mt(),Yt(!0));let P={open:I,source:c,timestamp:Date.now()};I&&!A?s.emit("widget:opened",P):!I&&A&&s.emit("widget:closed",P),s.emit("widget:state",{open:I,launcherEnabled:h,voiceActive:ke.active,streaming:R.isStreaming()})},bt=l=>{D.disabled=l,$&&($.disabled=l),ft.buttons.forEach(c=>{c.disabled=l})},oe=()=>{var b,Q,ue,T,G,Z,ve,O,Fe,Ae,pe,_e,qe,rt;Lt.textContent=(Q=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?Q:"Hello \u{1F44B}",Ft.textContent=(T=(ue=t.copy)==null?void 0:ue.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",V.placeholder=(Z=(G=t.copy)==null?void 0:G.inputPlaceholder)!=null?Z:"How can I help...",((O=(ve=t.sendButton)==null?void 0:ve.useIcon)!=null?O:!1)||(D.textContent=(Ae=(Fe=t.copy)==null?void 0:Fe.sendButtonLabel)!=null?Ae:"Send");let c=(_e=(pe=t.theme)==null?void 0:pe.inputFontFamily)!=null?_e:"sans-serif",A=(rt=(qe=t.theme)==null?void 0:qe.inputFontWeight)!=null?rt:"400",P=Tt=>{switch(Tt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};V.style.fontFamily=P(c),V.style.fontWeight=A};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(c=>({...c,session_id:l}))}}),R=new nn(t,{onMessagesChanged(l){Ke(X,l,v),R&&(l.some(P=>P.role==="user")?ft.render([],R,V,l):ft.render(t.suggestionChips,R,V,l,t.suggestionChipsConfig)),Yt(!wt),je(l);let c=[...l].reverse().find(A=>A.role==="user");ke.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),mn(l)},onStatusChanged(l){var P;let c=(P=t.statusIndicator)!=null?P:{},A=b=>{var Q,ue,T,G;return b==="idle"?(Q=c.idleText)!=null?Q:gt.idle:b==="connecting"?(ue=c.connectingText)!=null?ue:gt.connecting:b==="connected"?(T=c.connectedText)!=null?T:gt.connected:b==="error"?(G=c.errorText)!=null?G:gt.error:gt[b]};lt.textContent=A(l)},onStreamingChanged(l){wt=l,bt(l),R&&Ke(X,R.getMessages(),v),l||Yt(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=Es(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&R.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let B=l=>{var b;l.preventDefault();let c=V.value.trim(),A=(b=Te==null?void 0:Te.hasAttachments())!=null?b:!1;if(!c&&!A)return;let P;A&&(P=[],P.push(...Te.getContentParts()),c&&P.push(zn(c))),V.value="",V.style.height="auto",R.sendMessage(c,{contentParts:P}),A&&Te.clearAttachments()},E=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),D.click())},U=null,fe=!1,Me=null,Xe=null,Ie=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,De=(l="user")=>{var Q,ue,T,G;if(fe||R.isStreaming())return;let c=Ie();if(!c)return;U=new c;let P=(ue=((Q=t.voiceRecognition)!=null?Q:{}).pauseDuration)!=null?ue:2e3;U.continuous=!0,U.interimResults=!0,U.lang="en-US";let b=V.value;U.onresult=Z=>{let ve="",O="";for(let Ae=0;Ae<Z.results.length;Ae++){let pe=Z.results[Ae],_e=pe[0].transcript;pe.isFinal?ve+=_e+" ":O=_e}let Fe=b+ve+O;V.value=Fe,Me&&clearTimeout(Me),(ve||O)&&(Me=window.setTimeout(()=>{let Ae=V.value.trim();Ae&&U&&fe&&(We(),V.value="",V.style.height="auto",R.sendMessage(Ae,{viaVoice:!0}))},P))},U.onerror=Z=>{Z.error!=="no-speech"&&We()},U.onend=()=>{if(fe){let Z=V.value.trim();Z&&Z!==b.trim()&&(V.value="",V.style.height="auto",R.sendMessage(Z,{viaVoice:!0})),We()}};try{if(U.start(),fe=!0,ke.active=!0,l!=="system"&&(ke.manuallyDeactivated=!1),gn(l),jt(),$){Xe={backgroundColor:$.style.backgroundColor,color:$.style.color,borderColor:$.style.borderColor};let Z=(T=t.voiceRecognition)!=null?T:{},ve=(G=Z.recordingBackgroundColor)!=null?G:"#ef4444",O=Z.recordingIconColor,Fe=Z.recordingBorderColor;if($.classList.add("tvw-voice-recording"),$.style.backgroundColor=ve,O){$.style.color=O;let Ae=$.querySelector("svg");Ae&&Ae.setAttribute("stroke",O)}Fe&&($.style.borderColor=Fe),$.setAttribute("aria-label","Stop voice recognition")}}catch{We("system")}},We=(l="user")=>{if(fe){if(fe=!1,Me&&(clearTimeout(Me),Me=null),U){try{U.stop()}catch{}U=null}if(ke.active=!1,gn(l),jt(),$){if($.classList.remove("tvw-voice-recording"),Xe){$.style.backgroundColor=Xe.backgroundColor,$.style.color=Xe.color,$.style.borderColor=Xe.borderColor;let c=$.querySelector("svg");c&&c.setAttribute("stroke",Xe.color||"currentColor"),Xe=null}$.setAttribute("aria-label","Start voice recognition")}}},Ce=(l,c)=>{var _e,qe,rt,Tt,ee,Ee,Kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=p("div","tvw-send-button-wrapper"),b=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");b.type="button",b.setAttribute("aria-label","Start voice recognition");let Q=(_e=l==null?void 0:l.iconName)!=null?_e:"mic",ue=(qe=c==null?void 0:c.size)!=null?qe:"40px",T=(rt=l==null?void 0:l.iconSize)!=null?rt:ue,G=parseFloat(T)||24,Z=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,ve=(ee=l==null?void 0:l.iconColor)!=null?ee:c==null?void 0:c.textColor;b.style.width=T,b.style.height=T,b.style.minWidth=T,b.style.minHeight=T,b.style.fontSize="18px",b.style.lineHeight="1";let O=ve||"currentColor",Fe=re(Q,G,O,1.5);Fe?(b.appendChild(Fe),b.style.color=O):(b.textContent="\u{1F3A4}",b.style.color=O),Z?b.style.backgroundColor=Z:b.classList.add("tvw-bg-cw-primary"),ve?b.style.color=ve:!ve&&!(c!=null&&c.textColor)&&b.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(b.style.borderWidth=l.borderWidth,b.style.borderStyle="solid"),l!=null&&l.borderColor&&(b.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(b.style.paddingLeft=l.paddingX,b.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(b.style.paddingTop=l.paddingY,b.style.paddingBottom=l.paddingY),P.appendChild(b);let Ae=(Ee=l==null?void 0:l.tooltipText)!=null?Ee:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&Ae){let Xt=p("div","tvw-send-button-tooltip");Xt.textContent=Ae,P.appendChild(Xt)}return{micButton:b,micButtonWrapper:P}},xe=()=>{if(fe){let l=V.value.trim();ke.manuallyDeactivated=!0,jt(),We("user"),l&&(V.value="",V.style.height="auto",R.sendMessage(l))}else ke.manuallyDeactivated=!1,jt(),De("user")};$&&($.addEventListener("click",xe),He.push(()=>{We("system"),$&&$.removeEventListener("click",xe)}));let Ve=s.on("assistant:complete",()=>{pn&&(ke.active||ke.manuallyDeactivated||pn==="assistant"&&!ke.lastUserMessageWasVoice||setTimeout(()=>{!ke.active&&!ke.manuallyDeactivated&&De("auto")},600))});He.push(Ve);let ce=()=>{M(!I,"user")},se=null,de=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>Mn(t,ce).element,onToggle:ce});c&&(de=c)}de||(se=Mn(t,ce))}se?e.appendChild(se.element):de&&e.appendChild(de),Le(),ft.render(t.suggestionChips,R,V,void 0,t.suggestionChipsConfig),oe(),bt(R.isStreaming()),Yt(!0),Pn();let mt=()=>{var A,P,b,Q,ue,T,G,Z;let l=(P=(A=t.launcher)==null?void 0:A.sidebarMode)!=null?P:!1,c=l||((Q=(b=t.launcher)==null?void 0:b.fullHeight)!=null?Q:!1);if(!h){_.style.height="",_.style.width="";return}if(!l){let ve=(T=(ue=t==null?void 0:t.launcher)==null?void 0:ue.width)!=null?T:t==null?void 0:t.launcherWidth,O=ve!=null?ve:"min(400px, calc(100vw - 24px))";_.style.width=O,_.style.maxWidth=O}if(!c){let ve=window.innerHeight,O=64,Fe=(Z=(G=t.launcher)==null?void 0:G.heightOffset)!=null?Z:0,Ae=Math.max(200,ve-O),pe=Math.min(640,Ae),_e=Math.max(200,pe-Fe);_.style.height=`${_e}px`}};mt(),window.addEventListener("resize",mt),He.push(()=>window.removeEventListener("resize",mt)),At=H.scrollTop;let Ps=()=>{let l=H.scrollTop,c=H.scrollHeight,A=H.clientHeight,P=c-l-A,b=Math.abs(l-At);if(At=l,!Ze&&!(b<=Ot)){if(!yt&&P<tn){Re=!1,yt=!0;return}yt&&P>tn&&(Re=!0,vt=Date.now()+It,yt=!1)}};H.addEventListener("scroll",Ps,{passive:!0}),He.push(()=>H.removeEventListener("scroll",Ps)),He.push(()=>{ye&&cancelAnimationFrame(ye)});let Hs=()=>{q&&(ot&&(q.removeEventListener("click",ot),ot=null),h?(q.style.display="",ot=()=>{I=!1,Le()},q.addEventListener("click",ot)):q.style.display="none")};Hs(),(()=>{let{clearChatButton:l}=j;l&&l.addEventListener("click",()=>{R.clearMessages();try{localStorage.removeItem(un),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${un}`)}catch(A){console.error("[AgentWidget] Failed to clear default localStorage:",A)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==un)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(A){console.error("[AgentWidget] Failed to clear custom localStorage:",A)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let A=i.clear();A instanceof Promise&&A.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",P)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)}a={},w.syncFromMetadata()})})(),at.addEventListener("submit",B),V.addEventListener("keydown",E),He.push(()=>{at.removeEventListener("submit",B),V.removeEventListener("keydown",E)}),He.push(()=>{R.cancel()}),se?He.push(()=>{se==null||se.destroy()}):de&&He.push(()=>{de==null||de.remove()});let Dt={update(l){var Vs,Gs,Qs,Zs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Mo,Eo,Wo,ko,Lo,Po,Ho,Bo,Io,Ro,Fo,$o,Oo,No,jo,Do,_o,qo,Uo,zo,Jo,Yo,Ko,Xo,Vo,Go,Qo,Zo,er,tr,nr,sr,or,rr,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar;let c=t.toolCall,A=t.colorScheme;t={...t,...l},Qe(),Kn(e,t),t.colorScheme!==A&&Wt();let P=Wn.getForInstance(t.plugins);if(r.length=0,r.push(...P),h=(Gs=(Vs=t.launcher)==null?void 0:Vs.enabled)!=null?Gs:!0,F=(Zs=(Qs=t.launcher)==null?void 0:Qs.autoExpand)!=null?Zs:!1,N=(to=(eo=t.features)==null?void 0:eo.showReasoning)!=null?to:!0,C=(so=(no=t.features)==null?void 0:no.showToolCalls)!=null?so:!0,((oo=t.launcher)==null?void 0:oo.enabled)===!1&&se&&(se.destroy(),se=null),((ro=t.launcher)==null?void 0:ro.enabled)===!1&&de&&(de.remove(),de=null),((io=t.launcher)==null?void 0:io.enabled)!==!1&&!se&&!de){let x=r.find(ge=>ge.renderLauncher);if(x!=null&&x.renderLauncher){let ge=x.renderLauncher({config:t,defaultRenderer:()=>Mn(t,ce).element,onToggle:ce});ge&&(de=ge,e.appendChild(de))}de||(se=Mn(t,ce),e.appendChild(se.element))}se&&se.update(t),dt&&((ao=t.launcher)==null?void 0:ao.title)!==void 0&&(dt.textContent=t.launcher.title),ct&&((lo=t.launcher)==null?void 0:lo.subtitle)!==void 0&&(ct.textContent=t.launcher.subtitle);let b=(co=t.layout)==null?void 0:co.header;if((b==null?void 0:b.layout)!==S&&ze){let x=b?sn(t,b,{showClose:h,onClose:()=>M(!1,"user")}):qt({config:t,showClose:h,onClose:()=>M(!1,"user")});ze.replaceWith(x.header),ze=x.header,we=x.iconHolder,dt=x.headerTitle,ct=x.headerSubtitle,q=x.closeButton,S=b==null?void 0:b.layout}else if(b&&(we&&(we.style.display=b.showIcon===!1?"none":""),dt&&(dt.style.display=b.showTitle===!1?"none":""),ct&&(ct.style.display=b.showSubtitle===!1?"none":""),q&&(q.style.display=b.showCloseButton===!1?"none":""),j.clearChatButtonWrapper)){let x=b.showClearChat;if(x!==void 0){j.clearChatButtonWrapper.style.display=x?"":"none";let{closeButtonWrapper:ge}=j;ge&&!ge.classList.contains("tvw-absolute")&&(x?ge.classList.remove("tvw-ml-auto"):ge.classList.add("tvw-ml-auto"))}}let ue=((uo=t.layout)==null?void 0:uo.showHeader)!==!1;ze&&(ze.style.display=ue?"":"none");let T=((po=t.layout)==null?void 0:po.showFooter)!==!1;ut&&(ut.style.display=T?"":"none"),h!==y?h?M(F,"auto"):(I=!0,Le()):F!==W&&M(F,"auto"),W=F,y=h,mt(),Hs(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&R&&Ke(X,R.getMessages(),v);let O=(go=t.launcher)!=null?go:{},Fe=(mo=O.headerIconHidden)!=null?mo:!1,Ae=(fo=(ho=t.layout)==null?void 0:ho.header)==null?void 0:fo.showIcon,pe=Fe||Ae===!1,_e=O.headerIconName,qe=(wo=O.headerIconSize)!=null?wo:"48px";if(we){let x=Y.querySelector(".tvw-border-b-cw-divider"),ge=x==null?void 0:x.querySelector(".tvw-flex-col");if(pe)we.style.display="none",x&&ge&&!x.contains(ge)&&x.insertBefore(ge,x.firstChild);else{if(we.style.display="",we.style.height=qe,we.style.width=qe,x&&ge&&(x.contains(we)?we.nextSibling!==ge&&(we.remove(),x.insertBefore(we,ge)):x.insertBefore(we,ge)),_e){let ne=parseFloat(qe)||24,be=re(_e,ne*.6,"#ffffff",2);be?we.replaceChildren(be):we.textContent=(yo=O.agentIconText)!=null?yo:"\u{1F4AC}"}else if(O.iconUrl){let ne=we.querySelector("img");if(ne)ne.src=O.iconUrl,ne.style.height=qe,ne.style.width=qe;else{let be=document.createElement("img");be.src=O.iconUrl,be.alt="",be.className="tvw-rounded-xl tvw-object-cover",be.style.height=qe,be.style.width=qe,we.replaceChildren(be)}}else{let ne=we.querySelector("svg"),be=we.querySelector("img");(ne||be)&&we.replaceChildren(),we.textContent=(vo=O.agentIconText)!=null?vo:"\u{1F4AC}"}let $e=we.querySelector("img");$e&&($e.style.height=qe,$e.style.width=qe)}}let rt=(Co=(bo=t.layout)==null?void 0:bo.header)==null?void 0:Co.showTitle,Tt=(So=(xo=t.layout)==null?void 0:xo.header)==null?void 0:So.showSubtitle;if(dt&&(dt.style.display=rt===!1?"none":""),ct&&(ct.style.display=Tt===!1?"none":""),q){((To=(Ao=t.layout)==null?void 0:Ao.header)==null?void 0:To.showCloseButton)===!1?q.style.display="none":q.style.display="";let ge=(Mo=O.closeButtonSize)!=null?Mo:"32px",$e=(Eo=O.closeButtonPlacement)!=null?Eo:"inline";q.style.height=ge,q.style.width=ge;let{closeButtonWrapper:ne}=j,be=$e==="top-right",pt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&be!==pt)if(ne.remove(),be)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(ne);else{let ie=(ko=(Wo=O.clearChat)==null?void 0:Wo.placement)!=null?ko:"inline",Ge=(Po=(Lo=O.clearChat)==null?void 0:Lo.enabled)!=null?Po:!0;ne.className=Ge&&ie==="inline"?"":"tvw-ml-auto";let Ct=Y.querySelector(".tvw-border-b-cw-divider");Ct&&Ct.appendChild(ne)}if(O.closeButtonColor?(q.style.color=O.closeButtonColor,q.classList.remove("tvw-text-cw-muted")):(q.style.color="",q.classList.add("tvw-text-cw-muted")),O.closeButtonBackgroundColor?(q.style.backgroundColor=O.closeButtonBackgroundColor,q.classList.remove("hover:tvw-bg-gray-100")):(q.style.backgroundColor="",q.classList.add("hover:tvw-bg-gray-100")),O.closeButtonBorderWidth||O.closeButtonBorderColor){let ie=O.closeButtonBorderWidth||"0px",Ge=O.closeButtonBorderColor||"transparent";q.style.border=`${ie} solid ${Ge}`,q.classList.remove("tvw-border-none")}else q.style.border="",q.classList.add("tvw-border-none");O.closeButtonBorderRadius?(q.style.borderRadius=O.closeButtonBorderRadius,q.classList.remove("tvw-rounded-full")):(q.style.borderRadius="",q.classList.add("tvw-rounded-full")),O.closeButtonPaddingX?(q.style.paddingLeft=O.closeButtonPaddingX,q.style.paddingRight=O.closeButtonPaddingX):(q.style.paddingLeft="",q.style.paddingRight=""),O.closeButtonPaddingY?(q.style.paddingTop=O.closeButtonPaddingY,q.style.paddingBottom=O.closeButtonPaddingY):(q.style.paddingTop="",q.style.paddingBottom="");let it=(Ho=O.closeButtonIconName)!=null?Ho:"x",Mt=(Bo=O.closeButtonIconText)!=null?Bo:"\xD7";q.innerHTML="";let ht=re(it,"20px",O.closeButtonColor||"",2);ht?q.appendChild(ht):q.textContent=Mt;let Oe=(Io=O.closeButtonTooltipText)!=null?Io:"Close chat",Et=(Ro=O.closeButtonShowTooltip)!=null?Ro:!0;if(q.setAttribute("aria-label",Oe),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),Et&&Oe)){let ie=null,Ge=()=>{if(ie||!q)return;ie=p("div","tvw-clear-chat-tooltip"),ie.textContent=Oe;let Cn=p("div");Cn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(Cn);let Vt=q.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Vt.left+Vt.width/2}px`,ie.style.top=`${Vt.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};ne.addEventListener("mouseenter",Ge),ne.addEventListener("mouseleave",Ct),q.addEventListener("focus",Ge),q.addEventListener("blur",Ct),ne._cleanupTooltip=()=>{Ct(),ne&&(ne.removeEventListener("mouseenter",Ge),ne.removeEventListener("mouseleave",Ct)),q&&(q.removeEventListener("focus",Ge),q.removeEventListener("blur",Ct))}}}let{clearChatButton:ee,clearChatButtonWrapper:Ee}=j;if(ee){let x=(Fo=O.clearChat)!=null?Fo:{},ge=($o=x.enabled)!=null?$o:!0,$e=(No=(Oo=t.layout)==null?void 0:Oo.header)==null?void 0:No.showClearChat,ne=$e!==void 0?$e:ge,be=(jo=x.placement)!=null?jo:"inline";if(Ee){Ee.style.display=ne?"":"none";let{closeButtonWrapper:pt}=j;pt&&!pt.classList.contains("tvw-absolute")&&(ne?pt.classList.remove("tvw-ml-auto"):pt.classList.add("tvw-ml-auto"));let it=be==="top-right",Mt=Ee.classList.contains("tvw-absolute");if(it!==Mt&&ne){if(Ee.remove(),it)Ee.className="tvw-absolute tvw-top-4 tvw-z-50",Ee.style.right="48px",Y.style.position="relative",Y.appendChild(Ee);else{Ee.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Ee.style.right="";let Oe=Y.querySelector(".tvw-border-b-cw-divider"),Et=j.closeButtonWrapper;Oe&&Et&&Et.parentElement===Oe?Oe.insertBefore(Ee,Et):Oe&&Oe.appendChild(Ee)}let ht=j.closeButtonWrapper;ht&&!ht.classList.contains("tvw-absolute")&&(it?ht.classList.add("tvw-ml-auto"):ht.classList.remove("tvw-ml-auto"))}}if(ne){let pt=(Do=x.size)!=null?Do:"32px";ee.style.height=pt,ee.style.width=pt;let it=(_o=x.iconName)!=null?_o:"refresh-cw",Mt=(qo=x.iconColor)!=null?qo:"";ee.innerHTML="";let ht=re(it,"20px",Mt||"",2);if(ht&&ee.appendChild(ht),Mt?(ee.style.color=Mt,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),x.backgroundColor?(ee.style.backgroundColor=x.backgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),x.borderWidth||x.borderColor){let ie=x.borderWidth||"0px",Ge=x.borderColor||"transparent";ee.style.border=`${ie} solid ${Ge}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");x.borderRadius?(ee.style.borderRadius=x.borderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),x.paddingX?(ee.style.paddingLeft=x.paddingX,ee.style.paddingRight=x.paddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),x.paddingY?(ee.style.paddingTop=x.paddingY,ee.style.paddingBottom=x.paddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let Oe=(Uo=x.tooltipText)!=null?Uo:"Clear chat",Et=(zo=x.showTooltip)!=null?zo:!0;if(ee.setAttribute("aria-label",Oe),Ee&&(Ee._cleanupTooltip&&(Ee._cleanupTooltip(),delete Ee._cleanupTooltip),Et&&Oe)){let ie=null,Ge=()=>{if(ie||!ee)return;ie=p("div","tvw-clear-chat-tooltip"),ie.textContent=Oe;let Cn=p("div");Cn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(Cn);let Vt=ee.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Vt.left+Vt.width/2}px`,ie.style.top=`${Vt.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};Ee.addEventListener("mouseenter",Ge),Ee.addEventListener("mouseleave",Ct),ee.addEventListener("focus",Ge),ee.addEventListener("blur",Ct),Ee._cleanupTooltip=()=>{Ct(),Ee&&(Ee.removeEventListener("mouseenter",Ge),Ee.removeEventListener("mouseleave",Ct)),ee&&(ee.removeEventListener("focus",Ge),ee.removeEventListener("blur",Ct))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[kn],Xt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick];w=Ln({parsers:Kt,handlers:Xt,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),v=ui(t,w),R.updateConfig(t),Ke(X,R.getMessages(),v),ft.render(t.suggestionChips,R,V,void 0,t.suggestionChipsConfig),oe(),bt(R.isStreaming());let Bn=((Jo=t.voiceRecognition)==null?void 0:Jo.enabled)===!0,In=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Bn&&In)if(!$||!Ne){let x=Ce(t.voiceRecognition,t.sendButton);x&&($=x.micButton,Ne=x.micButtonWrapper,Ht.insertBefore(Ne,tt),$.addEventListener("click",xe),$.disabled=R.isStreaming())}else{let x=(Yo=t.voiceRecognition)!=null?Yo:{},ge=(Ko=t.sendButton)!=null?Ko:{},$e=(Xo=x.iconName)!=null?Xo:"mic",ne=(Vo=ge.size)!=null?Vo:"40px",be=(Go=x.iconSize)!=null?Go:ne,pt=parseFloat(be)||24;$.style.width=be,$.style.height=be,$.style.minWidth=be,$.style.minHeight=be;let it=(Zo=(Qo=x.iconColor)!=null?Qo:ge.textColor)!=null?Zo:"currentColor";$.innerHTML="";let Mt=re($e,pt,it,2);Mt?$.appendChild(Mt):$.textContent="\u{1F3A4}";let ht=(er=x.backgroundColor)!=null?er:ge.backgroundColor;ht?($.style.backgroundColor=ht,$.classList.remove("tvw-bg-cw-primary")):($.style.backgroundColor="",$.classList.add("tvw-bg-cw-primary")),it?($.style.color=it,$.classList.remove("tvw-text-white")):!it&&!ge.textColor&&($.style.color="",$.classList.add("tvw-text-white")),x.borderWidth?($.style.borderWidth=x.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),x.borderColor?$.style.borderColor=x.borderColor:$.style.borderColor="",x.paddingX?($.style.paddingLeft=x.paddingX,$.style.paddingRight=x.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),x.paddingY?($.style.paddingTop=x.paddingY,$.style.paddingBottom=x.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let Oe=Ne==null?void 0:Ne.querySelector(".tvw-send-button-tooltip"),Et=(tr=x.tooltipText)!=null?tr:"Start voice recognition";if(((nr=x.showTooltip)!=null?nr:!1)&&Et)if(Oe)Oe.textContent=Et,Oe.style.display="";else{let Ge=document.createElement("div");Ge.className="tvw-send-button-tooltip",Ge.textContent=Et,Ne==null||Ne.insertBefore(Ge,$)}else Oe&&(Oe.style.display="none");Ne.style.display="",$.disabled=R.isStreaming()}else $&&Ne&&(Ne.style.display="none",fe&&We());if(((sr=t.attachments)==null?void 0:sr.enabled)===!0)if(!nt||!me){let x=(or=t.attachments)!=null?or:{},$e=(ir=((rr=t.sendButton)!=null?rr:{}).size)!=null?ir:"40px";st||(st=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),st.style.display="none",at.insertBefore(st,V)),he||(he=document.createElement("input"),he.type="file",he.accept=((ar=x.allowedTypes)!=null?ar:Jt).join(","),he.multiple=((lr=x.maxFiles)!=null?lr:4)>1,he.style.display="none",he.setAttribute("aria-label","Attach files"),at.insertBefore(he,V)),nt=p("div","tvw-send-button-wrapper"),me=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),me.type="button",me.setAttribute("aria-label",(dr=x.buttonTooltipText)!=null?dr:"Attach file");let ne=(cr=x.buttonIconName)!=null?cr:"paperclip",be=$e,pt=parseFloat(be)||40,it=Math.round(pt*.6);me.style.width=be,me.style.height=be,me.style.minWidth=be,me.style.minHeight=be,me.style.fontSize="18px",me.style.lineHeight="1",me.style.backgroundColor="transparent",me.style.color="var(--cw-primary, #111827)",me.style.border="none",me.style.borderRadius="6px",me.style.transition="background-color 0.15s ease",me.addEventListener("mouseenter",()=>{me.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),me.addEventListener("mouseleave",()=>{me.style.backgroundColor="transparent"});let Mt=re(ne,it,"currentColor",1.5);Mt?me.appendChild(Mt):me.textContent="\u{1F4CE}",me.addEventListener("click",Et=>{Et.preventDefault(),he==null||he.click()}),nt.appendChild(me);let ht=(ur=x.buttonTooltipText)!=null?ur:"Attach file",Oe=p("div","tvw-send-button-tooltip");Oe.textContent=ht,nt.appendChild(Oe),Pt.append(nt),!Te&&he&&st&&(Te=Qt.fromConfig(x),Te.setPreviewsContainer(st),he.addEventListener("change",async()=>{Te&&(he!=null&&he.files)&&(await Te.handleFileSelect(he.files),he.value="")}))}else{nt.style.display="";let x=(pr=t.attachments)!=null?pr:{};he&&(he.accept=((gr=x.allowedTypes)!=null?gr:Jt).join(","),he.multiple=((mr=x.maxFiles)!=null?mr:4)>1),Te&&Te.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else nt&&(nt.style.display="none"),Te&&Te.clearAttachments();let Ue=(hr=t.sendButton)!=null?hr:{},Rn=(fr=Ue.useIcon)!=null?fr:!1,hn=(wr=Ue.iconText)!=null?wr:"\u2191",fn=Ue.iconName,zt=(yr=Ue.tooltipText)!=null?yr:"Send message",wn=(vr=Ue.showTooltip)!=null?vr:!1,yn=(br=Ue.size)!=null?br:"40px",Fn=Ue.backgroundColor,Rt=Ue.textColor;if(Rn){if(D.style.width=yn,D.style.height=yn,D.style.minWidth=yn,D.style.minHeight=yn,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",fn){let x=parseFloat(yn)||24,ge=Rt&&typeof Rt=="string"&&Rt.trim()?Rt.trim():"currentColor",$e=re(fn,x,ge,2);$e?(D.appendChild($e),D.style.color=ge):(D.textContent=hn,Rt?D.style.color=Rt:D.classList.add("tvw-text-white"))}else D.textContent=hn,Rt?D.style.color=Rt:D.classList.add("tvw-text-white");D.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Fn?(D.style.backgroundColor=Fn,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(xr=(Cr=t.copy)==null?void 0:Cr.sendButtonLabel)!=null?xr:"Send",D.style.width="",D.style.height="",D.style.minWidth="",D.style.minHeight="",D.style.fontSize="",D.style.lineHeight="",D.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",Fn?(D.style.backgroundColor=Fn,D.classList.remove("tvw-bg-cw-accent")):D.classList.add("tvw-bg-cw-accent"),Rt?D.style.color=Rt:D.classList.add("tvw-text-white");Ue.borderWidth?(D.style.borderWidth=Ue.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),Ue.borderColor?D.style.borderColor=Ue.borderColor:D.style.borderColor="",Ue.paddingX?(D.style.paddingLeft=Ue.paddingX,D.style.paddingRight=Ue.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),Ue.paddingY?(D.style.paddingTop=Ue.paddingY,D.style.paddingBottom=Ue.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let vn=tt==null?void 0:tt.querySelector(".tvw-send-button-tooltip");if(wn&&zt)if(vn)vn.textContent=zt,vn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=zt,tt==null||tt.insertBefore(x,D)}else vn&&(vn.style.display="none");let bn=(Sr=t.statusIndicator)!=null?Sr:{},vi=(Ar=bn.visible)!=null?Ar:!0;if(lt.style.display=vi?"":"none",R){let x=R.getStatus(),ge=$e=>{var ne,be,pt,it;return $e==="idle"?(ne=bn.idleText)!=null?ne:gt.idle:$e==="connecting"?(be=bn.connectingText)!=null?be:gt.connecting:$e==="connected"?(pt=bn.connectedText)!=null?pt:gt.connected:$e==="error"?(it=bn.errorText)!=null?it:gt.error:gt[$e]};lt.textContent=ge(x)}},open(){h&&M(!0,"api")},close(){h&&M(!1,"api")},toggle(){h&&M(!I,"api")},clearChat(){R.clearMessages();try{localStorage.removeItem(un),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${un}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==un)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let c=i.clear();c instanceof Promise&&c.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}a={},w.syncFromMetadata()},setMessage(l){return!V||R.isStreaming()?!1:(!I&&h&&M(!0,"system"),V.value=l,V.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(R.isStreaming())return!1;let c=(l==null?void 0:l.trim())||V.value.trim();return c?(!I&&h&&M(!0,"system"),V.value="",V.style.height="auto",R.sendMessage(c),!0):!1},startVoiceRecognition(){return fe||R.isStreaming()||!Ie()?!1:(!I&&h&&M(!0,"system"),ke.manuallyDeactivated=!1,jt(),De("user"),!0)},stopVoiceRecognition(){return fe?(ke.manuallyDeactivated=!0,jt(),We("user"),!0):!1},injectMessage(l){return!I&&h&&M(!0,"system"),R.injectMessage(l)},injectAssistantMessage(l){return!I&&h&&M(!0,"system"),R.injectAssistantMessage(l)},injectUserMessage(l){return!I&&h&&M(!0,"system"),R.injectUserMessage(l)},injectSystemMessage(l){return!I&&h&&M(!0,"system"),R.injectSystemMessage(l)},injectTestMessage(l){!I&&h&&M(!0,"system"),R.injectTestEvent(l)},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){f(l)},on(l,c){return s.on(l,c)},off(l,c){s.off(l,c)},isOpen(){return h&&I},isVoiceActive(){return ke.active},getState(){return{open:h&&I,launcherEnabled:h,voiceActive:ke.active,streaming:R.isStreaming()}},showCSATFeedback(l){!I&&h&&M(!0,"system");let c=X.querySelector(".tvw-feedback-container");c&&c.remove();let A=ns({onSubmit:async(P,b)=>{var Q;R.isClientTokenMode()&&await R.submitCSATFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});X.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&h&&M(!0,"system");let c=X.querySelector(".tvw-feedback-container");c&&c.remove();let A=ss({onSubmit:async(P,b)=>{var Q;R.isClientTokenMode()&&await R.submitNPSFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});X.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return R.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return R.submitNPSFeedback(l,c)},destroy(){He.forEach(l=>l()),z.remove(),se==null||se.destroy(),de==null||de.remove(),ot&&q.removeEventListener("click",ot)}};if((((Xs=o==null?void 0:o.debugTools)!=null?Xs:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,c={controller:Dt,getMessages:Dt.getMessages,getStatus:Dt.getStatus,getMetadata:Dt.getPersistentMetadata,updateMetadata:Dt.updatePersistentMetadata,clearHistory:()=>Dt.clearChat(),setVoiceActive:A=>A?Dt.startVoiceRecognition():Dt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,He.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return Dt};var Ws={},ea=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},ta=()=>{try{if(typeof Ws!="undefined"&&Ws.url)return new URL("../widget.css",Ws.url).href}catch{}return null},pi=e=>{let n=ta(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let r=t.cloneNode(!0);e.insertBefore(r,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else o();else if(!document.head.querySelector("link[data-persona]")&&n){let r=document.createElement("link");r.rel="stylesheet",r.href=n,r.setAttribute("data-persona","true"),document.head.appendChild(r)}},ks=e=>{var u,f,g,m;let n=ea(e.target),o=document.createElement("div");o.className="persona-host";let t=(g=(f=(u=e.config)==null?void 0:u.launcher)==null?void 0:f.enabled)!=null?g:!0;t||(o.style.height="100%"),n.appendChild(o);let r=e.useShadowDom===!0,s,i;if(r){let w=o.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),pi(w)}else i=o,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),o.appendChild(s),pi(o);let a=os(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:o,destroy(){a.destroy(),o.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};function Ut(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function na(e){if(e)return{getHeaders:Ut(e.getHeaders),onFeedback:Ut(e.onFeedback),onCopy:Ut(e.onCopy),requestMiddleware:Ut(e.requestMiddleware),actionHandlers:Ut(e.actionHandlers),actionParsers:Ut(e.actionParsers),postprocessMessage:Ut(e.postprocessMessage),contextProviders:Ut(e.contextProviders),streamParser:Ut(e.streamParser)}}var gi=`({ text, message }: any) => {
60
+ `}if(!Ae){let zt="max-height: -moz-available !important; max-height: stretch !important;",yn=l?"":"padding-top: 1.25em !important;";z.style.cssText+=zt+yn}};Qe(),Vn(e,t);let He=[],Ye=null,Wt=()=>{Ye&&(Ye(),Ye=null),t.colorScheme==="auto"&&(Ye=Xr(()=>{Vn(e,t)}))};Wt(),He.push(()=>{Ye&&(Ye(),Ye=null)});let ft=ri(Pe),ot=null,R,wt=!1,yt=!0,At=0,te=0,ye=null,Re=!1,vt=0,Ze=!1,Bt=125,It=2e3,Ot=5,nn=50,Nt=new Map,ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},gn=(Vs=(Ks=t.voiceRecognition)==null?void 0:Ks.autoResume)!=null?Vs:!1,mn=l=>{s.emit("voice:state",{active:ke.active,source:l,timestamp:Date.now()})},jt=()=>{f(l=>({...l,voiceState:{active:ke.active,timestamp:Date.now(),manuallyDeactivated:ke.manuallyDeactivated}}))},Hn=()=>{var P,b;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let l=Ws(a.voiceState),c=!!l.active,A=Number((b=l.timestamp)!=null?b:0);ke.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-A<ta&&setTimeout(()=>{ke.active||(ke.manuallyDeactivated=!1,De("restore"))},1e3)},Bn=()=>R?ui(R.getMessages()).filter(l=>!l.__skipPersist):[];function hn(l){if(!(i!=null&&i.save))return;let A={messages:l?ui(l):R?Bn():[],metadata:a};try{let P=i.save(A);P instanceof Promise&&P.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)})}catch(P){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)}}let Yt=(l=!1)=>{if(!yt)return;let c=Date.now();Re&&c<vt&&!l||(Re&&c>=vt&&(Re=!1),!(!l&&!wt)&&(c-te<Bt||(te=c,ye&&cancelAnimationFrame(ye),ye=requestAnimationFrame(()=>{Re||!yt||(Ze=!0,H.scrollTop=H.scrollHeight,At=H.scrollTop,requestAnimationFrame(()=>{Ze=!1}),ye=null)}))))},L=null,le=()=>z.querySelector("#persona-scroll-container")||H,Se=(l,c=500)=>{let A=l.scrollTop,P=l.clientHeight,b=l.scrollHeight,Q=b-A;if(A+P>=b-2||Math.abs(Q)<5)return;L!==null&&(cancelAnimationFrame(L),L=null);let M=performance.now(),G=ve=>1-Math.pow(1-ve,3),Z=ve=>{let O=l.scrollHeight;O!==b&&(b=O,Q=b-A);let Fe=ve-M,Ae=Math.min(Fe/c,1),pe=G(Ae),_e=A+Q*pe;l.scrollTop=_e,Ae<1?L=requestAnimationFrame(Z):(l.scrollTop=l.scrollHeight,L=null)};L=requestAnimationFrame(Z)},je=l=>{let c=new Map;l.forEach(A=>{let P=Nt.get(A.id);c.set(A.id,{streaming:A.streaming,role:A.role}),!P&&A.role==="assistant"&&s.emit("assistant:message",A),A.role==="assistant"&&(P!=null&&P.streaming)&&A.streaming===!1&&s.emit("assistant:complete",A)}),Nt.clear(),c.forEach((A,P)=>{Nt.set(P,A)})},Ke=(l,c,A)=>{let P=document.createElement("div");c.forEach(M=>{var Fe,Ae;let G=null,Z=r.find(pe=>!!(M.variant==="reasoning"&&pe.renderReasoning||M.variant==="tool"&&pe.renderToolCall||!M.variant&&pe.renderMessage)),ve=(Fe=t.layout)==null?void 0:Fe.messages;if(Z)if(M.variant==="reasoning"&&M.reasoning&&Z.renderReasoning){if(!N)return;G=Z.renderReasoning({message:M,defaultRenderer:()=>bs(M),config:t})}else if(M.variant==="tool"&&M.toolCall&&Z.renderToolCall){if(!C)return;G=Z.renderToolCall({message:M,defaultRenderer:()=>Cs(M,t),config:t})}else Z.renderMessage&&(G=Z.renderMessage({message:M,defaultRenderer:()=>{let pe=an(M,A,ve,t.messageActions,k);return M.role!=="user"&&xs(pe,M,t,R),pe},config:t}));if(!G&&M.role==="assistant"&&!M.variant&&t.enableComponentStreaming!==!1&&ts(M)){let _e=ns(M);if(_e){let qe=es(_e,{config:t,message:M,transform:A});if(qe){let rt=document.createElement("div");if(rt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),rt.id=`bubble-${M.id}`,rt.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=A({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),rt.appendChild(Tt)}rt.appendChild(qe),G=rt}}}if(!G)if(M.variant==="reasoning"&&M.reasoning){if(!N)return;G=bs(M)}else if(M.variant==="tool"&&M.toolCall){if(!C)return;G=Cs(M,t)}else{let pe=(Ae=t.layout)==null?void 0:Ae.messages;pe!=null&&pe.renderUserMessage&&M.role==="user"?G=pe.renderUserMessage({message:M,config:t,streaming:!!M.streaming}):pe!=null&&pe.renderAssistantMessage&&M.role==="assistant"?G=pe.renderAssistantMessage({message:M,config:t,streaming:!!M.streaming}):G=an(M,A,pe,t.messageActions,k),M.role!=="user"&&G&&xs(G,M,t,R)}let O=document.createElement("div");O.className="tvw-flex",O.id=`wrapper-${M.id}`,O.setAttribute("data-wrapper-id",M.id),M.role==="user"&&O.classList.add("tvw-justify-end"),O.appendChild(G),P.appendChild(O)});let b=c.some(M=>M.role==="assistant"&&M.streaming),Q=c[c.length-1],ue=(Q==null?void 0:Q.role)==="assistant"&&!Q.streaming;if(wt&&c.some(M=>M.role==="user")&&!b&&!ue){let M=Wn(),G=document.createElement("div");G.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),G.setAttribute("data-typing-indicator","true"),G.appendChild(M);let Z=document.createElement("div");Z.className="tvw-flex",Z.id="wrapper-typing-indicator",Z.setAttribute("data-wrapper-id","typing-indicator"),Z.appendChild(G),P.appendChild(Z)}Qr(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let M=le();Se(M)})})},Le=()=>{h&&(I?(z.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-95","tvw-opacity-0"),_.classList.add("tvw-scale-100","tvw-opacity-100"),se?se.element.style.display="none":de&&(de.style.display="none")):(z.classList.add("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-100","tvw-opacity-100"),_.classList.add("tvw-scale-95","tvw-opacity-0"),se?se.element.style.display="":de&&(de.style.display="")))},E=(l,c="user")=>{if(!h||I===l)return;let A=I;I=l,Le(),I&&(mt(),Yt(!0));let P={open:I,source:c,timestamp:Date.now()};I&&!A?s.emit("widget:opened",P):!I&&A&&s.emit("widget:closed",P),s.emit("widget:state",{open:I,launcherEnabled:h,voiceActive:ke.active,streaming:R.isStreaming()})},bt=l=>{D.disabled=l,$&&($.disabled=l),ft.buttons.forEach(c=>{c.disabled=l})},oe=()=>{var b,Q,ue,M,G,Z,ve,O,Fe,Ae,pe,_e,qe,rt;Lt.textContent=(Q=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?Q:"Hello \u{1F44B}",Ft.textContent=(M=(ue=t.copy)==null?void 0:ue.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",X.placeholder=(Z=(G=t.copy)==null?void 0:G.inputPlaceholder)!=null?Z:"How can I help...",((O=(ve=t.sendButton)==null?void 0:ve.useIcon)!=null?O:!1)||(D.textContent=(Ae=(Fe=t.copy)==null?void 0:Fe.sendButtonLabel)!=null?Ae:"Send");let c=(_e=(pe=t.theme)==null?void 0:pe.inputFontFamily)!=null?_e:"sans-serif",A=(rt=(qe=t.theme)==null?void 0:qe.inputFontWeight)!=null?rt:"400",P=Tt=>{switch(Tt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};X.style.fontFamily=P(c),X.style.fontWeight=A};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(c=>({...c,session_id:l}))}}),R=new sn(t,{onMessagesChanged(l){Ke(V,l,v),R&&(l.some(P=>P.role==="user")?ft.render([],R,X,l):ft.render(t.suggestionChips,R,X,l,t.suggestionChipsConfig)),Yt(!wt),je(l);let c=[...l].reverse().find(A=>A.role==="user");ke.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),hn(l)},onStatusChanged(l){var P;let c=(P=t.statusIndicator)!=null?P:{},A=b=>{var Q,ue,M,G;return b==="idle"?(Q=c.idleText)!=null?Q:gt.idle:b==="connecting"?(ue=c.connectingText)!=null?ue:gt.connecting:b==="connected"?(M=c.connectedText)!=null?M:gt.connected:b==="error"?(G=c.errorText)!=null?G:gt.error:gt[b]};lt.textContent=A(l)},onStreamingChanged(l){wt=l,bt(l),R&&Ke(V,R.getMessages(),v),l||Yt(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=Ws(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&R.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let B=l=>{var b;l.preventDefault();let c=X.value.trim(),A=(b=Te==null?void 0:Te.hasAttachments())!=null?b:!1;if(!c&&!A)return;let P;A&&(P=[],P.push(...Te.getContentParts()),c&&P.push(Jn(c))),X.value="",X.style.height="auto",R.sendMessage(c,{contentParts:P}),A&&Te.clearAttachments()},W=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),D.click())},U=null,fe=!1,Me=null,Ve=null,Ie=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,De=(l="user")=>{var Q,ue,M,G;if(fe||R.isStreaming())return;let c=Ie();if(!c)return;U=new c;let P=(ue=((Q=t.voiceRecognition)!=null?Q:{}).pauseDuration)!=null?ue:2e3;U.continuous=!0,U.interimResults=!0,U.lang="en-US";let b=X.value;U.onresult=Z=>{let ve="",O="";for(let Ae=0;Ae<Z.results.length;Ae++){let pe=Z.results[Ae],_e=pe[0].transcript;pe.isFinal?ve+=_e+" ":O=_e}let Fe=b+ve+O;X.value=Fe,Me&&clearTimeout(Me),(ve||O)&&(Me=window.setTimeout(()=>{let Ae=X.value.trim();Ae&&U&&fe&&(We(),X.value="",X.style.height="auto",R.sendMessage(Ae,{viaVoice:!0}))},P))},U.onerror=Z=>{Z.error!=="no-speech"&&We()},U.onend=()=>{if(fe){let Z=X.value.trim();Z&&Z!==b.trim()&&(X.value="",X.style.height="auto",R.sendMessage(Z,{viaVoice:!0})),We()}};try{if(U.start(),fe=!0,ke.active=!0,l!=="system"&&(ke.manuallyDeactivated=!1),mn(l),jt(),$){Ve={backgroundColor:$.style.backgroundColor,color:$.style.color,borderColor:$.style.borderColor};let Z=(M=t.voiceRecognition)!=null?M:{},ve=(G=Z.recordingBackgroundColor)!=null?G:"#ef4444",O=Z.recordingIconColor,Fe=Z.recordingBorderColor;if($.classList.add("tvw-voice-recording"),$.style.backgroundColor=ve,O){$.style.color=O;let Ae=$.querySelector("svg");Ae&&Ae.setAttribute("stroke",O)}Fe&&($.style.borderColor=Fe),$.setAttribute("aria-label","Stop voice recognition")}}catch{We("system")}},We=(l="user")=>{if(fe){if(fe=!1,Me&&(clearTimeout(Me),Me=null),U){try{U.stop()}catch{}U=null}if(ke.active=!1,mn(l),jt(),$){if($.classList.remove("tvw-voice-recording"),Ve){$.style.backgroundColor=Ve.backgroundColor,$.style.color=Ve.color,$.style.borderColor=Ve.borderColor;let c=$.querySelector("svg");c&&c.setAttribute("stroke",Ve.color||"currentColor"),Ve=null}$.setAttribute("aria-label","Start voice recognition")}}},Ce=(l,c)=>{var _e,qe,rt,Tt,ee,Ee,Kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=p("div","tvw-send-button-wrapper"),b=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");b.type="button",b.setAttribute("aria-label","Start voice recognition");let Q=(_e=l==null?void 0:l.iconName)!=null?_e:"mic",ue=(qe=c==null?void 0:c.size)!=null?qe:"40px",M=(rt=l==null?void 0:l.iconSize)!=null?rt:ue,G=parseFloat(M)||24,Z=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,ve=(ee=l==null?void 0:l.iconColor)!=null?ee:c==null?void 0:c.textColor;b.style.width=M,b.style.height=M,b.style.minWidth=M,b.style.minHeight=M,b.style.fontSize="18px",b.style.lineHeight="1";let O=ve||"currentColor",Fe=re(Q,G,O,1.5);Fe?(b.appendChild(Fe),b.style.color=O):(b.textContent="\u{1F3A4}",b.style.color=O),Z?b.style.backgroundColor=Z:b.classList.add("tvw-bg-cw-primary"),ve?b.style.color=ve:!ve&&!(c!=null&&c.textColor)&&b.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(b.style.borderWidth=l.borderWidth,b.style.borderStyle="solid"),l!=null&&l.borderColor&&(b.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(b.style.paddingLeft=l.paddingX,b.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(b.style.paddingTop=l.paddingY,b.style.paddingBottom=l.paddingY),P.appendChild(b);let Ae=(Ee=l==null?void 0:l.tooltipText)!=null?Ee:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&Ae){let Vt=p("div","tvw-send-button-tooltip");Vt.textContent=Ae,P.appendChild(Vt)}return{micButton:b,micButtonWrapper:P}},xe=()=>{if(fe){let l=X.value.trim();ke.manuallyDeactivated=!0,jt(),We("user"),l&&(X.value="",X.style.height="auto",R.sendMessage(l))}else ke.manuallyDeactivated=!1,jt(),De("user")};$&&($.addEventListener("click",xe),He.push(()=>{We("system"),$&&$.removeEventListener("click",xe)}));let Xe=s.on("assistant:complete",()=>{gn&&(ke.active||ke.manuallyDeactivated||gn==="assistant"&&!ke.lastUserMessageWasVoice||setTimeout(()=>{!ke.active&&!ke.manuallyDeactivated&&De("auto")},600))});He.push(Xe);let ce=()=>{E(!I,"user")},se=null,de=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>En(t,ce).element,onToggle:ce});c&&(de=c)}de||(se=En(t,ce))}se?e.appendChild(se.element):de&&e.appendChild(de),Le(),ft.render(t.suggestionChips,R,X,void 0,t.suggestionChipsConfig),oe(),bt(R.isStreaming()),Yt(!0),Hn();let mt=()=>{var A,P,b,Q,ue,M,G,Z;let l=(P=(A=t.launcher)==null?void 0:A.sidebarMode)!=null?P:!1,c=l||((Q=(b=t.launcher)==null?void 0:b.fullHeight)!=null?Q:!1);if(!h){_.style.height="",_.style.width="";return}if(!l){let ve=(M=(ue=t==null?void 0:t.launcher)==null?void 0:ue.width)!=null?M:t==null?void 0:t.launcherWidth,O=ve!=null?ve:"min(400px, calc(100vw - 24px))";_.style.width=O,_.style.maxWidth=O}if(!c){let ve=window.innerHeight,O=64,Fe=(Z=(G=t.launcher)==null?void 0:G.heightOffset)!=null?Z:0,Ae=Math.max(200,ve-O),pe=Math.min(640,Ae),_e=Math.max(200,pe-Fe);_.style.height=`${_e}px`}};mt(),window.addEventListener("resize",mt),He.push(()=>window.removeEventListener("resize",mt)),At=H.scrollTop;let Hs=()=>{let l=H.scrollTop,c=H.scrollHeight,A=H.clientHeight,P=c-l-A,b=Math.abs(l-At);if(At=l,!Ze&&!(b<=Ot)){if(!yt&&P<nn){Re=!1,yt=!0;return}yt&&P>nn&&(Re=!0,vt=Date.now()+It,yt=!1)}};H.addEventListener("scroll",Hs,{passive:!0}),He.push(()=>H.removeEventListener("scroll",Hs)),He.push(()=>{ye&&cancelAnimationFrame(ye)});let Bs=()=>{q&&(ot&&(q.removeEventListener("click",ot),ot=null),h?(q.style.display="",ot=()=>{I=!1,Le()},q.addEventListener("click",ot)):q.style.display="none")};Bs(),(()=>{let{clearChatButton:l}=j;l&&l.addEventListener("click",()=>{R.clearMessages();try{localStorage.removeItem(pn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pn}`)}catch(A){console.error("[AgentWidget] Failed to clear default localStorage:",A)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==pn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(A){console.error("[AgentWidget] Failed to clear custom localStorage:",A)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let A=i.clear();A instanceof Promise&&A.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",P)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)}a={},w.syncFromMetadata()})})(),at.addEventListener("submit",B),X.addEventListener("keydown",W),He.push(()=>{at.removeEventListener("submit",B),X.removeEventListener("keydown",W)}),He.push(()=>{R.cancel()}),se?He.push(()=>{se==null||se.destroy()}):de&&He.push(()=>{de==null||de.remove()});let Dt={update(l){var Gs,Qs,Zs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Mo,Eo,Wo,ko,Lo,Po,Ho,Bo,Io,Ro,Fo,$o,Oo,No,jo,Do,_o,qo,Uo,zo,Jo,Yo,Ko,Vo,Xo,Go,Qo,Zo,er,tr,nr,sr,or,rr,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar,Tr;let c=t.toolCall,A=t.colorScheme;t={...t,...l},Qe(),Vn(e,t),t.colorScheme!==A&&Wt();let P=kn.getForInstance(t.plugins);if(r.length=0,r.push(...P),h=(Qs=(Gs=t.launcher)==null?void 0:Gs.enabled)!=null?Qs:!0,F=(eo=(Zs=t.launcher)==null?void 0:Zs.autoExpand)!=null?eo:!1,N=(no=(to=t.features)==null?void 0:to.showReasoning)!=null?no:!0,C=(oo=(so=t.features)==null?void 0:so.showToolCalls)!=null?oo:!0,((ro=t.launcher)==null?void 0:ro.enabled)===!1&&se&&(se.destroy(),se=null),((io=t.launcher)==null?void 0:io.enabled)===!1&&de&&(de.remove(),de=null),((ao=t.launcher)==null?void 0:ao.enabled)!==!1&&!se&&!de){let x=r.find(ge=>ge.renderLauncher);if(x!=null&&x.renderLauncher){let ge=x.renderLauncher({config:t,defaultRenderer:()=>En(t,ce).element,onToggle:ce});ge&&(de=ge,e.appendChild(de))}de||(se=En(t,ce),e.appendChild(se.element))}se&&se.update(t),dt&&((lo=t.launcher)==null?void 0:lo.title)!==void 0&&(dt.textContent=t.launcher.title),ct&&((co=t.launcher)==null?void 0:co.subtitle)!==void 0&&(ct.textContent=t.launcher.subtitle);let b=(uo=t.layout)==null?void 0:uo.header;if((b==null?void 0:b.layout)!==S&&ze){let x=b?on(t,b,{showClose:h,onClose:()=>E(!1,"user")}):qt({config:t,showClose:h,onClose:()=>E(!1,"user")});ze.replaceWith(x.header),ze=x.header,we=x.iconHolder,dt=x.headerTitle,ct=x.headerSubtitle,q=x.closeButton,S=b==null?void 0:b.layout}else if(b&&(we&&(we.style.display=b.showIcon===!1?"none":""),dt&&(dt.style.display=b.showTitle===!1?"none":""),ct&&(ct.style.display=b.showSubtitle===!1?"none":""),q&&(q.style.display=b.showCloseButton===!1?"none":""),j.clearChatButtonWrapper)){let x=b.showClearChat;if(x!==void 0){j.clearChatButtonWrapper.style.display=x?"":"none";let{closeButtonWrapper:ge}=j;ge&&!ge.classList.contains("tvw-absolute")&&(x?ge.classList.remove("tvw-ml-auto"):ge.classList.add("tvw-ml-auto"))}}let ue=((po=t.layout)==null?void 0:po.showHeader)!==!1;ze&&(ze.style.display=ue?"":"none");let M=((go=t.layout)==null?void 0:go.showFooter)!==!1;ut&&(ut.style.display=M?"":"none"),h!==y?h?E(F,"auto"):(I=!0,Le()):F!==T&&E(F,"auto"),T=F,y=h,mt(),Bs(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&R&&Ke(V,R.getMessages(),v);let O=(mo=t.launcher)!=null?mo:{},Fe=(ho=O.headerIconHidden)!=null?ho:!1,Ae=(wo=(fo=t.layout)==null?void 0:fo.header)==null?void 0:wo.showIcon,pe=Fe||Ae===!1,_e=O.headerIconName,qe=(yo=O.headerIconSize)!=null?yo:"48px";if(we){let x=Y.querySelector(".tvw-border-b-cw-divider"),ge=x==null?void 0:x.querySelector(".tvw-flex-col");if(pe)we.style.display="none",x&&ge&&!x.contains(ge)&&x.insertBefore(ge,x.firstChild);else{if(we.style.display="",we.style.height=qe,we.style.width=qe,x&&ge&&(x.contains(we)?we.nextSibling!==ge&&(we.remove(),x.insertBefore(we,ge)):x.insertBefore(we,ge)),_e){let ne=parseFloat(qe)||24,be=re(_e,ne*.6,"#ffffff",2);be?we.replaceChildren(be):we.textContent=(vo=O.agentIconText)!=null?vo:"\u{1F4AC}"}else if(O.iconUrl){let ne=we.querySelector("img");if(ne)ne.src=O.iconUrl,ne.style.height=qe,ne.style.width=qe;else{let be=document.createElement("img");be.src=O.iconUrl,be.alt="",be.className="tvw-rounded-xl tvw-object-cover",be.style.height=qe,be.style.width=qe,we.replaceChildren(be)}}else{let ne=we.querySelector("svg"),be=we.querySelector("img");(ne||be)&&we.replaceChildren(),we.textContent=(bo=O.agentIconText)!=null?bo:"\u{1F4AC}"}let $e=we.querySelector("img");$e&&($e.style.height=qe,$e.style.width=qe)}}let rt=(xo=(Co=t.layout)==null?void 0:Co.header)==null?void 0:xo.showTitle,Tt=(Ao=(So=t.layout)==null?void 0:So.header)==null?void 0:Ao.showSubtitle;if(dt&&(dt.style.display=rt===!1?"none":""),ct&&(ct.style.display=Tt===!1?"none":""),q){((Mo=(To=t.layout)==null?void 0:To.header)==null?void 0:Mo.showCloseButton)===!1?q.style.display="none":q.style.display="";let ge=(Eo=O.closeButtonSize)!=null?Eo:"32px",$e=(Wo=O.closeButtonPlacement)!=null?Wo:"inline";q.style.height=ge,q.style.width=ge;let{closeButtonWrapper:ne}=j,be=$e==="top-right",pt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&be!==pt)if(ne.remove(),be)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(ne);else{let ie=(Lo=(ko=O.clearChat)==null?void 0:ko.placement)!=null?Lo:"inline",Ge=(Ho=(Po=O.clearChat)==null?void 0:Po.enabled)!=null?Ho:!0;ne.className=Ge&&ie==="inline"?"":"tvw-ml-auto";let Ct=Y.querySelector(".tvw-border-b-cw-divider");Ct&&Ct.appendChild(ne)}if(O.closeButtonColor?(q.style.color=O.closeButtonColor,q.classList.remove("tvw-text-cw-muted")):(q.style.color="",q.classList.add("tvw-text-cw-muted")),O.closeButtonBackgroundColor?(q.style.backgroundColor=O.closeButtonBackgroundColor,q.classList.remove("hover:tvw-bg-gray-100")):(q.style.backgroundColor="",q.classList.add("hover:tvw-bg-gray-100")),O.closeButtonBorderWidth||O.closeButtonBorderColor){let ie=O.closeButtonBorderWidth||"0px",Ge=O.closeButtonBorderColor||"transparent";q.style.border=`${ie} solid ${Ge}`,q.classList.remove("tvw-border-none")}else q.style.border="",q.classList.add("tvw-border-none");O.closeButtonBorderRadius?(q.style.borderRadius=O.closeButtonBorderRadius,q.classList.remove("tvw-rounded-full")):(q.style.borderRadius="",q.classList.add("tvw-rounded-full")),O.closeButtonPaddingX?(q.style.paddingLeft=O.closeButtonPaddingX,q.style.paddingRight=O.closeButtonPaddingX):(q.style.paddingLeft="",q.style.paddingRight=""),O.closeButtonPaddingY?(q.style.paddingTop=O.closeButtonPaddingY,q.style.paddingBottom=O.closeButtonPaddingY):(q.style.paddingTop="",q.style.paddingBottom="");let it=(Bo=O.closeButtonIconName)!=null?Bo:"x",Mt=(Io=O.closeButtonIconText)!=null?Io:"\xD7";q.innerHTML="";let ht=re(it,"20px",O.closeButtonColor||"",2);ht?q.appendChild(ht):q.textContent=Mt;let Oe=(Ro=O.closeButtonTooltipText)!=null?Ro:"Close chat",Et=(Fo=O.closeButtonShowTooltip)!=null?Fo:!0;if(q.setAttribute("aria-label",Oe),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),Et&&Oe)){let ie=null,Ge=()=>{if(ie||!q)return;ie=p("div","tvw-clear-chat-tooltip"),ie.textContent=Oe;let xn=p("div");xn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(xn);let Xt=q.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Xt.left+Xt.width/2}px`,ie.style.top=`${Xt.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};ne.addEventListener("mouseenter",Ge),ne.addEventListener("mouseleave",Ct),q.addEventListener("focus",Ge),q.addEventListener("blur",Ct),ne._cleanupTooltip=()=>{Ct(),ne&&(ne.removeEventListener("mouseenter",Ge),ne.removeEventListener("mouseleave",Ct)),q&&(q.removeEventListener("focus",Ge),q.removeEventListener("blur",Ct))}}}let{clearChatButton:ee,clearChatButtonWrapper:Ee}=j;if(ee){let x=($o=O.clearChat)!=null?$o:{},ge=(Oo=x.enabled)!=null?Oo:!0,$e=(jo=(No=t.layout)==null?void 0:No.header)==null?void 0:jo.showClearChat,ne=$e!==void 0?$e:ge,be=(Do=x.placement)!=null?Do:"inline";if(Ee){Ee.style.display=ne?"":"none";let{closeButtonWrapper:pt}=j;pt&&!pt.classList.contains("tvw-absolute")&&(ne?pt.classList.remove("tvw-ml-auto"):pt.classList.add("tvw-ml-auto"));let it=be==="top-right",Mt=Ee.classList.contains("tvw-absolute");if(it!==Mt&&ne){if(Ee.remove(),it)Ee.className="tvw-absolute tvw-top-4 tvw-z-50",Ee.style.right="48px",Y.style.position="relative",Y.appendChild(Ee);else{Ee.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Ee.style.right="";let Oe=Y.querySelector(".tvw-border-b-cw-divider"),Et=j.closeButtonWrapper;Oe&&Et&&Et.parentElement===Oe?Oe.insertBefore(Ee,Et):Oe&&Oe.appendChild(Ee)}let ht=j.closeButtonWrapper;ht&&!ht.classList.contains("tvw-absolute")&&(it?ht.classList.add("tvw-ml-auto"):ht.classList.remove("tvw-ml-auto"))}}if(ne){let pt=(_o=x.size)!=null?_o:"32px";ee.style.height=pt,ee.style.width=pt;let it=(qo=x.iconName)!=null?qo:"refresh-cw",Mt=(Uo=x.iconColor)!=null?Uo:"";ee.innerHTML="";let ht=re(it,"20px",Mt||"",2);if(ht&&ee.appendChild(ht),Mt?(ee.style.color=Mt,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),x.backgroundColor?(ee.style.backgroundColor=x.backgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),x.borderWidth||x.borderColor){let ie=x.borderWidth||"0px",Ge=x.borderColor||"transparent";ee.style.border=`${ie} solid ${Ge}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");x.borderRadius?(ee.style.borderRadius=x.borderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),x.paddingX?(ee.style.paddingLeft=x.paddingX,ee.style.paddingRight=x.paddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),x.paddingY?(ee.style.paddingTop=x.paddingY,ee.style.paddingBottom=x.paddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let Oe=(zo=x.tooltipText)!=null?zo:"Clear chat",Et=(Jo=x.showTooltip)!=null?Jo:!0;if(ee.setAttribute("aria-label",Oe),Ee&&(Ee._cleanupTooltip&&(Ee._cleanupTooltip(),delete Ee._cleanupTooltip),Et&&Oe)){let ie=null,Ge=()=>{if(ie||!ee)return;ie=p("div","tvw-clear-chat-tooltip"),ie.textContent=Oe;let xn=p("div");xn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(xn);let Xt=ee.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Xt.left+Xt.width/2}px`,ie.style.top=`${Xt.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};Ee.addEventListener("mouseenter",Ge),Ee.addEventListener("mouseleave",Ct),ee.addEventListener("focus",Ge),ee.addEventListener("blur",Ct),Ee._cleanupTooltip=()=>{Ct(),Ee&&(Ee.removeEventListener("mouseenter",Ge),Ee.removeEventListener("mouseleave",Ct)),ee&&(ee.removeEventListener("focus",Ge),ee.removeEventListener("blur",Ct))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Ln],Vt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick];w=Pn({parsers:Kt,handlers:Vt,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),v=pi(t,w),R.updateConfig(t),Ke(V,R.getMessages(),v),ft.render(t.suggestionChips,R,X,void 0,t.suggestionChipsConfig),oe(),bt(R.isStreaming());let In=((Yo=t.voiceRecognition)==null?void 0:Yo.enabled)===!0,Rn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(In&&Rn)if(!$||!Ne){let x=Ce(t.voiceRecognition,t.sendButton);x&&($=x.micButton,Ne=x.micButtonWrapper,Ht.insertBefore(Ne,tt),$.addEventListener("click",xe),$.disabled=R.isStreaming())}else{let x=(Ko=t.voiceRecognition)!=null?Ko:{},ge=(Vo=t.sendButton)!=null?Vo:{},$e=(Xo=x.iconName)!=null?Xo:"mic",ne=(Go=ge.size)!=null?Go:"40px",be=(Qo=x.iconSize)!=null?Qo:ne,pt=parseFloat(be)||24;$.style.width=be,$.style.height=be,$.style.minWidth=be,$.style.minHeight=be;let it=(er=(Zo=x.iconColor)!=null?Zo:ge.textColor)!=null?er:"currentColor";$.innerHTML="";let Mt=re($e,pt,it,2);Mt?$.appendChild(Mt):$.textContent="\u{1F3A4}";let ht=(tr=x.backgroundColor)!=null?tr:ge.backgroundColor;ht?($.style.backgroundColor=ht,$.classList.remove("tvw-bg-cw-primary")):($.style.backgroundColor="",$.classList.add("tvw-bg-cw-primary")),it?($.style.color=it,$.classList.remove("tvw-text-white")):!it&&!ge.textColor&&($.style.color="",$.classList.add("tvw-text-white")),x.borderWidth?($.style.borderWidth=x.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),x.borderColor?$.style.borderColor=x.borderColor:$.style.borderColor="",x.paddingX?($.style.paddingLeft=x.paddingX,$.style.paddingRight=x.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),x.paddingY?($.style.paddingTop=x.paddingY,$.style.paddingBottom=x.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let Oe=Ne==null?void 0:Ne.querySelector(".tvw-send-button-tooltip"),Et=(nr=x.tooltipText)!=null?nr:"Start voice recognition";if(((sr=x.showTooltip)!=null?sr:!1)&&Et)if(Oe)Oe.textContent=Et,Oe.style.display="";else{let Ge=document.createElement("div");Ge.className="tvw-send-button-tooltip",Ge.textContent=Et,Ne==null||Ne.insertBefore(Ge,$)}else Oe&&(Oe.style.display="none");Ne.style.display="",$.disabled=R.isStreaming()}else $&&Ne&&(Ne.style.display="none",fe&&We());if(((or=t.attachments)==null?void 0:or.enabled)===!0)if(!nt||!me){let x=(rr=t.attachments)!=null?rr:{},$e=(ar=((ir=t.sendButton)!=null?ir:{}).size)!=null?ar:"40px";st||(st=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),st.style.display="none",at.insertBefore(st,X)),he||(he=document.createElement("input"),he.type="file",he.accept=((lr=x.allowedTypes)!=null?lr:Jt).join(","),he.multiple=((dr=x.maxFiles)!=null?dr:4)>1,he.style.display="none",he.setAttribute("aria-label","Attach files"),at.insertBefore(he,X)),nt=p("div","tvw-send-button-wrapper"),me=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),me.type="button",me.setAttribute("aria-label",(cr=x.buttonTooltipText)!=null?cr:"Attach file");let ne=(ur=x.buttonIconName)!=null?ur:"paperclip",be=$e,pt=parseFloat(be)||40,it=Math.round(pt*.6);me.style.width=be,me.style.height=be,me.style.minWidth=be,me.style.minHeight=be,me.style.fontSize="18px",me.style.lineHeight="1",me.style.backgroundColor="transparent",me.style.color="var(--cw-primary, #111827)",me.style.border="none",me.style.borderRadius="6px",me.style.transition="background-color 0.15s ease",me.addEventListener("mouseenter",()=>{me.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),me.addEventListener("mouseleave",()=>{me.style.backgroundColor="transparent"});let Mt=re(ne,it,"currentColor",1.5);Mt?me.appendChild(Mt):me.textContent="\u{1F4CE}",me.addEventListener("click",Et=>{Et.preventDefault(),he==null||he.click()}),nt.appendChild(me);let ht=(pr=x.buttonTooltipText)!=null?pr:"Attach file",Oe=p("div","tvw-send-button-tooltip");Oe.textContent=ht,nt.appendChild(Oe),Pt.append(nt),!Te&&he&&st&&(Te=Qt.fromConfig(x),Te.setPreviewsContainer(st),he.addEventListener("change",async()=>{Te&&(he!=null&&he.files)&&(await Te.handleFileSelect(he.files),he.value="")}))}else{nt.style.display="";let x=(gr=t.attachments)!=null?gr:{};he&&(he.accept=((mr=x.allowedTypes)!=null?mr:Jt).join(","),he.multiple=((hr=x.maxFiles)!=null?hr:4)>1),Te&&Te.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else nt&&(nt.style.display="none"),Te&&Te.clearAttachments();let Ue=(fr=t.sendButton)!=null?fr:{},Fn=(wr=Ue.useIcon)!=null?wr:!1,fn=(yr=Ue.iconText)!=null?yr:"\u2191",wn=Ue.iconName,zt=(vr=Ue.tooltipText)!=null?vr:"Send message",yn=(br=Ue.showTooltip)!=null?br:!1,vn=(Cr=Ue.size)!=null?Cr:"40px",$n=Ue.backgroundColor,Rt=Ue.textColor;if(Fn){if(D.style.width=vn,D.style.height=vn,D.style.minWidth=vn,D.style.minHeight=vn,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",wn){let x=parseFloat(vn)||24,ge=Rt&&typeof Rt=="string"&&Rt.trim()?Rt.trim():"currentColor",$e=re(wn,x,ge,2);$e?(D.appendChild($e),D.style.color=ge):(D.textContent=fn,Rt?D.style.color=Rt:D.classList.add("tvw-text-white"))}else D.textContent=fn,Rt?D.style.color=Rt:D.classList.add("tvw-text-white");D.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",$n?(D.style.backgroundColor=$n,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Sr=(xr=t.copy)==null?void 0:xr.sendButtonLabel)!=null?Sr:"Send",D.style.width="",D.style.height="",D.style.minWidth="",D.style.minHeight="",D.style.fontSize="",D.style.lineHeight="",D.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",$n?(D.style.backgroundColor=$n,D.classList.remove("tvw-bg-cw-accent")):D.classList.add("tvw-bg-cw-accent"),Rt?D.style.color=Rt:D.classList.add("tvw-text-white");Ue.borderWidth?(D.style.borderWidth=Ue.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),Ue.borderColor?D.style.borderColor=Ue.borderColor:D.style.borderColor="",Ue.paddingX?(D.style.paddingLeft=Ue.paddingX,D.style.paddingRight=Ue.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),Ue.paddingY?(D.style.paddingTop=Ue.paddingY,D.style.paddingBottom=Ue.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let bn=tt==null?void 0:tt.querySelector(".tvw-send-button-tooltip");if(yn&&zt)if(bn)bn.textContent=zt,bn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=zt,tt==null||tt.insertBefore(x,D)}else bn&&(bn.style.display="none");let Cn=(Ar=t.statusIndicator)!=null?Ar:{},Ci=(Tr=Cn.visible)!=null?Tr:!0;if(lt.style.display=Ci?"":"none",R){let x=R.getStatus(),ge=$e=>{var ne,be,pt,it;return $e==="idle"?(ne=Cn.idleText)!=null?ne:gt.idle:$e==="connecting"?(be=Cn.connectingText)!=null?be:gt.connecting:$e==="connected"?(pt=Cn.connectedText)!=null?pt:gt.connected:$e==="error"?(it=Cn.errorText)!=null?it:gt.error:gt[$e]};lt.textContent=ge(x)}},open(){h&&E(!0,"api")},close(){h&&E(!1,"api")},toggle(){h&&E(!I,"api")},clearChat(){R.clearMessages();try{localStorage.removeItem(pn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pn}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==pn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let c=i.clear();c instanceof Promise&&c.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}a={},w.syncFromMetadata()},setMessage(l){return!X||R.isStreaming()?!1:(!I&&h&&E(!0,"system"),X.value=l,X.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(R.isStreaming())return!1;let c=(l==null?void 0:l.trim())||X.value.trim();return c?(!I&&h&&E(!0,"system"),X.value="",X.style.height="auto",R.sendMessage(c),!0):!1},startVoiceRecognition(){return fe||R.isStreaming()||!Ie()?!1:(!I&&h&&E(!0,"system"),ke.manuallyDeactivated=!1,jt(),De("user"),!0)},stopVoiceRecognition(){return fe?(ke.manuallyDeactivated=!0,jt(),We("user"),!0):!1},injectMessage(l){return!I&&h&&E(!0,"system"),R.injectMessage(l)},injectAssistantMessage(l){return!I&&h&&E(!0,"system"),R.injectAssistantMessage(l)},injectUserMessage(l){return!I&&h&&E(!0,"system"),R.injectUserMessage(l)},injectSystemMessage(l){return!I&&h&&E(!0,"system"),R.injectSystemMessage(l)},injectTestMessage(l){!I&&h&&E(!0,"system"),R.injectTestEvent(l)},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){f(l)},on(l,c){return s.on(l,c)},off(l,c){s.off(l,c)},isOpen(){return h&&I},isVoiceActive(){return ke.active},getState(){return{open:h&&I,launcherEnabled:h,voiceActive:ke.active,streaming:R.isStreaming()}},showCSATFeedback(l){!I&&h&&E(!0,"system");let c=V.querySelector(".tvw-feedback-container");c&&c.remove();let A=ss({onSubmit:async(P,b)=>{var Q;R.isClientTokenMode()&&await R.submitCSATFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});V.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&h&&E(!0,"system");let c=V.querySelector(".tvw-feedback-container");c&&c.remove();let A=os({onSubmit:async(P,b)=>{var Q;R.isClientTokenMode()&&await R.submitNPSFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});V.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return R.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return R.submitNPSFeedback(l,c)},destroy(){He.forEach(l=>l()),z.remove(),se==null||se.destroy(),de==null||de.remove(),ot&&q.removeEventListener("click",ot)}};if((((Xs=o==null?void 0:o.debugTools)!=null?Xs:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,c={controller:Dt,getMessages:Dt.getMessages,getStatus:Dt.getStatus,getMetadata:Dt.getPersistentMetadata,updateMetadata:Dt.updatePersistentMetadata,clearHistory:()=>Dt.clearChat(),setVoiceActive:A=>A?Dt.startVoiceRecognition():Dt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,He.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return Dt};var ks={},na=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},sa=()=>{try{if(typeof ks!="undefined"&&ks.url)return new URL("../widget.css",ks.url).href}catch{}return null},gi=e=>{let n=sa(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let r=t.cloneNode(!0);e.insertBefore(r,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else o();else if(!document.head.querySelector("link[data-persona]")&&n){let r=document.createElement("link");r.rel="stylesheet",r.href=n,r.setAttribute("data-persona","true"),document.head.appendChild(r)}},Ls=e=>{var u,f,g,m;let n=na(e.target),o=document.createElement("div");o.className="persona-host";let t=(g=(f=(u=e.config)==null?void 0:u.launcher)==null?void 0:f.enabled)!=null?g:!0;t||(o.style.height="100%"),n.appendChild(o);let r=e.useShadowDom===!0,s,i;if(r){let w=o.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),gi(w)}else i=o,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),o.appendChild(s),gi(o);let a=rs(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:o,destroy(){a.destroy(),o.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var mi={name:"@runtypelabs/persona",version:"1.37.2",description:"Themeable, plugable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var tn=mi.version;function Ut(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function ra(e){if(e)return{getHeaders:Ut(e.getHeaders),onFeedback:Ut(e.onFeedback),onCopy:Ut(e.onCopy),requestMiddleware:Ut(e.requestMiddleware),actionHandlers:Ut(e.actionHandlers),actionParsers:Ut(e.actionParsers),postprocessMessage:Ut(e.postprocessMessage),contextProviders:Ut(e.contextProviders),streamParser:Ut(e.streamParser)}}var hi=`({ text, message }: any) => {
61
61
  const jsonSource = (message as any).rawContent || text || message.content;
62
62
  if (!jsonSource || typeof jsonSource !== 'string') return null;
63
63
  let cleanJson = jsonSource
@@ -70,7 +70,7 @@
70
70
  if (parsed.action) return { type: parsed.action, payload: parsed };
71
71
  } catch (e) { return null; }
72
72
  return null;
73
- }`,mi=`function(ctx) {
73
+ }`,fi=`function(ctx) {
74
74
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
75
75
  if (!jsonSource || typeof jsonSource !== 'string') return null;
76
76
  var cleanJson = jsonSource
@@ -83,7 +83,7 @@
83
83
  if (parsed.action) return { type: parsed.action, payload: parsed };
84
84
  } catch (e) { return null; }
85
85
  return null;
86
- }`,hi=`(action: any, context: any) => {
86
+ }`,wi=`(action: any, context: any) => {
87
87
  if (action.type !== 'nav_then_click') return;
88
88
  const payload = action.payload || action.raw || {};
89
89
  const url = payload?.page;
@@ -100,7 +100,7 @@
100
100
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
101
101
  window.location.href = targetUrl;
102
102
  return { handled: true, displayText: text };
103
- }`,fi=`function(action, context) {
103
+ }`,yi=`function(action, context) {
104
104
  if (action.type !== 'nav_then_click') return;
105
105
  var payload = action.payload || action.raw || {};
106
106
  var url = payload.page;
@@ -117,24 +117,24 @@
117
117
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
118
118
  window.location.href = targetUrl;
119
119
  return { handled: true, displayText: text };
120
- }`,sa=`(parsed: any) => {
120
+ }`,ia=`(parsed: any) => {
121
121
  if (!parsed || typeof parsed !== 'object') return null;
122
122
  if (parsed.action === 'nav_then_click') return 'Navigating...';
123
123
  if (parsed.action === 'message') return parsed.text || '';
124
124
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
125
125
  return parsed.text || null;
126
- }`,oa=`function(parsed) {
126
+ }`,aa=`function(parsed) {
127
127
  if (!parsed || typeof parsed !== 'object') return null;
128
128
  if (parsed.action === 'nav_then_click') return 'Navigating...';
129
129
  if (parsed.action === 'message') return parsed.text || '';
130
130
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
131
131
  return parsed.text || null;
132
- }`;function ra(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function rs(e){var n,o;return(o=(n=e.parserType)!=null?n:ra(e.streamParser))!=null?o:"plain"}function is(e,n){let o=[];return e.toolCall&&(o.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([t,r])=>{typeof r=="string"&&o.push(`${n} ${t}: "${r}",`)}),o.push(`${n}},`)),o}function as(e,n,o){let t=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(o==null?void 0:o.onFeedback)||(o==null?void 0:o.onCopy);return(r||s)&&(t.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?t.push(`${n} ${i}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${i}: ${a},`))}),o!=null&&o.onFeedback&&t.push(`${n} onFeedback: ${o.onFeedback},`),o!=null&&o.onCopy&&t.push(`${n} onCopy: ${o.onCopy},`),t.push(`${n}},`)),t}function ls(e,n){let o=[];if(e.markdown){let t=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(t||r)&&(o.push(`${n}markdown: {`),t&&(o.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`)}),o.push(`${n} },`)),r&&o.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),o.push(`${n}},`))}return o}function ds(e,n){let o=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(t||r)&&(o.push(`${n}layout: {`),t&&(o.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`))}),o.push(`${n} },`)),r&&(o.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(o.push(`${n} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?o.push(`${n} ${a}: "${d}",`):typeof d=="boolean"&&o.push(`${n} ${a}: ${d},`)}),o.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(o.push(`${n} timestamp: {`),Object.entries(i).forEach(([d,u])=>{d!=="format"&&(typeof u=="string"?o.push(`${n} ${d}: "${u}",`):typeof u=="boolean"&&o.push(`${n} ${d}: ${u},`))}),o.push(`${n} },`)):typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`))}),o.push(`${n} },`)),o.push(`${n}},`))}return o}function Ls(e,n){let o=[];return e&&(e.getHeaders&&o.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&o.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&o.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&o.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&o.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&o.push(`${n}streamParser: ${e.streamParser},`)),o}function wi(e,n="esm",o){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let r=o?{...o,hooks:na(o.hooks)}:void 0;return n==="esm"?ia(t,r):n==="script-installer"?da(t):n==="script-advanced"?ua(t,r):n==="react-component"?aa(t,r):n==="react-advanced"?la(t,r):ca(t,r)}function ia(e,n){let o=n==null?void 0:n.hooks,t=rs(e),r=t!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...Ls(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
- `)}function aa(e,n){let o=n==null?void 0:n.hooks,t=rs(e),r=t!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...Ls(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
134
- `)}function la(e,n){let o=n==null?void 0:n.hooks,t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),e.theme&&(t.push(" theme: {"),Object.entries(e.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...is(e," ")),t.push(...as(e," ",o)),t.push(...ls(e," ")),t.push(...ds(e," ")),o!=null&&o.getHeaders&&t.push(` getHeaders: ${o.getHeaders},`),o!=null&&o.contextProviders&&t.push(` contextProviders: ${o.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),o!=null&&o.streamParser?t.push(` streamParser: ${o.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${sa}),`)),o!=null&&o.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${o.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${gi}`),t.push(" ],")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Parser for markdown-wrapped JSON"),t.push(` ${gi}`),t.push(" ],")),o!=null&&o.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${o.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${hi}`),t.push(" ],")):(t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(` ${hi}`),t.push(" ],")),o!=null&&o.postprocessMessage?t.push(` postprocessMessage: ${o.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),o!=null&&o.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${o.requestMiddleware})({ payload, config });`),t.push(" const merged = customResult || payload;"),t.push(" return {"),t.push(" ...merged,"),t.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),t.push(" };"),t.push(" }")):(t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }")),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('persona:message', handleMessage);"),t.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('persona:message', handleMessage);"),t.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
135
- `)}function yi(e){var r;let n=rs(e),o=n!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.clientToken&&(t.clientToken=e.clientToken),e.flowId&&(t.flowId=e.flowId),o&&(t.parserType=n),e.theme&&(t.theme=e.theme),e.launcher&&(t.launcher=e.launcher),e.copy&&(t.copy=e.copy),e.sendButton&&(t.sendButton=e.sendButton),e.voiceRecognition&&(t.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(t.statusIndicator=e.statusIndicator),e.features&&(t.features=e.features),((r=e.suggestionChips)==null?void 0:r.length)>0&&(t.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(t.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(t.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(t.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(t.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(t.markdown=s)}if(e.layout){let s={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,d])=>{a!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,d])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(a==="timestamp"&&typeof d=="object"&&d!==null){let u={};Object.entries(d).forEach(([f,g])=>{f!=="format"&&(typeof g=="string"||typeof g=="boolean")&&(u[f]=g)}),Object.keys(u).length>0&&(i.timestamp=u)}else(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(t.layout=s)}return t}function da(e){let n=yi(e);return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js" data-config='${JSON.stringify(n,null,0).replace(/'/g,"&#39;")}'></script>`}function ca(e,n){let o=n==null?void 0:n.hooks,t=rs(e),r=t!=="plain",s=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...Ls(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
136
- `)}function ua(e,n){let o=n==null?void 0:n.hooks,t=yi(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
132
+ }`;function la(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function is(e){var n,o;return(o=(n=e.parserType)!=null?n:la(e.streamParser))!=null?o:"plain"}function as(e,n){let o=[];return e.toolCall&&(o.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([t,r])=>{typeof r=="string"&&o.push(`${n} ${t}: "${r}",`)}),o.push(`${n}},`)),o}function ls(e,n,o){let t=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(o==null?void 0:o.onFeedback)||(o==null?void 0:o.onCopy);return(r||s)&&(t.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?t.push(`${n} ${i}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${i}: ${a},`))}),o!=null&&o.onFeedback&&t.push(`${n} onFeedback: ${o.onFeedback},`),o!=null&&o.onCopy&&t.push(`${n} onCopy: ${o.onCopy},`),t.push(`${n}},`)),t}function ds(e,n){let o=[];if(e.markdown){let t=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(t||r)&&(o.push(`${n}markdown: {`),t&&(o.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`)}),o.push(`${n} },`)),r&&o.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),o.push(`${n}},`))}return o}function cs(e,n){let o=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(t||r)&&(o.push(`${n}layout: {`),t&&(o.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`))}),o.push(`${n} },`)),r&&(o.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(o.push(`${n} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?o.push(`${n} ${a}: "${d}",`):typeof d=="boolean"&&o.push(`${n} ${a}: ${d},`)}),o.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(o.push(`${n} timestamp: {`),Object.entries(i).forEach(([d,u])=>{d!=="format"&&(typeof u=="string"?o.push(`${n} ${d}: "${u}",`):typeof u=="boolean"&&o.push(`${n} ${d}: ${u},`))}),o.push(`${n} },`)):typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`))}),o.push(`${n} },`)),o.push(`${n}},`))}return o}function Ps(e,n){let o=[];return e&&(e.getHeaders&&o.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&o.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&o.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&o.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&o.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&o.push(`${n}streamParser: ${e.streamParser},`)),o}function vi(e,n="esm",o){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let r=o?{...o,hooks:ra(o.hooks)}:void 0;return n==="esm"?da(t,r):n==="script-installer"?pa(t):n==="script-advanced"?ma(t,r):n==="react-component"?ca(t,r):n==="react-advanced"?ua(t,r):ga(t,r)}function da(e,n){let o=n==null?void 0:n.hooks,t=is(e),r=t!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...as(e," ")),s.push(...ls(e," ",o)),s.push(...ds(e," ")),s.push(...cs(e," ")),s.push(...Ps(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
+ `)}function ca(e,n){let o=n==null?void 0:n.hooks,t=is(e),r=t!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...as(e," ")),s.push(...ls(e," ",o)),s.push(...ds(e," ")),s.push(...cs(e," ")),s.push(...Ps(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
134
+ `)}function ua(e,n){let o=n==null?void 0:n.hooks,t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),e.theme&&(t.push(" theme: {"),Object.entries(e.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...as(e," ")),t.push(...ls(e," ",o)),t.push(...ds(e," ")),t.push(...cs(e," ")),o!=null&&o.getHeaders&&t.push(` getHeaders: ${o.getHeaders},`),o!=null&&o.contextProviders&&t.push(` contextProviders: ${o.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),o!=null&&o.streamParser?t.push(` streamParser: ${o.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${ia}),`)),o!=null&&o.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${o.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${hi}`),t.push(" ],")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Parser for markdown-wrapped JSON"),t.push(` ${hi}`),t.push(" ],")),o!=null&&o.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${o.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${wi}`),t.push(" ],")):(t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(` ${wi}`),t.push(" ],")),o!=null&&o.postprocessMessage?t.push(` postprocessMessage: ${o.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),o!=null&&o.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${o.requestMiddleware})({ payload, config });`),t.push(" const merged = customResult || payload;"),t.push(" return {"),t.push(" ...merged,"),t.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),t.push(" };"),t.push(" }")):(t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }")),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('persona:message', handleMessage);"),t.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('persona:message', handleMessage);"),t.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
135
+ `)}function bi(e){var r;let n=is(e),o=n!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.clientToken&&(t.clientToken=e.clientToken),e.flowId&&(t.flowId=e.flowId),o&&(t.parserType=n),e.theme&&(t.theme=e.theme),e.launcher&&(t.launcher=e.launcher),e.copy&&(t.copy=e.copy),e.sendButton&&(t.sendButton=e.sendButton),e.voiceRecognition&&(t.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(t.statusIndicator=e.statusIndicator),e.features&&(t.features=e.features),((r=e.suggestionChips)==null?void 0:r.length)>0&&(t.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(t.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(t.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(t.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(t.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(t.markdown=s)}if(e.layout){let s={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,d])=>{a!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,d])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(a==="timestamp"&&typeof d=="object"&&d!==null){let u={};Object.entries(d).forEach(([f,g])=>{f!=="format"&&(typeof g=="string"||typeof g=="boolean")&&(u[f]=g)}),Object.keys(u).length>0&&(i.timestamp=u)}else(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(t.layout=s)}return t}function pa(e){let n=bi(e),o=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${tn}/dist/install.global.js" data-config='${o}'></script>`}function ga(e,n){let o=n==null?void 0:n.hooks,t=is(e),r=t!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${tn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${tn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...as(e," ")),s.push(...ls(e," ",o)),s.push(...ds(e," ")),s.push(...cs(e," ")),s.push(...Ps(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
136
+ `)}function ma(e,n){let o=n==null?void 0:n.hooks,t=bi(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
137
137
  `).map((i,a)=>a===0?i:" "+i).join(`
138
- `)};`,""," // Constants"," var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist';"," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return o!=null&&o.getHeaders&&(s.push(` widgetConfig.getHeaders = ${o.getHeaders};`),s.push("")),o!=null&&o.contextProviders&&(s.push(` widgetConfig.contextProviders = ${o.contextProviders};`),s.push("")),o!=null&&o.streamParser?s.push(` widgetConfig.streamParser = ${o.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${oa});`),s.push(" };")),s.push(""),o!=null&&o.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${o.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${mi}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${mi}`),s.push(" ];")),s.push(""),o!=null&&o.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${o.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${fi}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${fi}`),s.push(" ];")),s.push(""),o!=null&&o.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${o.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),o!=null&&o.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${o.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(o!=null&&o.onFeedback||o!=null&&o.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),o!=null&&o.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${o.onFeedback};`),o!=null&&o.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${o.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
139
- `)}var pa=ks;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,validateImageFile});
138
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${tn}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return o!=null&&o.getHeaders&&(s.push(` widgetConfig.getHeaders = ${o.getHeaders};`),s.push("")),o!=null&&o.contextProviders&&(s.push(` widgetConfig.contextProviders = ${o.contextProviders};`),s.push("")),o!=null&&o.streamParser?s.push(` widgetConfig.streamParser = ${o.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${aa});`),s.push(" };")),s.push(""),o!=null&&o.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${o.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${fi}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${fi}`),s.push(" ];")),s.push(""),o!=null&&o.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${o.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${yi}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${yi}`),s.push(" ];")),s.push(""),o!=null&&o.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${o.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),o!=null&&o.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${o.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(o!=null&&o.onFeedback||o!=null&&o.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),o!=null&&o.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${o.onFeedback};`),o!=null&&o.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${o.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
139
+ `)}var ha=Ls;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,validateImageFile});
140
140
  //# sourceMappingURL=index.cjs.map