@runtypelabs/persona 1.38.1 → 1.38.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 Si=Object.create;var Nn=Object.defineProperty;var Ai=Object.getOwnPropertyDescriptor;var Ti=Object.getOwnPropertyNames;var Mi=Object.getPrototypeOf,Ei=Object.prototype.hasOwnProperty;var Wi=(e,n)=>{for(var o in n)Nn(e,o,{get:n[o],enumerable:!0})},Er=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Ti(n))!Ei.call(e,r)&&r!==o&&Nn(e,r,{get:()=>n[r],enumerable:!(t=Ai(n,r))||t.enumerable});return e};var ki=(e,n,o)=>(o=e!=null?Si(Mi(e)):{},Er(n||!e||!e.__esModule?Nn(o,"default",{value:e,enumerable:!0}):o,e)),Li=e=>Er(Nn({},"__esModule",{value:!0}),e);var wa={};Wi(wa,{AgentWidgetClient:()=>Gt,AgentWidgetSession:()=>sn,AttachmentManager:()=>Qt,DEFAULT_DARK_THEME:()=>Ms,DEFAULT_LIGHT_THEME:()=>Ts,DEFAULT_WIDGET_CONFIG:()=>Be,VERSION:()=>tn,attachHeaderToContainer:()=>Zt,buildComposer:()=>rn,buildDefaultHeader:()=>fs,buildExpandedHeader:()=>ys,buildHeader:()=>qt,buildHeaderWithLayout:()=>on,buildMinimalHeader:()=>ws,componentRegistry:()=>cn,createActionManager:()=>Hn,createAgentExperience:()=>is,createBubbleWithLayout:()=>si,createCSATFeedback:()=>os,createComponentMiddleware:()=>ui,createComponentStreamParser:()=>es,createDirectivePostprocessor:()=>Hr,createFlexibleJsonStreamParser:()=>Fr,createImagePart:()=>Ur,createJsonStreamParser:()=>zn,createLocalStorageAdapter:()=>Zn,createMarkdownProcessor:()=>An,createMarkdownProcessorFromConfig:()=>Tn,createMessageActions:()=>bs,createNPSFeedback:()=>rs,createPlainTextParser:()=>qn,createRegexJsonParser:()=>Un,createStandardBubble:()=>an,createTextPart:()=>Yn,createTypingIndicator:()=>kn,createXmlParser:()=>Jn,default:()=>fa,defaultActionHandlers:()=>en,defaultJsonActionParser:()=>Pn,directivePostprocessor:()=>Br,escapeHtml:()=>jn,extractComponentDirectiveFromMessage:()=>ss,fileToImagePart:()=>zr,generateAssistantMessageId:()=>En,generateCodeSnippet:()=>bi,generateMessageId:()=>Nr,generateUserMessageId:()=>Mn,getDisplayText:()=>Dr,getHeaderLayout:()=>vs,getImageParts:()=>qr,hasComponentDirective:()=>ns,hasImages:()=>_r,headerLayouts:()=>Gn,initAgentWidget:()=>Ps,isComponentDirectiveType:()=>ci,markdownPostprocessor:()=>gs,mergeWithDefaults:()=>Qn,normalizeContent:()=>jr,pluginRegistry:()=>Ln,renderComponentDirective:()=>ts,validateImageFile:()=>Jr});module.exports=Li(wa);var kr=require("marked"),Pi=e=>{if(e)return e},An=e=>{var r,s;let n=e==null?void 0:e.markedOptions,o=new kr.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=Pi(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},Tn=e=>e?An({markedOptions:e.options,renderer:e.renderer}):An(),Hi=An(),gs=e=>Hi(e),jn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Lr=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Wr=e=>`%%FORM_PLACEHOLDER_${e}%%`,Pr=(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=Wr(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=Wr(n.length);return n.push({token:s,type:r}),s}),o},Hr=e=>{let n=Tn(e);return o=>{let t=[],r=Pr(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="${Lr(a)}"></div>`;s=s.replace(d,f)}),s}},Br=e=>{let n=[],o=Pr(e,n),t=gs(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="${Lr(s)}"></div>`;t=t.replace(i,d)}),t};var _t=require("partial-json"),Dn=e=>e.replace(/\\n/g,`
1
+ "use strict";var Si=Object.create;var Nn=Object.defineProperty;var Ai=Object.getOwnPropertyDescriptor;var Ti=Object.getOwnPropertyNames;var Mi=Object.getPrototypeOf,Ei=Object.prototype.hasOwnProperty;var ki=(e,n)=>{for(var o in n)Nn(e,o,{get:n[o],enumerable:!0})},Er=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Ti(n))!Ei.call(e,r)&&r!==o&&Nn(e,r,{get:()=>n[r],enumerable:!(t=Ai(n,r))||t.enumerable});return e};var Wi=(e,n,o)=>(o=e!=null?Si(Mi(e)):{},Er(n||!e||!e.__esModule?Nn(o,"default",{value:e,enumerable:!0}):o,e)),Li=e=>Er(Nn({},"__esModule",{value:!0}),e);var wa={};ki(wa,{AgentWidgetClient:()=>Gt,AgentWidgetSession:()=>on,AttachmentManager:()=>Qt,DEFAULT_DARK_THEME:()=>Ms,DEFAULT_LIGHT_THEME:()=>Ts,DEFAULT_WIDGET_CONFIG:()=>Be,VERSION:()=>tn,attachHeaderToContainer:()=>Zt,buildComposer:()=>an,buildDefaultHeader:()=>fs,buildExpandedHeader:()=>ys,buildHeader:()=>qt,buildHeaderWithLayout:()=>rn,buildMinimalHeader:()=>ws,componentRegistry:()=>un,createActionManager:()=>Hn,createAgentExperience:()=>is,createBubbleWithLayout:()=>si,createCSATFeedback:()=>os,createComponentMiddleware:()=>ui,createComponentStreamParser:()=>es,createDirectivePostprocessor:()=>Hr,createFlexibleJsonStreamParser:()=>Fr,createImagePart:()=>Ur,createJsonStreamParser:()=>zn,createLocalStorageAdapter:()=>Zn,createMarkdownProcessor:()=>Tn,createMarkdownProcessorFromConfig:()=>Mn,createMessageActions:()=>bs,createNPSFeedback:()=>rs,createPlainTextParser:()=>qn,createRegexJsonParser:()=>Un,createStandardBubble:()=>ln,createTextPart:()=>Yn,createTypingIndicator:()=>Wn,createXmlParser:()=>Jn,default:()=>fa,defaultActionHandlers:()=>en,defaultJsonActionParser:()=>Pn,directivePostprocessor:()=>Br,escapeHtml:()=>jn,extractComponentDirectiveFromMessage:()=>ss,fileToImagePart:()=>zr,generateAssistantMessageId:()=>sn,generateCodeSnippet:()=>bi,generateMessageId:()=>Nr,generateUserMessageId:()=>En,getDisplayText:()=>Dr,getHeaderLayout:()=>vs,getImageParts:()=>qr,hasComponentDirective:()=>ns,hasImages:()=>_r,headerLayouts:()=>Gn,initAgentWidget:()=>Ps,isComponentDirectiveType:()=>ci,markdownPostprocessor:()=>gs,mergeWithDefaults:()=>Qn,normalizeContent:()=>jr,pluginRegistry:()=>Ln,renderComponentDirective:()=>ts,validateImageFile:()=>Jr});module.exports=Li(wa);var Wr=require("marked"),Pi=e=>{if(e)return e},Tn=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=Pi(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},Mn=e=>e?Tn({markedOptions:e.options,renderer:e.renderer}):Tn(),Hi=Tn(),gs=e=>Hi(e),jn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Lr=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),kr=e=>`%%FORM_PLACEHOLDER_${e}%%`,Pr=(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=kr(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=kr(n.length);return n.push({token:s,type:r}),s}),o},Hr=e=>{let n=Mn(e);return o=>{let t=[],r=Pr(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="${Lr(a)}"></div>`;s=s.replace(d,f)}),s}},Br=e=>{let n=[],o=Pr(e,n),t=gs(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="${Lr(s)}"></div>`;t=t.replace(i,d)}),t};var _t=require("partial-json"),Dn=e=>e.replace(/\\n/g,`
2
2
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ms=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)}},Bi=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`},Ir=e=>e.status==="complete"?Bi(e):e.status==="pending"?"Waiting":"",Ii=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 Rr=e=>e.status==="complete"?Ii(e):"Using tool...",Ri=()=>{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()=>{}}},_n=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},qn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Un=()=>{var n;let e=Ri();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)}},zn=()=>{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"?Dn(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Dn(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Fr=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Dn(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Dn(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:()=>{}}},Jn=()=>{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 Fi="https://api.runtype.com/v1/dispatch",$r="https://api.runtype.com",Or=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 $i(e){switch(e){case"json":return zn;case"regex-json":return Un;case"xml":return Jn;case"plain":default:return qn}}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:Fi,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:$i(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$/,""))||$r;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$/,""))||$r}/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(Or).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(Or).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 He,X,D,nt,lt,dt,Lt,Ft,q,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,xt,St,ie,Ye,Ze,ke,Ke,Wt,ft,rt,H,wt,yt,At,te,we,Fe,vt,et,Bt,It,Ot,nn,Nt,Le,gn,mn,jt,Bn,In,hn,Yt;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=L=>{let ae=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,xe=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,De=L.tools?L.tools.map(tt=>({...tt,chunks:tt.chunks?[...tt.chunks]:void 0})):void 0;return{...L,reasoning:ae,toolCall:xe,tools:De}},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}},R=L=>{var ae,xe,De,tt,Ve;return S((Ve=(tt=(De=(xe=(ae=L.stepId)!=null?ae:L.step_id)!=null?xe:L.step)!=null?De:L.parentId)!=null?tt:L.flowStepId)!=null?Ve:L.flow_step_id)},v=L=>{var ae,xe,De,tt,Ve,Pe,E;return S((E=(Pe=(Ve=(tt=(De=(xe=(ae=L.callId)!=null?ae:L.call_id)!=null?xe:L.requestId)!=null?De:L.request_id)!=null?tt:L.toolCallId)!=null?Ve:L.tool_call_id)!=null?Pe: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,ae)=>{T.lastId=ae,L&&T.byStep.set(L,ae)},k=(L,ae)=>{var Ve;let xe=(Ve=L.reasoningId)!=null?Ve:L.id,De=R(L);if(xe){let Pe=String(xe);return C(De,Pe),Pe}if(De){let Pe=T.byStep.get(De);if(Pe)return T.lastId=Pe,Pe}if(T.lastId&&!ae)return T.lastId;if(!ae)return null;let tt=`reason-${u()}`;return C(De,tt),tt},K=L=>{let ae=h.get(L);if(ae)return ae;let xe={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,xe),g(xe),xe},J=(L,ae)=>{y.lastId=ae,L&&y.byCall.set(L,ae)},z=(L,ae)=>{var Ve;let xe=(Ve=L.toolId)!=null?Ve:L.id,De=v(L);if(xe){let Pe=String(xe);return J(De,Pe),Pe}if(De){let Pe=y.byCall.get(De);if(Pe)return y.lastId=Pe,Pe}if(y.lastId&&!ae)return y.lastId;if(!ae)return null;let tt=`tool-${u()}`;return J(De,tt),tt},_=L=>{let ae=F.get(L);if(ae)return ae;let xe={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,xe),g(xe),xe},j=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let ae=Number(L);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let xe=Date.parse(L);if(!Number.isNaN(xe))return xe}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},B=new Map,V=new Map;for(;;){let{done:L,value:ae}=await r.read();if(L)break;i+=s.decode(ae,{stream:!0});let xe=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()=>{}}},_n=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},qn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Un=()=>{var n;let e=Ri();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)}},zn=()=>{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"?Dn(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Dn(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Fr=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Dn(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Dn(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:()=>{}}},Jn=()=>{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 Fi="https://api.runtype.com/v1/dispatch",$r="https://api.runtype.com",Or=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 $i(e){switch(e){case"json":return zn;case"regex-json":return Un;case"xml":return Jn;case"plain":default:return qn}}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:Fi,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:$i(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$/,""))||$r;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$/,""))||$r}/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,p={session_id:d.sessionId,messages:n.messages.filter(Or).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",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),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(Or).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 He,X,D,nt,lt,dt,Lt,Ft,q,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,xt,St,ie,Ye,Ze,We,Ke,kt,ft,rt,H,wt,yt,At,te,we,Fe,vt,et,Bt,It,Ot,nn,Nt,Le,mn,hn,jt,Bn,In,fn,Yt;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=L=>{let ae=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,xe=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,De=L.tools?L.tools.map(tt=>({...tt,chunks:tt.chunks?[...tt.chunks]:void 0})):void 0;return{...L,reasoning:ae,toolCall:xe,tools:De}},p=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}},R=L=>{var ae,xe,De,tt,Ve;return S((Ve=(tt=(De=(xe=(ae=L.stepId)!=null?ae:L.step_id)!=null?xe:L.step)!=null?De:L.parentId)!=null?tt:L.flowStepId)!=null?Ve:L.flow_step_id)},v=L=>{var ae,xe,De,tt,Ve,Pe,E;return S((E=(Pe=(Ve=(tt=(De=(xe=(ae=L.callId)!=null?ae:L.call_id)!=null?xe:L.requestId)!=null?De:L.request_id)!=null?tt:L.toolCallId)!=null?Ve:L.tool_call_id)!=null?Pe: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()},p(m),m),C=(L,ae)=>{T.lastId=ae,L&&T.byStep.set(L,ae)},W=(L,ae)=>{var Ve;let xe=(Ve=L.reasoningId)!=null?Ve:L.id,De=R(L);if(xe){let Pe=String(xe);return C(De,Pe),Pe}if(De){let Pe=T.byStep.get(De);if(Pe)return T.lastId=Pe,Pe}if(T.lastId&&!ae)return T.lastId;if(!ae)return null;let tt=`reason-${u()}`;return C(De,tt),tt},K=L=>{let ae=h.get(L);if(ae)return ae;let xe={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,xe),p(xe),xe},J=(L,ae)=>{y.lastId=ae,L&&y.byCall.set(L,ae)},z=(L,ae)=>{var Ve;let xe=(Ve=L.toolId)!=null?Ve:L.id,De=v(L);if(xe){let Pe=String(xe);return J(De,Pe),Pe}if(De){let Pe=y.byCall.get(De);if(Pe)return y.lastId=Pe,Pe}if(y.lastId&&!ae)return y.lastId;if(!ae)return null;let tt=`tool-${u()}`;return J(De,tt),tt},_=L=>{let ae=F.get(L);if(ae)return ae;let xe={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,xe),p(xe),xe},j=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let ae=Number(L);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let xe=Date.parse(L);if(!Number.isNaN(xe))return xe}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},B=new Map,V=new Map;for(;;){let{done:L,value:ae}=await r.read();if(L)break;i+=s.decode(ae,{stream:!0});let xe=i.split(`
5
5
 
6
6
  `);i=(He=xe.pop())!=null?He:"";for(let De of xe){let tt=De.split(`
7
- `),Ve="message",Pe="";for(let se of tt)se.startsWith("event:")?Ve=se.replace("event:","").trim():se.startsWith("data:")&&(Pe+=se.replace("data:","").trim());if(!Pe)continue;let E;try{E=JSON.parse(Pe)}catch(se){o({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let bt=Ve!=="message"?Ve:(X=E.type)!=null?X:"message";if(this.parseSSEEvent){w.current=m;let se=await this.handleCustomSSEEvent(E,o,w,g,u);if(w.current&&!m&&(m=w.current),se)continue}if(bt==="reason_start"){let se=(D=k(E,!0))!=null?D:`reason-${u()}`,I=K(se);I.reasoning=(nt=I.reasoning)!=null?nt:{id:se,status:"streaming",chunks:[]},I.reasoning.startedAt=(dt=I.reasoning.startedAt)!=null?dt:j((lt=E.startedAt)!=null?lt:E.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",g(I)}else if(bt==="reason_chunk"){let se=(Ft=(Lt=k(E,!1))!=null?Lt:k(E,!0))!=null?Ft:`reason-${u()}`,I=K(se);I.reasoning=(q=I.reasoning)!=null?q:{id:se,status:"streaming",chunks:[]},I.reasoning.startedAt=(ct=I.reasoning.startedAt)!=null?ct:j((fe=E.startedAt)!=null?fe:E.timestamp);let W=(pt=(Je=(ut=E.reasoningText)!=null?ut:E.text)!=null?Je:E.delta)!=null?pt:"";if(W&&E.hidden!==!0&&I.reasoning.chunks.push(String(W)),I.reasoning.status=E.done?"complete":"streaming",E.done){I.reasoning.completedAt=j(($t=E.completedAt)!=null?$t:E.timestamp);let U=(Pt=I.reasoning.startedAt)!=null?Pt:Date.now();I.reasoning.durationMs=Math.max(0,((Ht=I.reasoning.completedAt)!=null?Ht:Date.now())-U)}I.streaming=I.reasoning.status!=="complete",g(I)}else if(bt==="reason_complete"){let se=(je=($=k(E,!1))!=null?$:k(E,!0))!=null?je:`reason-${u()}`,I=h.get(se);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=j((pe=E.completedAt)!=null?pe:E.timestamp);let U=(st=I.reasoning.startedAt)!=null?st:Date.now();I.reasoning.durationMs=Math.max(0,((ge=I.reasoning.completedAt)!=null?ge:Date.now())-U),I.streaming=!1,g(I)}let W=R(E);W&&T.byStep.delete(W)}else if(bt==="tool_start"){let se=(ot=z(E,!0))!=null?ot:`tool-${u()}`,I=_(se),W=(Ae=I.toolCall)!=null?Ae:{id:se,status:"pending"};W.name=(xt=E.toolName)!=null?xt:W.name,W.status="running",E.args!==void 0&&(W.args=E.args),W.startedAt=(ie=W.startedAt)!=null?ie:j((St=E.startedAt)!=null?St:E.timestamp),W.completedAt=void 0,W.durationMs=void 0,I.toolCall=W,I.streaming=!0,g(I)}else if(bt==="tool_chunk"){let se=(Ze=(Ye=z(E,!1))!=null?Ye:z(E,!0))!=null?Ze:`tool-${u()}`,I=_(se),W=(ke=I.toolCall)!=null?ke:{id:se,status:"running"};W.startedAt=(Wt=W.startedAt)!=null?Wt:j((Ke=E.startedAt)!=null?Ke:E.timestamp);let U=(H=(rt=(ft=E.text)!=null?ft:E.delta)!=null?rt:E.message)!=null?H:"";U&&(W.chunks=(wt=W.chunks)!=null?wt:[],W.chunks.push(String(U))),W.status="running",I.toolCall=W,I.streaming=!0,g(I)}else if(bt==="tool_complete"){let se=(At=(yt=z(E,!1))!=null?yt:z(E,!0))!=null?At:`tool-${u()}`,I=_(se),W=(te=I.toolCall)!=null?te:{id:se,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((we=E.completedAt)!=null?we:E.timestamp),typeof E.duration=="number")W.durationMs=E.duration;else{let me=(Fe=W.startedAt)!=null?Fe:Date.now();W.durationMs=Math.max(0,((vt=W.completedAt)!=null?vt:Date.now())-me)}I.toolCall=W,I.streaming=!1,g(I);let U=v(E);U&&y.byCall.delete(U)}else if(bt==="step_chunk"){let se=E.stepType,I=E.executionType;if(se==="tool"||I==="context")continue;let W=N(),U=(Ot=(It=(Bt=(et=E.text)!=null?et:E.delta)!=null?Bt:E.content)!=null?It:E.chunk)!=null?Ot:"";if(U){let Te=((nn=V.get(W.id))!=null?nn:"")+U;W.rawContent=Te,B.has(W.id)||B.set(W.id,this.createStreamParser());let Xe=B.get(W.id),Ie=Te.trim().startsWith("{")||Te.trim().startsWith("[");if(Ie&&V.set(W.id,Te),Xe.__isPlainTextParser===!0){W.content+=U,V.delete(W.id),B.delete(W.id),W.rawContent=void 0,g(W);continue}let We=Xe.processChunk(Te);if(We instanceof Promise)We.then(be=>{var Ge;let Ce=typeof be=="string"?be:(Ge=be==null?void 0:be.text)!=null?Ge:null;if(Ce!==null&&Ce.trim()!==""){let Me=m;Me&&Me.id===W.id&&(Me.content=Ce,g(Me))}else if(!Ie&&!Te.trim().startsWith("<")){let Me=m;Me&&Me.id===W.id&&(Me.content+=U,V.delete(Me.id),B.delete(Me.id),Me.rawContent=void 0,g(Me))}}).catch(()=>{W.content+=U,V.delete(W.id),B.delete(W.id),W.rawContent=void 0,g(W)});else{let be=typeof We=="string"?We:(Nt=We==null?void 0:We.text)!=null?Nt:null;be!==null&&be.trim()!==""?(W.content=be,g(W)):!Ie&&!Te.trim().startsWith("<")&&(W.content+=U,V.delete(W.id),B.delete(W.id),W.rawContent=void 0,g(W))}}if(E.isComplete){let me=(gn=(Le=E.result)==null?void 0:Le.response)!=null?gn:W.content;if(me){let Te=V.get(W.id),Xe=Te!=null?Te:Y(me);W.rawContent=Xe;let Ie=B.get(W.id),_e=null,We=!1;if(Ie&&(_e=Ie.getExtractedText(),_e===null&&(_e=_n(Xe)),_e===null)){let be=Ie.processChunk(Xe);be instanceof Promise?(We=!0,be.then(Ce=>{var Me;let Ge=typeof Ce=="string"?Ce:(Me=Ce==null?void 0:Ce.text)!=null?Me:null;if(Ge!==null){let Re=m;Re&&Re.id===W.id&&(Re.content=Ge,Re.streaming=!1,B.delete(Re.id),V.delete(Re.id),g(Re))}})):_e=typeof be=="string"?be:(mn=be==null?void 0:be.text)!=null?mn:null}if(!We){_e!==null&&_e.trim()!==""?W.content=_e:V.has(W.id)||(W.content=Y(me));let be=B.get(W.id);if(be){let Ce=(jt=be.close)==null?void 0:jt.call(be);Ce instanceof Promise&&Ce.catch(()=>{}),B.delete(W.id)}V.delete(W.id),W.streaming=!1,g(W)}}}}else if(bt==="step_complete"){let se=E.stepType,I=E.executionType;if(se==="tool"||I==="context")continue;let W=(Bn=E.result)==null?void 0:Bn.response,U=N();if(W!=null){let me=B.get(U.id),Te=!1,Xe=!1;if(me){let Ie=me.getExtractedText(),_e=V.get(U.id),We=_e!=null?_e:Y(W);if(U.rawContent=We,Ie!==null&&Ie.trim()!=="")U.content=Ie,Te=!0;else{let be=_n(We);if(be!==null)U.content=be,Te=!0;else{let Ce=me.processChunk(We);if(Ce instanceof Promise)Xe=!0,Ce.then(Ge=>{var Re;let Me=typeof Ge=="string"?Ge:(Re=Ge==null?void 0:Ge.text)!=null?Re:null;if(Me!==null&&Me.trim()!==""){let le=m;le&&le.id===U.id&&(le.content=Me,le.streaming=!1,B.delete(le.id),V.delete(le.id),g(le))}else{let le=me.getExtractedText(),he=m;he&&he.id===U.id&&(le!==null&&le.trim()!==""?he.content=le:V.has(he.id)||(he.content=Y(W)),he.streaming=!1,B.delete(he.id),V.delete(he.id),g(he))}});else{let Ge=typeof Ce=="string"?Ce:(In=Ce==null?void 0:Ce.text)!=null?In:null;if(Ge!==null&&Ge.trim()!=="")U.content=Ge,Te=!0;else{let Me=me.getExtractedText();Me!==null&&Me.trim()!==""&&(U.content=Me,Te=!0)}}}}}if(!Xe){if(!U.rawContent){let Ie=V.get(U.id);U.rawContent=Ie!=null?Ie:Y(W)}if(!Te&&!V.has(U.id)&&(U.content=Y(W)),me){let Ie=(hn=me.close)==null?void 0:hn.call(me);Ie instanceof Promise&&Ie.catch(()=>{})}B.delete(U.id),V.delete(U.id),U.streaming=!1,g(U)}}else B.delete(U.id),V.delete(U.id),U.streaming=!1,g(U)}else if(bt==="flow_complete"){let se=(Yt=E.result)==null?void 0:Yt.response;if(se!=null){let I=N(),W=V.get(I.id),U=W!=null?W:Y(se);I.rawContent=U;let me=Y(se),Te=B.get(I.id);if(Te){let _e=_n(U);if(_e!==null)me=_e;else{let We=Te.processChunk(U);We instanceof Promise&&We.then(Ce=>{var Me;let Ge=typeof Ce=="string"?Ce:(Me=Ce==null?void 0:Ce.text)!=null?Me:null;if(Ge!==null){let Re=m;Re&&Re.id===I.id&&(Re.content=Ge,Re.streaming=!1,g(Re))}});let be=Te.getExtractedText();be!==null&&(me=be)}}B.delete(I.id),V.delete(I.id);let Xe=me!==I.content,Ie=I.streaming!==!1;Xe&&(I.content=me),I.streaming=!1,(Xe||Ie)&&g(I)}else if(m!==null){let I=m;B.delete(I.id),V.delete(I.id),I.streaming!==!1&&(I.streaming=!1,g(I))}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 Nr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Mn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function En(){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"?Mn():o==="assistant"?En():`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=Mn(),s=En(),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 Oi=ki(require("lucide"),1),oe=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Oi[r];return s?Ni(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 Ni(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 jr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Dr(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function _r(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function qr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Yn(e){return{type:"text",text:e}}function Ur(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 zr(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 Jr(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 Yr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ji=["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=[...Yr,...ji];function Di(e){return Yr.includes(e)||e.startsWith("image/")}function Kn(e){return Di(e.type)}async function Kr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Kn(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 Vr(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 _i(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Xr(e,n){let o=_i(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 Vn={allowedTypes:Jt,maxFileSize:10*1024*1024,maxFiles:4};function qi(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ui(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:Vn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Vn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Vn.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:Vn.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=Vr(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 Kr(f),w=Kn(f)?URL.createObjectURL(f):null,h={id:qi(),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=Kn(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=Ui(n.file.type),d=oe(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=p("span");u.textContent=Xr(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=oe("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 hs=()=>{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"},zi=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"||hs()==="dark"?t:o},Gr=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(hs())});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(hs());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())}},Xn=(e,n)=>{let o=zi(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 Qr=require("idiomorph"),Zr=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;Qr.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 mt={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 Wn=(e,n)=>{let o=p("button");o.type="button",o.innerHTML=`
7
+ `),Ve="message",Pe="";for(let se of tt)se.startsWith("event:")?Ve=se.replace("event:","").trim():se.startsWith("data:")&&(Pe+=se.replace("data:","").trim());if(!Pe)continue;let E;try{E=JSON.parse(Pe)}catch(se){o({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let bt=Ve!=="message"?Ve:(X=E.type)!=null?X:"message";if(this.parseSSEEvent){w.current=m;let se=await this.handleCustomSSEEvent(E,o,w,p,u);if(w.current&&!m&&(m=w.current),se)continue}if(bt==="reason_start"){let se=(D=W(E,!0))!=null?D:`reason-${u()}`,I=K(se);I.reasoning=(nt=I.reasoning)!=null?nt:{id:se,status:"streaming",chunks:[]},I.reasoning.startedAt=(dt=I.reasoning.startedAt)!=null?dt:j((lt=E.startedAt)!=null?lt:E.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(bt==="reason_chunk"){let se=(Ft=(Lt=W(E,!1))!=null?Lt:W(E,!0))!=null?Ft:`reason-${u()}`,I=K(se);I.reasoning=(q=I.reasoning)!=null?q:{id:se,status:"streaming",chunks:[]},I.reasoning.startedAt=(ct=I.reasoning.startedAt)!=null?ct:j((fe=E.startedAt)!=null?fe:E.timestamp);let k=(pt=(Je=(ut=E.reasoningText)!=null?ut:E.text)!=null?Je:E.delta)!=null?pt:"";if(k&&E.hidden!==!0&&I.reasoning.chunks.push(String(k)),I.reasoning.status=E.done?"complete":"streaming",E.done){I.reasoning.completedAt=j(($t=E.completedAt)!=null?$t:E.timestamp);let U=(Pt=I.reasoning.startedAt)!=null?Pt:Date.now();I.reasoning.durationMs=Math.max(0,((Ht=I.reasoning.completedAt)!=null?Ht:Date.now())-U)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(bt==="reason_complete"){let se=(je=($=W(E,!1))!=null?$:W(E,!0))!=null?je:`reason-${u()}`,I=h.get(se);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=j((pe=E.completedAt)!=null?pe:E.timestamp);let U=(st=I.reasoning.startedAt)!=null?st:Date.now();I.reasoning.durationMs=Math.max(0,((ge=I.reasoning.completedAt)!=null?ge:Date.now())-U),I.streaming=!1,p(I)}let k=R(E);k&&T.byStep.delete(k)}else if(bt==="tool_start"){let se=(ot=z(E,!0))!=null?ot:`tool-${u()}`,I=_(se),k=(Ae=I.toolCall)!=null?Ae:{id:se,status:"pending"};k.name=(xt=E.toolName)!=null?xt:k.name,k.status="running",E.args!==void 0&&(k.args=E.args),k.startedAt=(ie=k.startedAt)!=null?ie:j((St=E.startedAt)!=null?St:E.timestamp),k.completedAt=void 0,k.durationMs=void 0,I.toolCall=k,I.streaming=!0,p(I)}else if(bt==="tool_chunk"){let se=(Ze=(Ye=z(E,!1))!=null?Ye:z(E,!0))!=null?Ze:`tool-${u()}`,I=_(se),k=(We=I.toolCall)!=null?We:{id:se,status:"running"};k.startedAt=(kt=k.startedAt)!=null?kt:j((Ke=E.startedAt)!=null?Ke:E.timestamp);let U=(H=(rt=(ft=E.text)!=null?ft:E.delta)!=null?rt:E.message)!=null?H:"";U&&(k.chunks=(wt=k.chunks)!=null?wt:[],k.chunks.push(String(U))),k.status="running",I.toolCall=k,I.streaming=!0,p(I)}else if(bt==="tool_complete"){let se=(At=(yt=z(E,!1))!=null?yt:z(E,!0))!=null?At:`tool-${u()}`,I=_(se),k=(te=I.toolCall)!=null?te:{id:se,status:"running"};if(k.status="complete",E.result!==void 0&&(k.result=E.result),typeof E.duration=="number"&&(k.duration=E.duration),k.completedAt=j((we=E.completedAt)!=null?we:E.timestamp),typeof E.duration=="number")k.durationMs=E.duration;else{let me=(Fe=k.startedAt)!=null?Fe:Date.now();k.durationMs=Math.max(0,((vt=k.completedAt)!=null?vt:Date.now())-me)}I.toolCall=k,I.streaming=!1,p(I);let U=v(E);U&&y.byCall.delete(U)}else if(bt==="step_chunk"){let se=E.stepType,I=E.executionType;if(se==="tool"||I==="context")continue;let k=N(),U=(Ot=(It=(Bt=(et=E.text)!=null?et:E.delta)!=null?Bt:E.content)!=null?It:E.chunk)!=null?Ot:"";if(U){let Te=((nn=V.get(k.id))!=null?nn:"")+U;k.rawContent=Te,B.has(k.id)||B.set(k.id,this.createStreamParser());let Xe=B.get(k.id),Ie=Te.trim().startsWith("{")||Te.trim().startsWith("[");if(Ie&&V.set(k.id,Te),Xe.__isPlainTextParser===!0){k.content+=U,V.delete(k.id),B.delete(k.id),k.rawContent=void 0,p(k);continue}let ke=Xe.processChunk(Te);if(ke instanceof Promise)ke.then(be=>{var Ge;let Ce=typeof be=="string"?be:(Ge=be==null?void 0:be.text)!=null?Ge:null;if(Ce!==null&&Ce.trim()!==""){let Me=m;Me&&Me.id===k.id&&(Me.content=Ce,p(Me))}else if(!Ie&&!Te.trim().startsWith("<")){let Me=m;Me&&Me.id===k.id&&(Me.content+=U,V.delete(Me.id),B.delete(Me.id),Me.rawContent=void 0,p(Me))}}).catch(()=>{k.content+=U,V.delete(k.id),B.delete(k.id),k.rawContent=void 0,p(k)});else{let be=typeof ke=="string"?ke:(Nt=ke==null?void 0:ke.text)!=null?Nt:null;be!==null&&be.trim()!==""?(k.content=be,p(k)):!Ie&&!Te.trim().startsWith("<")&&(k.content+=U,V.delete(k.id),B.delete(k.id),k.rawContent=void 0,p(k))}}if(E.isComplete){let me=(mn=(Le=E.result)==null?void 0:Le.response)!=null?mn:k.content;if(me){let Te=V.get(k.id),Xe=Te!=null?Te:Y(me);k.rawContent=Xe;let Ie=B.get(k.id),_e=null,ke=!1;if(Ie&&(_e=Ie.getExtractedText(),_e===null&&(_e=_n(Xe)),_e===null)){let be=Ie.processChunk(Xe);be instanceof Promise?(ke=!0,be.then(Ce=>{var Me;let Ge=typeof Ce=="string"?Ce:(Me=Ce==null?void 0:Ce.text)!=null?Me:null;if(Ge!==null){let Re=m;Re&&Re.id===k.id&&(Re.content=Ge,Re.streaming=!1,B.delete(Re.id),V.delete(Re.id),p(Re))}})):_e=typeof be=="string"?be:(hn=be==null?void 0:be.text)!=null?hn:null}if(!ke){_e!==null&&_e.trim()!==""?k.content=_e:V.has(k.id)||(k.content=Y(me));let be=B.get(k.id);if(be){let Ce=(jt=be.close)==null?void 0:jt.call(be);Ce instanceof Promise&&Ce.catch(()=>{}),B.delete(k.id)}V.delete(k.id),k.streaming=!1,p(k)}}}}else if(bt==="step_complete"){let se=E.stepType,I=E.executionType;if(se==="tool"||I==="context")continue;let k=(Bn=E.result)==null?void 0:Bn.response,U=N();if(k!=null){let me=B.get(U.id),Te=!1,Xe=!1;if(me){let Ie=me.getExtractedText(),_e=V.get(U.id),ke=_e!=null?_e:Y(k);if(U.rawContent=ke,Ie!==null&&Ie.trim()!=="")U.content=Ie,Te=!0;else{let be=_n(ke);if(be!==null)U.content=be,Te=!0;else{let Ce=me.processChunk(ke);if(Ce instanceof Promise)Xe=!0,Ce.then(Ge=>{var Re;let Me=typeof Ge=="string"?Ge:(Re=Ge==null?void 0:Ge.text)!=null?Re:null;if(Me!==null&&Me.trim()!==""){let le=m;le&&le.id===U.id&&(le.content=Me,le.streaming=!1,B.delete(le.id),V.delete(le.id),p(le))}else{let le=me.getExtractedText(),he=m;he&&he.id===U.id&&(le!==null&&le.trim()!==""?he.content=le:V.has(he.id)||(he.content=Y(k)),he.streaming=!1,B.delete(he.id),V.delete(he.id),p(he))}});else{let Ge=typeof Ce=="string"?Ce:(In=Ce==null?void 0:Ce.text)!=null?In:null;if(Ge!==null&&Ge.trim()!=="")U.content=Ge,Te=!0;else{let Me=me.getExtractedText();Me!==null&&Me.trim()!==""&&(U.content=Me,Te=!0)}}}}}if(!Xe){if(!U.rawContent){let Ie=V.get(U.id);U.rawContent=Ie!=null?Ie:Y(k)}if(!Te&&!V.has(U.id)&&(U.content=Y(k)),me){let Ie=(fn=me.close)==null?void 0:fn.call(me);Ie instanceof Promise&&Ie.catch(()=>{})}B.delete(U.id),V.delete(U.id),U.streaming=!1,p(U)}}else B.delete(U.id),V.delete(U.id),U.streaming=!1,p(U)}else if(bt==="flow_complete"){let se=(Yt=E.result)==null?void 0:Yt.response;if(se!=null){let I=N(),k=V.get(I.id),U=k!=null?k:Y(se);I.rawContent=U;let me=Y(se),Te=B.get(I.id);if(Te){let _e=_n(U);if(_e!==null)me=_e;else{let ke=Te.processChunk(U);ke instanceof Promise&&ke.then(Ce=>{var Me;let Ge=typeof Ce=="string"?Ce:(Me=Ce==null?void 0:Ce.text)!=null?Me:null;if(Ge!==null){let Re=m;Re&&Re.id===I.id&&(Re.content=Ge,Re.streaming=!1,p(Re))}});let be=Te.getExtractedText();be!==null&&(me=be)}}B.delete(I.id),V.delete(I.id);let Xe=me!==I.content,Ie=I.streaming!==!1;Xe&&(I.content=me),I.streaming=!1,(Xe||Ie)&&p(I)}else if(m!==null){let I=m;B.delete(I.id),V.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}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 Nr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function En(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function sn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var on=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,p={id:i!=null?i:o==="user"?En():o==="assistant"?sn():`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(p),p}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,p,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=En(),s=sn(),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?(p=(f=this.callbacks).onError)==null||p.call(f,h):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(h)))}}async continueConversation(){var r,s,i,a,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let n=sn();this.setStreaming(!0);let o=new AbortController;this.abortController=o;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n},this.handleEvent)}catch(u){let f={id:n,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,u instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,u):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(u)))}}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 g=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var Oi=Wi(require("lucide"),1),oe=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Oi[r];return s?Ni(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 Ni(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 jr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Dr(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function _r(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function qr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Yn(e){return{type:"text",text:e}}function Ur(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 zr(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 Jr(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 Yr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ji=["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=[...Yr,...ji];function Di(e){return Yr.includes(e)||e.startsWith("image/")}function Kn(e){return Di(e.type)}async function Kr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Kn(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 Vr(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 _i(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Xr(e,n){let o=_i(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 Vn={allowedTypes:Jt,maxFileSize:10*1024*1024,maxFiles:4};function qi(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ui(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:Vn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Vn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Vn.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:Vn.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 p=Vr(f,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,m);continue}try{let m=await Kr(f),w=Kn(f)?URL.createObjectURL(f):null,h={id:qi(),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=Kn(n.file),t=g("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=g("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=g("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=Ui(n.file.type),d=oe(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=g("span");u.textContent=Xr(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=g("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=oe("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 hs=()=>{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"},zi=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"||hs()==="dark"?t:o},Gr=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(hs())});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(hs());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())}},Xn=(e,n)=>{let o=zi(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 Qr=require("idiomorph"),Zr=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;Qr.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 mt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Wt={"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 kn=(e,n)=>{let o=g("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,R,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=(R=i.subtitle)!=null?R:"Get answers fast");let u=o.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let 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 B=parseFloat(Y)||24,V=oe(i.agentIconName,B*.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 B=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,B=(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,He=Math.max(V-B,8),X=oe(i.callToActionIconName,He,"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,B,V,He,X,D,nt,lt,dt,Lt,Ft,q,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,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=(B=r.headerIconHidden)!=null?B:!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 ie=parseFloat(s)||24,Ye=oe(u,ie*.6,"#ffffff",2);Ye?f.replaceChildren(Ye):f.textContent=(He=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?He:"\u{1F4AC}"}else if((X=n==null?void 0:n.launcher)!=null&&X.iconUrl){let ie=p("img");ie.src=n.launcher.iconUrl,ie.alt="",ie.className="tvw-rounded-xl tvw-object-cover",ie.style.height=s,ie.style.width=s,f.replaceChildren(ie)}else f.textContent=(nt=(D=n==null?void 0:n.launcher)==null?void 0:D.agentIconText)!=null?nt:"\u{1F4AC}";let g=p("div","tvw-flex tvw-flex-col"),m=p("span","tvw-text-base tvw-font-semibold");m.textContent=(dt=(lt=n==null?void 0:n.launcher)==null?void 0:lt.title)!=null?dt:"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=(fe=h.enabled)!=null?fe:!0,T=(ct=h.placement)!=null?ct:"inline",y=null,S=null;if(F){let ie=(ut=h.size)!=null?ut:"32px",Ye=(Je=h.iconName)!=null?Je:"refresh-cw",Ze=(pt=h.iconColor)!=null?pt:"",ke=($t=h.backgroundColor)!=null?$t:"",Ke=(Pt=h.borderWidth)!=null?Pt:"",Wt=(Ht=h.borderColor)!=null?Ht:"",ft=($=h.borderRadius)!=null?$:"",rt=(je=h.paddingX)!=null?je:"",H=(pe=h.paddingY)!=null?pe:"",wt=(st=h.tooltipText)!=null?st:"Clear chat",yt=(ge=h.showTooltip)!=null?ge:!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=ie,y.style.width=ie,y.type="button",y.setAttribute("aria-label",wt);let At=oe(Ye,"20px",Ze||"",2);if(At&&y.appendChild(At),Ze&&(y.style.color=Ze,y.classList.remove("tvw-text-cw-muted")),ke&&(y.style.backgroundColor=ke,y.classList.remove("hover:tvw-bg-gray-100")),Ke||Wt){let te=Ke||"0px",we=Wt||"transparent";y.style.border=`${te} solid ${we}`,y.classList.remove("tvw-border-none")}if(ft&&(y.style.borderRadius=ft,y.classList.remove("tvw-rounded-full")),rt?(y.style.paddingLeft=rt,y.style.paddingRight=rt):(y.style.paddingLeft="",y.style.paddingRight=""),H?(y.style.paddingTop=H,y.style.paddingBottom=H):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),yt&&wt&&y&&S){let te=null,we=()=>{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 et=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${et.left+et.width/2}px`,te.style.top=`${et.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Fe=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};S.addEventListener("mouseenter",we),S.addEventListener("mouseleave",Fe),y.addEventListener("focus",we),y.addEventListener("blur",Fe),S._cleanupTooltip=()=>{Fe(),S&&(S.removeEventListener("mouseenter",we),S.removeEventListener("mouseleave",Fe)),y&&(y.removeEventListener("focus",we),y.removeEventListener("blur",Fe))}}T==="inline"&&t.appendChild(S)}let R=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=(ot=r.closeButtonTooltipText)!=null?ot:"Close chat",C=(Ae=r.closeButtonShowTooltip)!=null?Ae:!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=oe(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 ie=r.closeButtonBorderWidth||"0px",Ye=r.closeButtonBorderColor||"transparent";v.style.border=`${ie} solid ${Ye}`,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=""),R.appendChild(v),C&&N){let ie=null,Ye=()=>{if(ie)return;ie=p("div","tvw-clear-chat-tooltip"),ie.textContent=N;let ke=p("div");ke.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(ke);let Ke=v.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Ke.left+Ke.width/2}px`,ie.style.top=`${Ke.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ze=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};R.addEventListener("mouseenter",Ye),R.addEventListener("mouseleave",Ze),v.addEventListener("focus",Ye),v.addEventListener("blur",Ze),R._cleanupTooltip=()=>{Ze(),R.removeEventListener("mouseenter",Ye),R.removeEventListener("mouseleave",Ze),v.removeEventListener("focus",Ye),v.removeEventListener("blur",Ze)}}return a!=="top-right"&&t.appendChild(R),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:v,closeButtonWrapper:R,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 fs=e=>qt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),ws=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=oe(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}},ys=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=oe(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=oe(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 R=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return R.textContent="Online and ready to help",i.appendChild(R),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:T,closeButtonWrapper:F,clearChatButton:null,clearChatButtonWrapper:null}},Gn={default:fs,minimal:ws,expanded:ys},vs=e=>{var n;return(n=Gn[e])!=null?n:Gn.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=vs(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 Ji=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,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,xt,St,ie,Ye,Ze,ke,Ke,Wt,ft,rt,H,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=(fe=(q=n==null?void 0:n.copy)==null?void 0:q.inputPlaceholder)!=null?fe:"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=(ut=(ct=n==null?void 0:n.theme)==null?void 0:ct.inputFontFamily)!=null?ut:"sans-serif",a=(pt=(Je=n==null?void 0:n.theme)==null?void 0:Je.inputFontWeight)!=null?pt:"400";s.style.fontFamily=Ji(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=(je=m.showTooltip)!=null?je:!1,S=(pe=m.size)!=null?pe:"40px",R=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,we=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Fe=oe(F,te,we,2);Fe?(C.appendChild(Fe),C.style.color=we):(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");R?C.style.backgroundColor=R:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(ge=(st=n==null?void 0:n.copy)==null?void 0:st.sendButtonLabel)!=null?ge:"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=(ot=n==null?void 0:n.voiceRecognition)!=null?ot:{},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=(Ae=k.iconName)!=null?Ae:"mic",we=(xt=k.iconSize)!=null?xt:S,Fe=parseFloat(we)||24,vt=(St=k.backgroundColor)!=null?St:R,et=(ie=k.iconColor)!=null?ie:v;J.style.width=we,J.style.height=we,J.style.minWidth=we,J.style.minHeight=we,J.style.fontSize="18px",J.style.lineHeight="1";let Bt=et||"currentColor",It=oe(te,Fe,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"),et?J.style.color=et:!et&&!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=(Ye=k.tooltipText)!=null?Ye:"Start voice recognition";if(((Ze=k.showTooltip)!=null?Ze:!1)&&Ot){let Nt=p("div","tvw-send-button-tooltip");Nt.textContent=Ot,z.appendChild(Nt)}}let j=(ke=n==null?void 0:n.attachments)!=null?ke:{},Y=j.enabled===!0,B=null,V=null,He=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",He=p("input"),He.type="file",He.accept=((Ke=j.allowedTypes)!=null?Ke:Jt).join(","),He.multiple=((Wt=j.maxFiles)!=null?Wt:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),V=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 tvw-attachment-button"),B.type="button",B.setAttribute("aria-label",(ft=j.buttonTooltipText)!=null?ft:"Attach file");let te=(rt=j.buttonIconName)!=null?rt:"paperclip",we=S,Fe=parseFloat(we)||40,vt=Math.round(Fe*.6);B.style.width=we,B.style.height=we,B.style.minWidth=we,B.style.minHeight=we,B.style.fontSize="18px",B.style.lineHeight="1",B.style.backgroundColor="transparent",B.style.color="var(--cw-primary, #111827)",B.style.border="none",B.style.borderRadius="6px",B.style.transition="background-color 0.15s ease",B.addEventListener("mouseenter",()=>{B.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),B.addEventListener("mouseleave",()=>{B.style.backgroundColor="transparent"});let et=oe(te,vt,"currentColor",1.5);et?B.appendChild(et):B.textContent="\u{1F4CE}",B.addEventListener("click",Ot=>{Ot.preventDefault(),He==null||He.click()}),V.appendChild(B);let Bt=(H=j.buttonTooltipText)!=null?H:"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!==B&&te.target!==V&&s.focus()}),X&&(X.style.gap="8px",r.append(X)),He&&r.append(He),r.append(s);let D=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),nt=p("div","tvw-flex tvw-items-center tvw-gap-2");V&&nt.append(V);let lt=p("div","tvw-flex tvw-items-center tvw-gap-1");z&&lt.append(z),lt.append(N),D.append(nt,lt),r.append(D);let dt=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 dt.style.display=Ft?"":"none",dt.textContent=(At=Lt.idleText)!=null?At:"Online",o.append(t,r,dt),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:N,micButton:J,micButtonWrapper:z,statusText:dt,attachmentButton:B,attachmentButtonWrapper:V,attachmentInput:He,attachmentPreviewsContainer:X,actionsRow:D,leftActions:nt,rightActions:lt}};var ei=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}},ti=(e,n=!0)=>{var w,h,F,T,y,S,R;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=((R=e==null?void 0:e.layout)==null?void 0:R.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 kn=()=>{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},Yi=(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},ni=(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},Ki=(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},bs=(e,n,o)=>{var h,F,T,y,S,R;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=(R=n.layout)!=null?R:"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=oe(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=oe("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=oe("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 R,v,N,C,k;let s=o!=null?o:{},i=(R=s.layout)!=null?R:"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=Ki(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=ni(e,d);K.classList.add("tvw-ml-2","tvw-inline"),F.appendChild(K)}if(h.appendChild(F),f&&m==="below"&&e.createdAt){let K=ni(e,d);K.classList.add("tvw-mt-1"),h.appendChild(K)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let K=kn();h.appendChild(K)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let K=bs(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=Yi(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},si=(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,oi=(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=oe(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},Cs=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=Ir(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),f=oe(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=oe(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,ri=(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=oe(t?"chevron-up":"chevron-down",16,f,2);g?d.appendChild(g):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},xs=(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=Rr(o),a.appendChild(d);let u=p("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",g=oe(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=ms(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=ms(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=oe(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 ii=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 ai={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"}},Ss=(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=ai[i])!=null?F:ai.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 R=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");R.textContent=y.label,S.appendChild(R);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",R=new FormData(f),v={};R.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 As=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()}},Ln=new As;var Ts={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"},Ms={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:Ts,darkTheme:Ms,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 Qn(e){var n,o,t,r,s,i,a,d,u,f,g,m,w,h,F,T,y,S,R;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,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var li=()=>{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 Vi=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Xi=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},Pn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Vi(e),o=Xi(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}},Es=e=>typeof e=="string"?e:e==null?"":String(e),en={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Es(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Es(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:Es(o.text)}}},di=e=>Array.isArray(e)?e.map(n=>String(n)):[],Hn=e=>{let n=new Set(di(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(di(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,m=f.displayText!==void 0?f.displayText:"";return f.resubmit&&e.emit("action:resubmit",d),{text:m,persist:g,resubmit:f.resubmit}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var Gi=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}},Qi=e=>e.map(n=>({...n,streaming:!1})),Zn=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?Gi(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?Qi(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 Ws=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 Ws;var un=require("partial-json");function Zi(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function ea(e,n){if(!Zi(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 es(){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=ea(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function ci(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ts(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 ui(){let e=es();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ns(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 ss(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 ta=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function os(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=ta}=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=`
15
+ `,o.addEventListener("click",n);let t=s=>{var y,S,R,v,N,C,W,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=(R=i.subtitle)!=null?R:"Get answers fast");let u=o.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let 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 B=parseFloat(Y)||24,V=oe(i.agentIconName,B*.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 p=o.querySelector("[data-role='launcher-image']");if(p){let Y=(W=i.agentIconSize)!=null?W:"40px";p.style.height=Y,p.style.width=Y,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(p.src=i.iconUrl,p.style.display="block"):p.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 B=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,B=(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,He=Math.max(V-B,8),X=oe(i.callToActionIconName,He,"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&&Wt[i.position]?Wt[i.position]:Wt["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,B,V,He,X,D,nt,lt,dt,Lt,Ft,q,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,xt,St;let{config:n,showClose:o=!0}=e,t=g("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=(B=r.headerIconHidden)!=null?B:!1,u=r.headerIconName,f=g("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 ie=parseFloat(s)||24,Ye=oe(u,ie*.6,"#ffffff",2);Ye?f.replaceChildren(Ye):f.textContent=(He=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?He:"\u{1F4AC}"}else if((X=n==null?void 0:n.launcher)!=null&&X.iconUrl){let ie=g("img");ie.src=n.launcher.iconUrl,ie.alt="",ie.className="tvw-rounded-xl tvw-object-cover",ie.style.height=s,ie.style.width=s,f.replaceChildren(ie)}else f.textContent=(nt=(D=n==null?void 0:n.launcher)==null?void 0:D.agentIconText)!=null?nt:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(dt=(lt=n==null?void 0:n.launcher)==null?void 0:lt.title)!=null?dt:"Chat Assistant";let w=g("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",p.append(m,w),d?t.append(p):t.append(f,p);let h=(q=r.clearChat)!=null?q:{},F=(fe=h.enabled)!=null?fe:!0,T=(ct=h.placement)!=null?ct:"inline",y=null,S=null;if(F){let ie=(ut=h.size)!=null?ut:"32px",Ye=(Je=h.iconName)!=null?Je:"refresh-cw",Ze=(pt=h.iconColor)!=null?pt:"",We=($t=h.backgroundColor)!=null?$t:"",Ke=(Pt=h.borderWidth)!=null?Pt:"",kt=(Ht=h.borderColor)!=null?Ht:"",ft=($=h.borderRadius)!=null?$:"",rt=(je=h.paddingX)!=null?je:"",H=(pe=h.paddingY)!=null?pe:"",wt=(st=h.tooltipText)!=null?st:"Clear chat",yt=(ge=h.showTooltip)!=null?ge:!0;S=g("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=g("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=ie,y.style.width=ie,y.type="button",y.setAttribute("aria-label",wt);let At=oe(Ye,"20px",Ze||"",2);if(At&&y.appendChild(At),Ze&&(y.style.color=Ze,y.classList.remove("tvw-text-cw-muted")),We&&(y.style.backgroundColor=We,y.classList.remove("hover:tvw-bg-gray-100")),Ke||kt){let te=Ke||"0px",we=kt||"transparent";y.style.border=`${te} solid ${we}`,y.classList.remove("tvw-border-none")}if(ft&&(y.style.borderRadius=ft,y.classList.remove("tvw-rounded-full")),rt?(y.style.paddingLeft=rt,y.style.paddingRight=rt):(y.style.paddingLeft="",y.style.paddingRight=""),H?(y.style.paddingTop=H,y.style.paddingBottom=H):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),yt&&wt&&y&&S){let te=null,we=()=>{if(te||!y)return;te=g("div","tvw-clear-chat-tooltip"),te.textContent=wt;let vt=g("div");vt.className="tvw-clear-chat-tooltip-arrow",te.appendChild(vt);let et=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${et.left+et.width/2}px`,te.style.top=`${et.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Fe=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};S.addEventListener("mouseenter",we),S.addEventListener("mouseleave",Fe),y.addEventListener("focus",we),y.addEventListener("blur",Fe),S._cleanupTooltip=()=>{Fe(),S&&(S.removeEventListener("mouseenter",we),S.removeEventListener("mouseleave",Fe)),y&&(y.removeEventListener("focus",we),y.removeEventListener("blur",Fe))}}T==="inline"&&t.appendChild(S)}let R=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":F&&T==="inline"?"":"tvw-ml-auto"),v=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let N=(ot=r.closeButtonTooltipText)!=null?ot:"Close chat",C=(Ae=r.closeButtonShowTooltip)!=null?Ae:!0;v.setAttribute("aria-label",N),v.style.display=o?"":"none";let W=(xt=r.closeButtonIconName)!=null?xt:"x",K=(St=r.closeButtonIconText)!=null?St:"\xD7",J=oe(W,"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 ie=r.closeButtonBorderWidth||"0px",Ye=r.closeButtonBorderColor||"transparent";v.style.border=`${ie} solid ${Ye}`,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=""),R.appendChild(v),C&&N){let ie=null,Ye=()=>{if(ie)return;ie=g("div","tvw-clear-chat-tooltip"),ie.textContent=N;let We=g("div");We.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(We);let Ke=v.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Ke.left+Ke.width/2}px`,ie.style.top=`${Ke.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ze=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};R.addEventListener("mouseenter",Ye),R.addEventListener("mouseleave",Ze),v.addEventListener("focus",Ye),v.addEventListener("blur",Ze),R._cleanupTooltip=()=>{Ze(),R.removeEventListener("mouseenter",Ye),R.removeEventListener("mouseleave",Ze),v.removeEventListener("focus",Ye),v.removeEventListener("blur",Ze)}}return a!=="top-right"&&t.appendChild(R),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:v,closeButtonWrapper:R,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 fs=e=>qt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),ws=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=g("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=g("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=g("div",""),u=g("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",p=oe(f,"20px",r.closeButtonColor||"",2);p?u.appendChild(p):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),s.appendChild(d);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},ys=e=>{var v,N,C,W,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=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=s.headerIconSize)!=null?N:"56px",u=g("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=oe(f,j*.5,"#ffffff",2);Y?u.replaceChildren(Y):u.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let j=g("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=(W=s.agentIconText)!=null?W:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(K=s.title)!=null?K:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(J=s.subtitle)!=null?J:"Here to help you get answers fast",p.append(m,w),a.append(u,p);let h=(z=s.closeButtonSize)!=null?z:"32px",F=g("div",""),T=g("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=oe(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 R=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return R.textContent="Online and ready to help",i.appendChild(R),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:T,closeButtonWrapper:F,clearChatButton:null,clearChatButtonWrapper:null}},Gn={default:fs,minimal:ws,expanded:ys},vs=e=>{var n;return(n=Gn[e])!=null?n:Gn.default},rn=(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=g("div");f.style.display="none";let p=g("span"),m=g("span"),w=g("button");w.style.display="none";let h=g("div");return h.style.display="none",{header:u,iconHolder:f,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=vs(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 Ji=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'}},an=e=>{var q,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,xt,St,ie,Ye,Ze,We,Ke,kt,ft,rt,H,wt,yt,At;let{config:n}=e,o=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=g("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=g("textarea");s.placeholder=(fe=(q=n==null?void 0:n.copy)==null?void 0:q.inputPlaceholder)!=null?fe:"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=(ut=(ct=n==null?void 0:n.theme)==null?void 0:ct.inputFontFamily)!=null?ut:"sans-serif",a=(pt=(Je=n==null?void 0:n.theme)==null?void 0:Je.inputFontWeight)!=null?pt:"400";s.style.fontFamily=Ji(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",p),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=(je=m.showTooltip)!=null?je:!1,S=(pe=m.size)!=null?pe:"40px",R=m.backgroundColor,v=m.textColor,N=g("div","tvw-send-button-wrapper"),C=g("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,we=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Fe=oe(F,te,we,2);Fe?(C.appendChild(Fe),C.style.color=we):(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");R?C.style.backgroundColor=R:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(ge=(st=n==null?void 0:n.copy)==null?void 0:st.sendButtonLabel)!=null?ge:"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=g("div","tvw-send-button-tooltip");te.textContent=T,N.appendChild(te)}N.appendChild(C);let W=(ot=n==null?void 0:n.voiceRecognition)!=null?ot:{},K=W.enabled===!0,J=null,z=null,_=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(K&&_){z=g("div","tvw-send-button-wrapper"),J=g("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=(Ae=W.iconName)!=null?Ae:"mic",we=(xt=W.iconSize)!=null?xt:S,Fe=parseFloat(we)||24,vt=(St=W.backgroundColor)!=null?St:R,et=(ie=W.iconColor)!=null?ie:v;J.style.width=we,J.style.height=we,J.style.minWidth=we,J.style.minHeight=we,J.style.fontSize="18px",J.style.lineHeight="1";let Bt=et||"currentColor",It=oe(te,Fe,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"),et?J.style.color=et:!et&&!v&&J.classList.add("tvw-text-white"),W.borderWidth&&(J.style.borderWidth=W.borderWidth,J.style.borderStyle="solid"),W.borderColor&&(J.style.borderColor=W.borderColor),W.paddingX&&(J.style.paddingLeft=W.paddingX,J.style.paddingRight=W.paddingX),W.paddingY&&(J.style.paddingTop=W.paddingY,J.style.paddingBottom=W.paddingY),z.appendChild(J);let Ot=(Ye=W.tooltipText)!=null?Ye:"Start voice recognition";if(((Ze=W.showTooltip)!=null?Ze:!1)&&Ot){let Nt=g("div","tvw-send-button-tooltip");Nt.textContent=Ot,z.appendChild(Nt)}}let j=(We=n==null?void 0:n.attachments)!=null?We:{},Y=j.enabled===!0,B=null,V=null,He=null,X=null;if(Y){X=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),X.style.display="none",He=g("input"),He.type="file",He.accept=((Ke=j.allowedTypes)!=null?Ke:Jt).join(","),He.multiple=((kt=j.maxFiles)!=null?kt:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),V=g("div","tvw-send-button-wrapper"),B=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),B.type="button",B.setAttribute("aria-label",(ft=j.buttonTooltipText)!=null?ft:"Attach file");let te=(rt=j.buttonIconName)!=null?rt:"paperclip",we=S,Fe=parseFloat(we)||40,vt=Math.round(Fe*.6);B.style.width=we,B.style.height=we,B.style.minWidth=we,B.style.minHeight=we,B.style.fontSize="18px",B.style.lineHeight="1",B.style.backgroundColor="transparent",B.style.color="var(--cw-primary, #111827)",B.style.border="none",B.style.borderRadius="6px",B.style.transition="background-color 0.15s ease",B.addEventListener("mouseenter",()=>{B.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),B.addEventListener("mouseleave",()=>{B.style.backgroundColor="transparent"});let et=oe(te,vt,"currentColor",1.5);et?B.appendChild(et):B.textContent="\u{1F4CE}",B.addEventListener("click",Ot=>{Ot.preventDefault(),He==null||He.click()}),V.appendChild(B);let Bt=(H=j.buttonTooltipText)!=null?H:"Attach file",It=g("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!==B&&te.target!==V&&s.focus()}),X&&(X.style.gap="8px",r.append(X)),He&&r.append(He),r.append(s);let D=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),nt=g("div","tvw-flex tvw-items-center tvw-gap-2");V&&nt.append(V);let lt=g("div","tvw-flex tvw-items-center tvw-gap-1");z&&lt.append(z),lt.append(N),D.append(nt,lt),r.append(D);let dt=g("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 dt.style.display=Ft?"":"none",dt.textContent=(At=Lt.idleText)!=null?At:"Online",o.append(t,r,dt),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:N,micButton:J,micButtonWrapper:z,statusText:dt,attachmentButton:B,attachmentButtonWrapper:V,attachmentInput:He,attachmentPreviewsContainer:X,actionsRow:D,leftActions:nt,rightActions:lt}};var ei=e=>{var d,u,f,p,m,w,h;if(!((u=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?u:!0)){let F=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),T=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(p=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?p:"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&&Wt[o.position]?Wt[o.position]:Wt["bottom-right"],r=g("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=g("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}},ti=(e,n=!0)=>{var w,h,F,T,y,S,R;let o=g("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?rn(e,t,{showClose:n}):qt({config:e,showClose:n}),i=g("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=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=g("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=g("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=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let p=an({config:e}),m=((R=e==null?void 0:e.layout)==null?void 0:R.showFooter)!==!1;return r?Zt(o,s,e):(s.header.style.display="none",Zt(o,s,e)),o.append(i),m||(p.footer.style.display="none"),o.append(p.footer),{container:o,body:i,messagesWrapper:f,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.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:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.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},Yi=(e,n)=>{let o=g("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=g("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},ni=(e,n)=>{let o=g("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},Ki=(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},bs=(e,n,o)=>{var h,F,T,y,S,R;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=(R=n.layout)!=null?R:"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],p=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=null,w=(v,N,C,W)=>{let K=document.createElement("button");K.className="tvw-message-action-btn",K.setAttribute("aria-label",N),K.setAttribute("title",N),W&&K.setAttribute("data-action",W);let J=oe(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=oe("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let W=oe("copy",14,"currentColor",2);W&&(v.innerHTML="",v.appendChild(W))},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");p.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=p.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),m="upvote",v.classList.add("tvw-message-action-active");let W={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(W),n.onFeedback&&n.onFeedback(W)}},"upvote");p.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=p.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),m="downvote",v.classList.add("tvw-message-action-active");let W={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(W),n.onFeedback&&n.onFeedback(W)}},"downvote");p.appendChild(v)}return p},ln=(e,n,o,t,r)=>{var R,v,N,C,W;let s=o!=null?o:{},i=(R=s.layout)!=null?R:"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,p=(C=a==null?void 0:a.position)!=null?C:"left",m=(W=d==null?void 0:d.position)!=null?W:"below",w=Ki(e.role,i),h=g("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=ni(e,d);K.classList.add("tvw-ml-2","tvw-inline"),F.appendChild(K)}if(h.appendChild(F),f&&m==="below"&&e.createdAt){let K=ni(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=bs(e,t,r);h.appendChild(K)}if(!u||e.role==="system")return h;let y=g("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),S=Yi(a,e.role);return p==="right"||p==="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},si=(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}):ln(e,n,o,t,r)};var dn=new Set,oi=(e,n)=>{let o=dn.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=oe(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},Cs=e=>{let n=e.reasoning,o=g("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=dn.has(e.id),r=g("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=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Ir(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),f=oe(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let p=g("div","tvw-flex tvw-items-center tvw-ml-auto");p.append(d),r.append(s,p);let m=g("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=g("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=oe(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 cn=new Set,ri=(e,n,o)=>{var u;let t=cn.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",p=oe(t?"chevron-up":"chevron-down",16,f,2);p?d.appendChild(p):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},xs=(e,n)=>{var F;let o=e.toolCall,t=(F=n==null?void 0:n.toolCall)!=null?F:{},r=g("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=cn.has(e.id),i=g("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=g("div","tvw-flex tvw-flex-col tvw-text-left"),d=g("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Rr(o),a.appendChild(d);let u=g("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",p=oe(s?"chevron-up":"chevron-down",16,f,2);p?u.appendChild(p):u.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(a,m);let w=g("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=g("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=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let S=g("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=ms(o.args),T.append(y,S),w.appendChild(T)}if(o.chunks&&o.chunks.length){let T=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let S=g("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=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let S=g("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=ms(o.result),T.append(y,S),w.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=g("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=oe(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 ii=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(),p=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=g("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=p,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 ai={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"}},Ss=(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=ai[i])!=null?F:ai.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=g("div","tvw-space-y-1"),u=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=a.title,d.appendChild(u),a.description){let y=g("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,W;let S=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${n.id}-${i}-${y.name}`;let R=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");R.textContent=y.label,S.appendChild(R);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=(W=y.placeholder)!=null?W:"",y.required&&(N.required=!0),S.appendChild(N),f.appendChild(S)});let p=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("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",p.appendChild(m),p.appendChild(w),f.appendChild(p),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var N,C;y.preventDefault();let S=(N=o.formEndpoint)!=null?N:"/form",R=new FormData(f),v={};R.forEach((W,K)=>{v[K]=W}),v.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let W=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let K=await W.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(W){m.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var As=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()}},Ln=new As;var Ts={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"},Ms={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:Ts,darkTheme:Ms,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 Qn(e){var n,o,t,r,s,i,a,d,u,f,p,m,w,h,F,T,y,S,R;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,...(p=(f=e.layout)==null?void 0:f.messages)==null?void 0:p.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,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var li=()=>{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 Vi=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Xi=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},Pn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Vi(e),o=Xi(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}},Es=e=>typeof e=="string"?e:e==null?"":String(e),en={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Es(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Es(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:Es(o.text)}}},di=e=>Array.isArray(e)?e.map(n=>String(n)):[],Hn=e=>{let n=new Set(di(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(di(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=()=>{e.emit("action:resubmit",d)},p=u(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:f});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1,w=p.displayText!==void 0?p.displayText:"";return p.resubmit&&e.emit("action:resubmit",d),{text:w,persist:m,resubmit:p.resubmit}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var Gi=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}},Qi=e=>e.map(n=>({...n,streaming:!1})),Zn=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?Gi(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?Qi(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 ks=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)})}},un=new ks;var pn=require("partial-json");function Zi(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function ea(e,n){if(!Zi(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 es(){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,pn.parse)(o,pn.STR|pn.OBJ),s=ea(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function ci(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ts(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=un.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 ui(){let e=es();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ns(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 ss(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 ta=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function os(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=ta}=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 p=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 W=document.createElement("button");W.type="button",W.className="tvw-feedback-rating-btn tvw-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),W.title=u[C-1],W.dataset.rating=String(C),W.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),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 R=document.createElement("div");R.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)}}),R.appendChild(v),R.appendChild(N),m.appendChild(R),f.appendChild(m),f}function rs(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 R=document.createElement("span");R.className="tvw-feedback-label-low",R.textContent=u;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,S.appendChild(R),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,B)=>{Y.classList.toggle("selected",B===_),Y.setAttribute("aria-checked",B===_?"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",na=30*1e3,ks=e=>!e||typeof e!="object"?{}:{...e},pi=e=>e.map(n=>({...n,streaming:!1})),gi=(e,n)=>{let o=e!=null&&e.markdown?Tn(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):jn(r)}},is=(e,n,o)=>{var Rs,Fs,$s,Os,Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs,Gs;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=Qn(n),r=Ln.getForInstance(t.plugins);t.components&&cn.registerAll(t.components);let s=li(),i=(Rs=t.storageAdapter)!=null?Rs:Zn(),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=ks(c.metadata)),(Fs=c.messages)!=null&&Fs.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:[Pn],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick],w=Hn({parsers:g,handlers:m,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Os=($s=t.launcher)==null?void 0:$s.enabled)!=null?Os:!0,F=(js=(Ns=t.launcher)==null?void 0:Ns.autoExpand)!=null?js:!1,T=F,y=h,S=(_s=(Ds=t.layout)==null?void 0:Ds.header)==null?void 0:_s.layout,R=h?F:!0,v=gi(t,w),N=(Us=(qs=t.features)==null?void 0:qs.showReasoning)!=null?Us:!0,C=(Js=(zs=t.features)==null?void 0:zs.showToolCalls)!=null?Js:!0,k={onCopy:l=>{var c,A;s.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.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),H!=null&&H.isClientTokenMode()&&H.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=(Ys=t.statusIndicator)!=null?Ys:{},J=l=>{var c,A,P,b;return l==="idle"?(c=K.idleText)!=null?c:mt.idle:l==="connecting"?(A=K.connectingText)!=null?A:mt.connecting:l==="connected"?(P=K.connectedText)!=null?P:mt.connected:l==="error"?(b=K.errorText)!=null?b:mt.error:mt[l]},{wrapper:z,panel:_}=ei(t),j=ti(t,h),{container:Y,body:B,messagesWrapper:V,suggestions:He,textarea:X,sendButton:D,sendButtonWrapper:nt,composerForm:lt,statusText:dt,introTitle:Lt,introSubtitle:Ft,closeButton:q,iconHolder:fe,headerTitle:ct,headerSubtitle:ut,header:Je,footer:pt,actionsRow:$t,leftActions:Pt,rightActions:Ht}=j,$=j.micButton,je=j.micButtonWrapper,pe=j.attachmentButton,st=j.attachmentButtonWrapper,ge=j.attachmentInput,ot=j.attachmentPreviewsContainer,Ae=null;(Ks=t.attachments)!=null&&Ks.enabled&&ge&&ot&&(Ae=Qt.fromConfig(t.attachments),Ae.setPreviewsContainer(ot),ge.addEventListener("change",l=>{let c=l.target;Ae==null||Ae.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),Je=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=>{H&&!H.isStreaming()&&H.sendMessage(c)},disabled:!1});l&&(pt.replaceWith(l),pt=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 He;case"composer":return lt;case"footer-bottom":return dt;default:return null}},A=(Q,de)=>{var M;switch(Q){case"header-left":case"header-center":case"header-right":if(Q==="header-left")Je.insertBefore(de,Je.firstChild);else if(Q==="header-right")Je.appendChild(de);else{let G=Je.querySelector(".tvw-flex-col");G?(M=G.parentNode)==null||M.insertBefore(de,G.nextSibling):Je.appendChild(de)}break;case"body-top":{let G=B.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(de):B.insertBefore(de,B.firstChild);break}case"body-bottom":B.appendChild(de);break;case"footer-top":He.replaceWith(de);break;case"footer-bottom":dt.replaceWith(de);break;default:break}};for(let[Q,de]of Object.entries(l))if(de)try{let M=de({config:t,defaultContent:()=>c(Q)});M&&A(Q,M)}catch(M){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${Q}":`,M)}})();let Ye=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),oi(b,P)):Q==="tool"&&(dn.has(b)?dn.delete(b):dn.add(b),ri(b,P,t))};V.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ye(l))}),V.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ye(l))}),_.appendChild(Y),e.appendChild(z);let Ze=()=>{var ce,qe,Ue,it,Tt,ee,Ee,Kt,Vt,Rn,Fn,ps,ze,$n,wn,yn;let l=(qe=(ce=t.launcher)==null?void 0:ce.sidebarMode)!=null?qe:!1,c=l||((it=(Ue=t.launcher)==null?void 0:Ue.fullHeight)!=null?it:!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)",de=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:de,ye=(Rn=A.panelBorderRadius)!=null?Rn:M;e.style.cssText="",z.style.cssText="",_.style.cssText="",Y.style.cssText="",B.style.cssText="",pt.style.cssText="";let O=(ps=(Fn=t==null?void 0:t.launcher)==null?void 0:Fn.width)!=null?ps:t==null?void 0:t.launcherWidth,$e=O!=null?O:"min(400px, calc(100vw - 24px))";l||(_.style.width=$e,_.style.maxWidth=$e),_.style.boxShadow=Z,_.style.borderRadius=ye,Y.style.border=G,Y.style.borderRadius=ye;let Se=((ze=t.launcher)==null?void 0:ze.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%",Se&&(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",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.overflowY="auto",pt.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&&!Se&&(($n=kt[P])!=null?$n:kt["bottom-right"]).split(" ").forEach(vn=>z.classList.add(vn)),l){let zt=(yn=(wn=t.launcher)==null?void 0:wn.sidebarWidth)!=null?yn:"420px";z.style.cssText=`
20
+ `,W.addEventListener("click",()=>{p=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(W),T.appendChild(W)}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 R=document.createElement("div");R.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(p===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(p,C),f.remove()}catch(C){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),R.appendChild(v),R.appendChild(N),m.appendChild(R),f.appendChild(m),f}function rs(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,p=document.createElement("div");p.className="tvw-feedback-container tvw-feedback-nps",p.setAttribute("role","dialog"),p.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 R=document.createElement("span");R.className="tvw-feedback-label-low",R.textContent=u;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,S.appendChild(R),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,B)=>{Y.classList.toggle("selected",B===_),Y.setAttribute("aria-checked",B===_?"true":"false")})}),C.push(j),N.appendChild(j)}y.appendChild(S),y.appendChild(N),w.appendChild(y);let W=null;if(d){let _=document.createElement("div");_.className="tvw-feedback-comment-container",W=document.createElement("textarea"),W.className="tvw-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),_.appendChild(W),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(),p.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 _=(W==null?void 0:W.value.trim())||void 0;await n(m,_),p.remove()}catch(_){z.disabled=!1,z.textContent=i,console.error("[NPS Feedback] Failed to submit:",_)}}),K.appendChild(J),K.appendChild(z),w.appendChild(K),p.appendChild(w),p}var gn="persona-chat-history",na=30*1e3,Ws=e=>!e||typeof e!="object"?{}:{...e},pi=e=>e.map(n=>({...n,streaming:!1})),gi=(e,n)=>{let o=e!=null&&e.markdown?Mn(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):jn(r)}},is=(e,n,o)=>{var Rs,Fs,$s,Os,Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs,Gs;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=Qn(n),r=Ln.getForInstance(t.plugins);t.components&&un.registerAll(t.components);let s=li(),i=(Rs=t.storageAdapter)!=null?Rs:Zn(),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)),(Fs=c.messages)!=null&&Fs.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:{},fn()},p=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Pn],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick],w=Hn({parsers:p,handlers:m,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Os=($s=t.launcher)==null?void 0:$s.enabled)!=null?Os:!0,F=(js=(Ns=t.launcher)==null?void 0:Ns.autoExpand)!=null?js:!1,T=F,y=h,S=(_s=(Ds=t.layout)==null?void 0:Ds.header)==null?void 0:_s.layout,R=h?F:!0,v=gi(t,w),N=(Us=(qs=t.features)==null?void 0:qs.showReasoning)!=null?Us:!0,C=(Js=(zs=t.features)==null?void 0:zs.showToolCalls)!=null?Js:!0,W={onCopy:l=>{var c,A;s.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.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),H!=null&&H.isClientTokenMode()&&H.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=(Ys=t.statusIndicator)!=null?Ys:{},J=l=>{var c,A,P,b;return l==="idle"?(c=K.idleText)!=null?c:mt.idle:l==="connecting"?(A=K.connectingText)!=null?A:mt.connecting:l==="connected"?(P=K.connectedText)!=null?P:mt.connected:l==="error"?(b=K.errorText)!=null?b:mt.error:mt[l]},{wrapper:z,panel:_}=ei(t),j=ti(t,h),{container:Y,body:B,messagesWrapper:V,suggestions:He,textarea:X,sendButton:D,sendButtonWrapper:nt,composerForm:lt,statusText:dt,introTitle:Lt,introSubtitle:Ft,closeButton:q,iconHolder:fe,headerTitle:ct,headerSubtitle:ut,header:Je,footer:pt,actionsRow:$t,leftActions:Pt,rightActions:Ht}=j,$=j.micButton,je=j.micButtonWrapper,pe=j.attachmentButton,st=j.attachmentButtonWrapper,ge=j.attachmentInput,ot=j.attachmentPreviewsContainer,Ae=null;(Ks=t.attachments)!=null&&Ks.enabled&&ge&&ot&&(Ae=Qt.fromConfig(t.attachments),Ae.setPreviewsContainer(ot),ge.addEventListener("change",l=>{let c=l.target;Ae==null||Ae.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),Je=l)}}let St=r.find(l=>l.renderComposer);if(St!=null&&St.renderComposer){let l=St.renderComposer({config:t,defaultRenderer:()=>an({config:t}).footer,onSubmit:c=>{H&&!H.isStreaming()&&H.sendMessage(c)},disabled:!1});l&&(pt.replaceWith(l),pt=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 He;case"composer":return lt;case"footer-bottom":return dt;default:return null}},A=(Q,de)=>{var M;switch(Q){case"header-left":case"header-center":case"header-right":if(Q==="header-left")Je.insertBefore(de,Je.firstChild);else if(Q==="header-right")Je.appendChild(de);else{let G=Je.querySelector(".tvw-flex-col");G?(M=G.parentNode)==null||M.insertBefore(de,G.nextSibling):Je.appendChild(de)}break;case"body-top":{let G=B.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(de):B.insertBefore(de,B.firstChild);break}case"body-bottom":B.appendChild(de);break;case"footer-top":He.replaceWith(de);break;case"footer-bottom":dt.replaceWith(de);break;default:break}};for(let[Q,de]of Object.entries(l))if(de)try{let M=de({config:t,defaultContent:()=>c(Q)});M&&A(Q,M)}catch(M){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${Q}":`,M)}})();let Ye=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"?(dn.has(b)?dn.delete(b):dn.add(b),oi(b,P)):Q==="tool"&&(cn.has(b)?cn.delete(b):cn.add(b),ri(b,P,t))};V.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ye(l))}),V.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ye(l))}),_.appendChild(Y),e.appendChild(z);let Ze=()=>{var ce,qe,Ue,it,Tt,ee,Ee,Kt,Vt,Rn,Fn,ps,ze,$n,yn,vn;let l=(qe=(ce=t.launcher)==null?void 0:ce.sidebarMode)!=null?qe:!1,c=l||((it=(Ue=t.launcher)==null?void 0:Ue.fullHeight)!=null?it:!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)",de=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:de,ye=(Rn=A.panelBorderRadius)!=null?Rn:M;e.style.cssText="",z.style.cssText="",_.style.cssText="",Y.style.cssText="",B.style.cssText="",pt.style.cssText="";let O=(ps=(Fn=t==null?void 0:t.launcher)==null?void 0:Fn.width)!=null?ps:t==null?void 0:t.launcherWidth,$e=O!=null?O:"min(400px, calc(100vw - 24px))";l||(_.style.width=$e,_.style.maxWidth=$e),_.style.boxShadow=Z,_.style.borderRadius=ye,Y.style.border=G,Y.style.borderRadius=ye;let Se=((ze=t.launcher)==null?void 0:ze.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%",Se&&(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",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.overflowY="auto",pt.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&&!Se&&(($n=Wt[P])!=null?$n:Wt["bottom-right"]).split(" ").forEach(bn=>z.classList.add(bn)),l){let zt=(vn=(yn=t.launcher)==null?void 0:yn.sidebarWidth)!=null?vn:"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(!Se){let zt="max-height: -moz-available !important; max-height: stretch !important;",vn=l?"":"padding-top: 1.25em !important;";z.style.cssText+=zt+vn}};Ze(),Xn(e,t);let ke=[],Ke=null,Wt=()=>{Ke&&(Ke(),Ke=null),t.colorScheme==="auto"&&(Ke=Gr(()=>{Xn(e,t)}))};Wt(),ke.push(()=>{Ke&&(Ke(),Ke=null)});let ft=ii(He),rt=null,H,wt=!1,yt=!0,At=0,te=0,we=null,Fe=!1,vt=0,et=!1,Bt=125,It=2e3,Ot=5,nn=50,Nt=new Map,Le={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},gn=(Xs=(Vs=t.voiceRecognition)==null?void 0:Vs.autoResume)!=null?Xs:!1,mn=l=>{s.emit("voice:state",{active:Le.active,source:l,timestamp:Date.now()})},jt=()=>{f(l=>({...l,voiceState:{active:Le.active,timestamp:Date.now(),manuallyDeactivated:Le.manuallyDeactivated}}))},Bn=()=>{var P,b;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let l=ks(a.voiceState),c=!!l.active,A=Number((b=l.timestamp)!=null?b:0);Le.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-A<na&&setTimeout(()=>{Le.active||(Le.manuallyDeactivated=!1,_e("restore"))},1e3)},In=()=>H?pi(H.getMessages()).filter(l=>!l.__skipPersist):[];function hn(l){if(!(i!=null&&i.save))return;let A={messages:l?pi(l):H?In():[],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();Fe&&c<vt&&!l||(Fe&&c>=vt&&(Fe=!1),!(!l&&!wt)&&(c-te<Bt||(te=c,we&&cancelAnimationFrame(we),we=requestAnimationFrame(()=>{Fe||!yt||(et=!0,B.scrollTop=B.scrollHeight,At=B.scrollTop,requestAnimationFrame(()=>{et=!1}),we=null)}))))},L=null,ae=()=>z.querySelector("#persona-scroll-container")||B,xe=(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=ye=>1-Math.pow(1-ye,3),Z=ye=>{let O=l.scrollHeight;O!==b&&(b=O,Q=b-A);let $e=ye-M,Se=Math.min($e/c,1),ce=G(Se),qe=A+Q*ce;l.scrollTop=qe,Se<1?L=requestAnimationFrame(Z):(l.scrollTop=l.scrollHeight,L=null)};L=requestAnimationFrame(Z)},De=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)})},Ve=(l,c,A)=>{let P=document.createElement("div");c.forEach(M=>{var $e,Se;let G=null,Z=r.find(ce=>!!(M.variant==="reasoning"&&ce.renderReasoning||M.variant==="tool"&&ce.renderToolCall||!M.variant&&ce.renderMessage)),ye=($e=t.layout)==null?void 0:$e.messages;if(Z)if(M.variant==="reasoning"&&M.reasoning&&Z.renderReasoning){if(!N)return;G=Z.renderReasoning({message:M,defaultRenderer:()=>Cs(M),config:t})}else if(M.variant==="tool"&&M.toolCall&&Z.renderToolCall){if(!C)return;G=Z.renderToolCall({message:M,defaultRenderer:()=>xs(M,t),config:t})}else Z.renderMessage&&(G=Z.renderMessage({message:M,defaultRenderer:()=>{let ce=an(M,A,ye,t.messageActions,k);return M.role!=="user"&&Ss(ce,M,t,H),ce},config:t}));if(!G&&M.role==="assistant"&&!M.variant&&t.enableComponentStreaming!==!1&&ns(M)){let qe=ss(M);if(qe){let Ue=ts(qe,{config:t,message:M,transform:A});if(Ue){let it=document.createElement("div");if(it.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(" "),it.id=`bubble-${M.id}`,it.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}),it.appendChild(Tt)}it.appendChild(Ue),G=it}}}if(!G)if(M.variant==="reasoning"&&M.reasoning){if(!N)return;G=Cs(M)}else if(M.variant==="tool"&&M.toolCall){if(!C)return;G=xs(M,t)}else{let ce=(Se=t.layout)==null?void 0:Se.messages;ce!=null&&ce.renderUserMessage&&M.role==="user"?G=ce.renderUserMessage({message:M,config:t,streaming:!!M.streaming}):ce!=null&&ce.renderAssistantMessage&&M.role==="assistant"?G=ce.renderAssistantMessage({message:M,config:t,streaming:!!M.streaming}):G=an(M,A,ce,t.messageActions,k),M.role!=="user"&&G&&Ss(G,M,t,H)}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],de=(Q==null?void 0:Q.role)==="assistant"&&!Q.streaming;if(wt&&c.some(M=>M.role==="user")&&!b&&!de){let M=kn(),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)}Zr(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let M=ae();xe(M)})})},Pe=()=>{h&&(R?(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"),le?le.element.style.display="none":he&&(he.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"),le?le.element.style.display="":he&&(he.style.display="")))},E=(l,c="user")=>{if(!h||R===l)return;let A=R;R=l,Pe(),R&&(fn(),Yt(!0));let P={open:R,source:c,timestamp:Date.now()};R&&!A?s.emit("widget:opened",P):!R&&A&&s.emit("widget:closed",P),s.emit("widget:state",{open:R,launcherEnabled:h,voiceActive:Le.active,streaming:H.isStreaming()})},bt=l=>{D.disabled=l,$&&($.disabled=l),ft.buttons.forEach(c=>{c.disabled=l})},se=()=>{var b,Q,de,M,G,Z,ye,O,$e,Se,ce,qe,Ue,it;Lt.textContent=(Q=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?Q:"Hello \u{1F44B}",Ft.textContent=(M=(de=t.copy)==null?void 0:de.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=(ye=t.sendButton)==null?void 0:ye.useIcon)!=null?O:!1)||(D.textContent=(Se=($e=t.copy)==null?void 0:$e.sendButtonLabel)!=null?Se:"Send");let c=(qe=(ce=t.theme)==null?void 0:ce.inputFontFamily)!=null?qe:"sans-serif",A=(it=(Ue=t.theme)==null?void 0:Ue.inputFontWeight)!=null?it:"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}))}}),H=new sn(t,{onMessagesChanged(l){Ve(V,l,v),H&&(l.some(P=>P.role==="user")?ft.render([],H,X,l):ft.render(t.suggestionChips,H,X,l,t.suggestionChipsConfig)),Yt(!wt),De(l);let c=[...l].reverse().find(A=>A.role==="user");Le.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),hn(l)},onStatusChanged(l){var P;let c=(P=t.statusIndicator)!=null?P:{},A=b=>{var Q,de,M,G;return b==="idle"?(Q=c.idleText)!=null?Q:mt.idle:b==="connecting"?(de=c.connectingText)!=null?de:mt.connecting:b==="connected"?(M=c.connectedText)!=null?M:mt.connected:b==="error"?(G=c.errorText)!=null?G:mt.error:mt[b]};dt.textContent=A(l)},onStreamingChanged(l){wt=l,bt(l),H&&Ve(V,H.getMessages(),v),l||Yt(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=ks(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let I=l=>{var b;l.preventDefault();let c=X.value.trim(),A=(b=Ae==null?void 0:Ae.hasAttachments())!=null?b:!1;if(!c&&!A)return;let P;A&&(P=[],P.push(...Ae.getContentParts()),c&&P.push(Yn(c))),X.value="",X.style.height="auto",H.sendMessage(c,{contentParts:P}),A&&Ae.clearAttachments()},W=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),D.click())},U=null,me=!1,Te=null,Xe=null,Ie=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,_e=(l="user")=>{var Q,de,M,G;if(me||H.isStreaming())return;let c=Ie();if(!c)return;U=new c;let P=(de=((Q=t.voiceRecognition)!=null?Q:{}).pauseDuration)!=null?de:2e3;U.continuous=!0,U.interimResults=!0,U.lang="en-US";let b=X.value;U.onresult=Z=>{let ye="",O="";for(let Se=0;Se<Z.results.length;Se++){let ce=Z.results[Se],qe=ce[0].transcript;ce.isFinal?ye+=qe+" ":O=qe}let $e=b+ye+O;X.value=$e,Te&&clearTimeout(Te),(ye||O)&&(Te=window.setTimeout(()=>{let Se=X.value.trim();Se&&U&&me&&(We(),X.value="",X.style.height="auto",H.sendMessage(Se,{viaVoice:!0}))},P))},U.onerror=Z=>{Z.error!=="no-speech"&&We()},U.onend=()=>{if(me){let Z=X.value.trim();Z&&Z!==b.trim()&&(X.value="",X.style.height="auto",H.sendMessage(Z,{viaVoice:!0})),We()}};try{if(U.start(),me=!0,Le.active=!0,l!=="system"&&(Le.manuallyDeactivated=!1),mn(l),jt(),$){Xe={backgroundColor:$.style.backgroundColor,color:$.style.color,borderColor:$.style.borderColor};let Z=(M=t.voiceRecognition)!=null?M:{},ye=(G=Z.recordingBackgroundColor)!=null?G:"#ef4444",O=Z.recordingIconColor,$e=Z.recordingBorderColor;if($.classList.add("tvw-voice-recording"),$.style.backgroundColor=ye,O){$.style.color=O;let Se=$.querySelector("svg");Se&&Se.setAttribute("stroke",O)}$e&&($.style.borderColor=$e),$.setAttribute("aria-label","Stop voice recognition")}}catch{We("system")}},We=(l="user")=>{if(me){if(me=!1,Te&&(clearTimeout(Te),Te=null),U){try{U.stop()}catch{}U=null}if(Le.active=!1,mn(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")}}},be=(l,c)=>{var qe,Ue,it,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=(qe=l==null?void 0:l.iconName)!=null?qe:"mic",de=(Ue=c==null?void 0:c.size)!=null?Ue:"40px",M=(it=l==null?void 0:l.iconSize)!=null?it:de,G=parseFloat(M)||24,Z=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,ye=(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=ye||"currentColor",$e=oe(Q,G,O,1.5);$e?(b.appendChild($e),b.style.color=O):(b.textContent="\u{1F3A4}",b.style.color=O),Z?b.style.backgroundColor=Z:b.classList.add("tvw-bg-cw-primary"),ye?b.style.color=ye:!ye&&!(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 Se=(Ee=l==null?void 0:l.tooltipText)!=null?Ee:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&Se){let Vt=p("div","tvw-send-button-tooltip");Vt.textContent=Se,P.appendChild(Vt)}return{micButton:b,micButtonWrapper:P}},Ce=()=>{if(me){let l=X.value.trim();Le.manuallyDeactivated=!0,jt(),We("user"),l&&(X.value="",X.style.height="auto",H.sendMessage(l))}else Le.manuallyDeactivated=!1,jt(),_e("user")};$&&($.addEventListener("click",Ce),ke.push(()=>{We("system"),$&&$.removeEventListener("click",Ce)}));let Ge=s.on("assistant:complete",()=>{gn&&(Le.active||Le.manuallyDeactivated||gn==="assistant"&&!Le.lastUserMessageWasVoice||setTimeout(()=>{!Le.active&&!Le.manuallyDeactivated&&_e("auto")},600))});ke.push(Ge);let Me=s.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.sendMessage("[continue]")},500)});ke.push(Me);let Re=()=>{E(!R,"user")},le=null,he=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>Wn(t,Re).element,onToggle:Re});c&&(he=c)}he||(le=Wn(t,Re))}le?e.appendChild(le.element):he&&e.appendChild(he),Pe(),ft.render(t.suggestionChips,H,X,void 0,t.suggestionChipsConfig),se(),bt(H.isStreaming()),Yt(!0),Bn();let fn=()=>{var A,P,b,Q,de,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 ye=(M=(de=t==null?void 0:t.launcher)==null?void 0:de.width)!=null?M:t==null?void 0:t.launcherWidth,O=ye!=null?ye:"min(400px, calc(100vw - 24px))";_.style.width=O,_.style.maxWidth=O}if(!c){let ye=window.innerHeight,O=64,$e=(Z=(G=t.launcher)==null?void 0:G.heightOffset)!=null?Z:0,Se=Math.max(200,ye-O),ce=Math.min(640,Se),qe=Math.max(200,ce-$e);_.style.height=`${qe}px`}};fn(),window.addEventListener("resize",fn),ke.push(()=>window.removeEventListener("resize",fn)),At=B.scrollTop;let Bs=()=>{let l=B.scrollTop,c=B.scrollHeight,A=B.clientHeight,P=c-l-A,b=Math.abs(l-At);if(At=l,!et&&!(b<=Ot)){if(!yt&&P<nn){Fe=!1,yt=!0;return}yt&&P>nn&&(Fe=!0,vt=Date.now()+It,yt=!1)}};B.addEventListener("scroll",Bs,{passive:!0}),ke.push(()=>B.removeEventListener("scroll",Bs)),ke.push(()=>{we&&cancelAnimationFrame(we)});let Is=()=>{q&&(rt&&(q.removeEventListener("click",rt),rt=null),h?(q.style.display="",rt=()=>{R=!1,Pe()},q.addEventListener("click",rt)):q.style.display="none")};Is(),(()=>{let{clearChatButton:l}=j;l&&l.addEventListener("click",()=>{H.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()})})(),lt.addEventListener("submit",I),X.addEventListener("keydown",W),ke.push(()=>{lt.removeEventListener("submit",I),X.removeEventListener("keydown",W)}),ke.push(()=>{H.cancel()}),le?ke.push(()=>{le==null||le.destroy()}):he&&ke.push(()=>{he==null||he.remove()});let Dt={update(l){var 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,Mr;let c=t.toolCall,A=t.colorScheme;t={...t,...l},Ze(),Xn(e,t),t.colorScheme!==A&&Wt();let P=Ln.getForInstance(t.plugins);if(r.length=0,r.push(...P),h=(Zs=(Qs=t.launcher)==null?void 0:Qs.enabled)!=null?Zs:!0,F=(to=(eo=t.launcher)==null?void 0:eo.autoExpand)!=null?to:!1,N=(so=(no=t.features)==null?void 0:no.showReasoning)!=null?so:!0,C=(ro=(oo=t.features)==null?void 0:oo.showToolCalls)!=null?ro:!0,((io=t.launcher)==null?void 0:io.enabled)===!1&&le&&(le.destroy(),le=null),((ao=t.launcher)==null?void 0:ao.enabled)===!1&&he&&(he.remove(),he=null),((lo=t.launcher)==null?void 0:lo.enabled)!==!1&&!le&&!he){let x=r.find(ue=>ue.renderLauncher);if(x!=null&&x.renderLauncher){let ue=x.renderLauncher({config:t,defaultRenderer:()=>Wn(t,Re).element,onToggle:Re});ue&&(he=ue,e.appendChild(he))}he||(le=Wn(t,Re),e.appendChild(le.element))}le&&le.update(t),ct&&((co=t.launcher)==null?void 0:co.title)!==void 0&&(ct.textContent=t.launcher.title),ut&&((uo=t.launcher)==null?void 0:uo.subtitle)!==void 0&&(ut.textContent=t.launcher.subtitle);let b=(po=t.layout)==null?void 0:po.header;if((b==null?void 0:b.layout)!==S&&Je){let x=b?on(t,b,{showClose:h,onClose:()=>E(!1,"user")}):qt({config:t,showClose:h,onClose:()=>E(!1,"user")});Je.replaceWith(x.header),Je=x.header,fe=x.iconHolder,ct=x.headerTitle,ut=x.headerSubtitle,q=x.closeButton,S=b==null?void 0:b.layout}else if(b&&(fe&&(fe.style.display=b.showIcon===!1?"none":""),ct&&(ct.style.display=b.showTitle===!1?"none":""),ut&&(ut.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:ue}=j;ue&&!ue.classList.contains("tvw-absolute")&&(x?ue.classList.remove("tvw-ml-auto"):ue.classList.add("tvw-ml-auto"))}}let de=((go=t.layout)==null?void 0:go.showHeader)!==!1;Je&&(Je.style.display=de?"":"none");let M=((mo=t.layout)==null?void 0:mo.showFooter)!==!1;pt&&(pt.style.display=M?"":"none"),h!==y?h?E(F,"auto"):(R=!0,Pe()):F!==T&&E(F,"auto"),T=F,y=h,fn(),Is(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&H&&Ve(V,H.getMessages(),v);let O=(ho=t.launcher)!=null?ho:{},$e=(fo=O.headerIconHidden)!=null?fo:!1,Se=(yo=(wo=t.layout)==null?void 0:wo.header)==null?void 0:yo.showIcon,ce=$e||Se===!1,qe=O.headerIconName,Ue=(vo=O.headerIconSize)!=null?vo:"48px";if(fe){let x=Y.querySelector(".tvw-border-b-cw-divider"),ue=x==null?void 0:x.querySelector(".tvw-flex-col");if(ce)fe.style.display="none",x&&ue&&!x.contains(ue)&&x.insertBefore(ue,x.firstChild);else{if(fe.style.display="",fe.style.height=Ue,fe.style.width=Ue,x&&ue&&(x.contains(fe)?fe.nextSibling!==ue&&(fe.remove(),x.insertBefore(fe,ue)):x.insertBefore(fe,ue)),qe){let ne=parseFloat(Ue)||24,ve=oe(qe,ne*.6,"#ffffff",2);ve?fe.replaceChildren(ve):fe.textContent=(bo=O.agentIconText)!=null?bo:"\u{1F4AC}"}else if(O.iconUrl){let ne=fe.querySelector("img");if(ne)ne.src=O.iconUrl,ne.style.height=Ue,ne.style.width=Ue;else{let ve=document.createElement("img");ve.src=O.iconUrl,ve.alt="",ve.className="tvw-rounded-xl tvw-object-cover",ve.style.height=Ue,ve.style.width=Ue,fe.replaceChildren(ve)}}else{let ne=fe.querySelector("svg"),ve=fe.querySelector("img");(ne||ve)&&fe.replaceChildren(),fe.textContent=(Co=O.agentIconText)!=null?Co:"\u{1F4AC}"}let Oe=fe.querySelector("img");Oe&&(Oe.style.height=Ue,Oe.style.width=Ue)}}let it=(So=(xo=t.layout)==null?void 0:xo.header)==null?void 0:So.showTitle,Tt=(To=(Ao=t.layout)==null?void 0:Ao.header)==null?void 0:To.showSubtitle;if(ct&&(ct.style.display=it===!1?"none":""),ut&&(ut.style.display=Tt===!1?"none":""),q){((Eo=(Mo=t.layout)==null?void 0:Mo.header)==null?void 0:Eo.showCloseButton)===!1?q.style.display="none":q.style.display="";let ue=(Wo=O.closeButtonSize)!=null?Wo:"32px",Oe=(ko=O.closeButtonPlacement)!=null?ko:"inline";q.style.height=ue,q.style.width=ue;let{closeButtonWrapper:ne}=j,ve=Oe==="top-right",gt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&ve!==gt)if(ne.remove(),ve)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(ne);else{let re=(Po=(Lo=O.clearChat)==null?void 0:Lo.placement)!=null?Po:"inline",Qe=(Bo=(Ho=O.clearChat)==null?void 0:Ho.enabled)!=null?Bo:!0;ne.className=Qe&&re==="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 re=O.closeButtonBorderWidth||"0px",Qe=O.closeButtonBorderColor||"transparent";q.style.border=`${re} solid ${Qe}`,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 at=(Io=O.closeButtonIconName)!=null?Io:"x",Mt=(Ro=O.closeButtonIconText)!=null?Ro:"\xD7";q.innerHTML="";let ht=oe(at,"20px",O.closeButtonColor||"",2);ht?q.appendChild(ht):q.textContent=Mt;let Ne=(Fo=O.closeButtonTooltipText)!=null?Fo:"Close chat",Et=($o=O.closeButtonShowTooltip)!=null?$o:!0;if(q.setAttribute("aria-label",Ne),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),Et&&Ne)){let re=null,Qe=()=>{if(re||!q)return;re=p("div","tvw-clear-chat-tooltip"),re.textContent=Ne;let Sn=p("div");Sn.className="tvw-clear-chat-tooltip-arrow",re.appendChild(Sn);let Xt=q.getBoundingClientRect();re.style.position="fixed",re.style.left=`${Xt.left+Xt.width/2}px`,re.style.top=`${Xt.top-8}px`,re.style.transform="translate(-50%, -100%)",document.body.appendChild(re)},Ct=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};ne.addEventListener("mouseenter",Qe),ne.addEventListener("mouseleave",Ct),q.addEventListener("focus",Qe),q.addEventListener("blur",Ct),ne._cleanupTooltip=()=>{Ct(),ne&&(ne.removeEventListener("mouseenter",Qe),ne.removeEventListener("mouseleave",Ct)),q&&(q.removeEventListener("focus",Qe),q.removeEventListener("blur",Ct))}}}let{clearChatButton:ee,clearChatButtonWrapper:Ee}=j;if(ee){let x=(Oo=O.clearChat)!=null?Oo:{},ue=(No=x.enabled)!=null?No:!0,Oe=(Do=(jo=t.layout)==null?void 0:jo.header)==null?void 0:Do.showClearChat,ne=Oe!==void 0?Oe:ue,ve=(_o=x.placement)!=null?_o:"inline";if(Ee){Ee.style.display=ne?"":"none";let{closeButtonWrapper:gt}=j;gt&&!gt.classList.contains("tvw-absolute")&&(ne?gt.classList.remove("tvw-ml-auto"):gt.classList.add("tvw-ml-auto"));let at=ve==="top-right",Mt=Ee.classList.contains("tvw-absolute");if(at!==Mt&&ne){if(Ee.remove(),at)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 Ne=Y.querySelector(".tvw-border-b-cw-divider"),Et=j.closeButtonWrapper;Ne&&Et&&Et.parentElement===Ne?Ne.insertBefore(Ee,Et):Ne&&Ne.appendChild(Ee)}let ht=j.closeButtonWrapper;ht&&!ht.classList.contains("tvw-absolute")&&(at?ht.classList.add("tvw-ml-auto"):ht.classList.remove("tvw-ml-auto"))}}if(ne){let gt=(qo=x.size)!=null?qo:"32px";ee.style.height=gt,ee.style.width=gt;let at=(Uo=x.iconName)!=null?Uo:"refresh-cw",Mt=(zo=x.iconColor)!=null?zo:"";ee.innerHTML="";let ht=oe(at,"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 re=x.borderWidth||"0px",Qe=x.borderColor||"transparent";ee.style.border=`${re} solid ${Qe}`,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 Ne=(Jo=x.tooltipText)!=null?Jo:"Clear chat",Et=(Yo=x.showTooltip)!=null?Yo:!0;if(ee.setAttribute("aria-label",Ne),Ee&&(Ee._cleanupTooltip&&(Ee._cleanupTooltip(),delete Ee._cleanupTooltip),Et&&Ne)){let re=null,Qe=()=>{if(re||!ee)return;re=p("div","tvw-clear-chat-tooltip"),re.textContent=Ne;let Sn=p("div");Sn.className="tvw-clear-chat-tooltip-arrow",re.appendChild(Sn);let Xt=ee.getBoundingClientRect();re.style.position="fixed",re.style.left=`${Xt.left+Xt.width/2}px`,re.style.top=`${Xt.top-8}px`,re.style.transform="translate(-50%, -100%)",document.body.appendChild(re)},Ct=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};Ee.addEventListener("mouseenter",Qe),Ee.addEventListener("mouseleave",Ct),ee.addEventListener("focus",Qe),ee.addEventListener("blur",Ct),Ee._cleanupTooltip=()=>{Ct(),Ee&&(Ee.removeEventListener("mouseenter",Qe),Ee.removeEventListener("mouseleave",Ct)),ee&&(ee.removeEventListener("focus",Qe),ee.removeEventListener("blur",Ct))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Pn],Vt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick];w=Hn({parsers:Kt,handlers:Vt,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),v=gi(t,w),H.updateConfig(t),Ve(V,H.getMessages(),v),ft.render(t.suggestionChips,H,X,void 0,t.suggestionChipsConfig),se(),bt(H.isStreaming());let Rn=((Ko=t.voiceRecognition)==null?void 0:Ko.enabled)===!0,Fn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Rn&&Fn)if(!$||!je){let x=be(t.voiceRecognition,t.sendButton);x&&($=x.micButton,je=x.micButtonWrapper,Ht.insertBefore(je,nt),$.addEventListener("click",Ce),$.disabled=H.isStreaming())}else{let x=(Vo=t.voiceRecognition)!=null?Vo:{},ue=(Xo=t.sendButton)!=null?Xo:{},Oe=(Go=x.iconName)!=null?Go:"mic",ne=(Qo=ue.size)!=null?Qo:"40px",ve=(Zo=x.iconSize)!=null?Zo:ne,gt=parseFloat(ve)||24;$.style.width=ve,$.style.height=ve,$.style.minWidth=ve,$.style.minHeight=ve;let at=(tr=(er=x.iconColor)!=null?er:ue.textColor)!=null?tr:"currentColor";$.innerHTML="";let Mt=oe(Oe,gt,at,2);Mt?$.appendChild(Mt):$.textContent="\u{1F3A4}";let ht=(nr=x.backgroundColor)!=null?nr:ue.backgroundColor;ht?($.style.backgroundColor=ht,$.classList.remove("tvw-bg-cw-primary")):($.style.backgroundColor="",$.classList.add("tvw-bg-cw-primary")),at?($.style.color=at,$.classList.remove("tvw-text-white")):!at&&!ue.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 Ne=je==null?void 0:je.querySelector(".tvw-send-button-tooltip"),Et=(sr=x.tooltipText)!=null?sr:"Start voice recognition";if(((or=x.showTooltip)!=null?or:!1)&&Et)if(Ne)Ne.textContent=Et,Ne.style.display="";else{let Qe=document.createElement("div");Qe.className="tvw-send-button-tooltip",Qe.textContent=Et,je==null||je.insertBefore(Qe,$)}else Ne&&(Ne.style.display="none");je.style.display="",$.disabled=H.isStreaming()}else $&&je&&(je.style.display="none",me&&We());if(((rr=t.attachments)==null?void 0:rr.enabled)===!0)if(!st||!pe){let x=(ir=t.attachments)!=null?ir:{},Oe=(lr=((ar=t.sendButton)!=null?ar:{}).size)!=null?lr:"40px";ot||(ot=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ot.style.display="none",lt.insertBefore(ot,X)),ge||(ge=document.createElement("input"),ge.type="file",ge.accept=((dr=x.allowedTypes)!=null?dr:Jt).join(","),ge.multiple=((cr=x.maxFiles)!=null?cr:4)>1,ge.style.display="none",ge.setAttribute("aria-label","Attach files"),lt.insertBefore(ge,X)),st=p("div","tvw-send-button-wrapper"),pe=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),pe.type="button",pe.setAttribute("aria-label",(ur=x.buttonTooltipText)!=null?ur:"Attach file");let ne=(pr=x.buttonIconName)!=null?pr:"paperclip",ve=Oe,gt=parseFloat(ve)||40,at=Math.round(gt*.6);pe.style.width=ve,pe.style.height=ve,pe.style.minWidth=ve,pe.style.minHeight=ve,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.style.backgroundColor="transparent",pe.style.color="var(--cw-primary, #111827)",pe.style.border="none",pe.style.borderRadius="6px",pe.style.transition="background-color 0.15s ease",pe.addEventListener("mouseenter",()=>{pe.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),pe.addEventListener("mouseleave",()=>{pe.style.backgroundColor="transparent"});let Mt=oe(ne,at,"currentColor",1.5);Mt?pe.appendChild(Mt):pe.textContent="\u{1F4CE}",pe.addEventListener("click",Et=>{Et.preventDefault(),ge==null||ge.click()}),st.appendChild(pe);let ht=(gr=x.buttonTooltipText)!=null?gr:"Attach file",Ne=p("div","tvw-send-button-tooltip");Ne.textContent=ht,st.appendChild(Ne),Pt.append(st),!Ae&&ge&&ot&&(Ae=Qt.fromConfig(x),Ae.setPreviewsContainer(ot),ge.addEventListener("change",async()=>{Ae&&(ge!=null&&ge.files)&&(await Ae.handleFileSelect(ge.files),ge.value="")}))}else{st.style.display="";let x=(mr=t.attachments)!=null?mr:{};ge&&(ge.accept=((hr=x.allowedTypes)!=null?hr:Jt).join(","),ge.multiple=((fr=x.maxFiles)!=null?fr:4)>1),Ae&&Ae.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else st&&(st.style.display="none"),Ae&&Ae.clearAttachments();let ze=(wr=t.sendButton)!=null?wr:{},$n=(yr=ze.useIcon)!=null?yr:!1,wn=(vr=ze.iconText)!=null?vr:"\u2191",yn=ze.iconName,zt=(br=ze.tooltipText)!=null?br:"Send message",vn=(Cr=ze.showTooltip)!=null?Cr:!1,bn=(xr=ze.size)!=null?xr:"40px",On=ze.backgroundColor,Rt=ze.textColor;if($n){if(D.style.width=bn,D.style.height=bn,D.style.minWidth=bn,D.style.minHeight=bn,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",yn){let x=parseFloat(bn)||24,ue=Rt&&typeof Rt=="string"&&Rt.trim()?Rt.trim():"currentColor",Oe=oe(yn,x,ue,2);Oe?(D.appendChild(Oe),D.style.color=ue):(D.textContent=wn,Rt?D.style.color=Rt:D.classList.add("tvw-text-white"))}else D.textContent=wn,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",On?(D.style.backgroundColor=On,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Ar=(Sr=t.copy)==null?void 0:Sr.sendButtonLabel)!=null?Ar:"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",On?(D.style.backgroundColor=On,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");ze.borderWidth?(D.style.borderWidth=ze.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),ze.borderColor?D.style.borderColor=ze.borderColor:D.style.borderColor="",ze.paddingX?(D.style.paddingLeft=ze.paddingX,D.style.paddingRight=ze.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ze.paddingY?(D.style.paddingTop=ze.paddingY,D.style.paddingBottom=ze.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Cn=nt==null?void 0:nt.querySelector(".tvw-send-button-tooltip");if(vn&&zt)if(Cn)Cn.textContent=zt,Cn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=zt,nt==null||nt.insertBefore(x,D)}else Cn&&(Cn.style.display="none");let xn=(Tr=t.statusIndicator)!=null?Tr:{},xi=(Mr=xn.visible)!=null?Mr:!0;if(dt.style.display=xi?"":"none",H){let x=H.getStatus(),ue=Oe=>{var ne,ve,gt,at;return Oe==="idle"?(ne=xn.idleText)!=null?ne:mt.idle:Oe==="connecting"?(ve=xn.connectingText)!=null?ve:mt.connecting:Oe==="connected"?(gt=xn.connectedText)!=null?gt:mt.connected:Oe==="error"?(at=xn.errorText)!=null?at:mt.error:mt[Oe]};dt.textContent=ue(x)}},open(){h&&E(!0,"api")},close(){h&&E(!1,"api")},toggle(){h&&E(!R,"api")},clearChat(){H.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||H.isStreaming()?!1:(!R&&h&&E(!0,"system"),X.value=l,X.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let c=(l==null?void 0:l.trim())||X.value.trim();return c?(!R&&h&&E(!0,"system"),X.value="",X.style.height="auto",H.sendMessage(c),!0):!1},startVoiceRecognition(){return me||H.isStreaming()||!Ie()?!1:(!R&&h&&E(!0,"system"),Le.manuallyDeactivated=!1,jt(),_e("user"),!0)},stopVoiceRecognition(){return me?(Le.manuallyDeactivated=!0,jt(),We("user"),!0):!1},injectMessage(l){return!R&&h&&E(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){return!R&&h&&E(!0,"system"),H.injectAssistantMessage(l)},injectUserMessage(l){return!R&&h&&E(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!R&&h&&E(!0,"system"),H.injectSystemMessage(l)},injectTestMessage(l){!R&&h&&E(!0,"system"),H.injectTestEvent(l)},getMessages(){return H.getMessages()},getStatus(){return H.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&&R},isVoiceActive(){return Le.active},getState(){return{open:h&&R,launcherEnabled:h,voiceActive:Le.active,streaming:H.isStreaming()}},showCSATFeedback(l){!R&&h&&E(!0,"system");let c=V.querySelector(".tvw-feedback-container");c&&c.remove();let A=os({onSubmit:async(P,b)=>{var Q;H.isClientTokenMode()&&await H.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){!R&&h&&E(!0,"system");let c=V.querySelector(".tvw-feedback-container");c&&c.remove();let A=rs({onSubmit:async(P,b)=>{var Q;H.isClientTokenMode()&&await H.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 H.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return H.submitNPSFeedback(l,c)},destroy(){ke.forEach(l=>l()),z.remove(),le==null||le.destroy(),he==null||he.remove(),rt&&q.removeEventListener("click",rt)}};if((((Gs=o==null?void 0:o.debugTools)!=null?Gs:!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,ke.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return Dt};var Ls={},sa=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},oa=()=>{try{if(typeof Ls!="undefined"&&Ls.url)return new URL("../widget.css",Ls.url).href}catch{}return null},mi=e=>{let n=oa(),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)}},Ps=e=>{var u,f,g,m;let n=sa(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),mi(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),mi(o);let a=is(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 hi={name:"@runtypelabs/persona",version:"1.38.1",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=hi.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 ia(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 fi=`({ text, message }: any) => {
60
+ `}if(!Se){let zt="max-height: -moz-available !important; max-height: stretch !important;",bn=l?"":"padding-top: 1.25em !important;";z.style.cssText+=zt+bn}};Ze(),Xn(e,t);let We=[],Ke=null,kt=()=>{Ke&&(Ke(),Ke=null),t.colorScheme==="auto"&&(Ke=Gr(()=>{Xn(e,t)}))};kt(),We.push(()=>{Ke&&(Ke(),Ke=null)});let ft=ii(He),rt=null,H,wt=!1,yt=!0,At=0,te=0,we=null,Fe=!1,vt=0,et=!1,Bt=125,It=2e3,Ot=5,nn=50,Nt=new Map,Le={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},mn=(Xs=(Vs=t.voiceRecognition)==null?void 0:Vs.autoResume)!=null?Xs:!1,hn=l=>{s.emit("voice:state",{active:Le.active,source:l,timestamp:Date.now()})},jt=()=>{f(l=>({...l,voiceState:{active:Le.active,timestamp:Date.now(),manuallyDeactivated:Le.manuallyDeactivated}}))},Bn=()=>{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);Le.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-A<na&&setTimeout(()=>{Le.active||(Le.manuallyDeactivated=!1,_e("restore"))},1e3)},In=()=>H?pi(H.getMessages()).filter(l=>!l.__skipPersist):[];function fn(l){if(!(i!=null&&i.save))return;let A={messages:l?pi(l):H?In():[],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();Fe&&c<vt&&!l||(Fe&&c>=vt&&(Fe=!1),!(!l&&!wt)&&(c-te<Bt||(te=c,we&&cancelAnimationFrame(we),we=requestAnimationFrame(()=>{Fe||!yt||(et=!0,B.scrollTop=B.scrollHeight,At=B.scrollTop,requestAnimationFrame(()=>{et=!1}),we=null)}))))},L=null,ae=()=>z.querySelector("#persona-scroll-container")||B,xe=(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=ye=>1-Math.pow(1-ye,3),Z=ye=>{let O=l.scrollHeight;O!==b&&(b=O,Q=b-A);let $e=ye-M,Se=Math.min($e/c,1),ce=G(Se),qe=A+Q*ce;l.scrollTop=qe,Se<1?L=requestAnimationFrame(Z):(l.scrollTop=l.scrollHeight,L=null)};L=requestAnimationFrame(Z)},De=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)})},Ve=(l,c,A)=>{let P=document.createElement("div");c.forEach(M=>{var $e,Se;let G=null,Z=r.find(ce=>!!(M.variant==="reasoning"&&ce.renderReasoning||M.variant==="tool"&&ce.renderToolCall||!M.variant&&ce.renderMessage)),ye=($e=t.layout)==null?void 0:$e.messages;if(Z)if(M.variant==="reasoning"&&M.reasoning&&Z.renderReasoning){if(!N)return;G=Z.renderReasoning({message:M,defaultRenderer:()=>Cs(M),config:t})}else if(M.variant==="tool"&&M.toolCall&&Z.renderToolCall){if(!C)return;G=Z.renderToolCall({message:M,defaultRenderer:()=>xs(M,t),config:t})}else Z.renderMessage&&(G=Z.renderMessage({message:M,defaultRenderer:()=>{let ce=ln(M,A,ye,t.messageActions,W);return M.role!=="user"&&Ss(ce,M,t,H),ce},config:t}));if(!G&&M.role==="assistant"&&!M.variant&&t.enableComponentStreaming!==!1&&ns(M)){let qe=ss(M);if(qe){let Ue=ts(qe,{config:t,message:M,transform:A});if(Ue){let it=document.createElement("div");if(it.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(" "),it.id=`bubble-${M.id}`,it.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}),it.appendChild(Tt)}it.appendChild(Ue),G=it}}}if(!G)if(M.variant==="reasoning"&&M.reasoning){if(!N)return;G=Cs(M)}else if(M.variant==="tool"&&M.toolCall){if(!C)return;G=xs(M,t)}else{let ce=(Se=t.layout)==null?void 0:Se.messages;ce!=null&&ce.renderUserMessage&&M.role==="user"?G=ce.renderUserMessage({message:M,config:t,streaming:!!M.streaming}):ce!=null&&ce.renderAssistantMessage&&M.role==="assistant"?G=ce.renderAssistantMessage({message:M,config:t,streaming:!!M.streaming}):G=ln(M,A,ce,t.messageActions,W),M.role!=="user"&&G&&Ss(G,M,t,H)}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],de=(Q==null?void 0:Q.role)==="assistant"&&!Q.streaming;if(wt&&c.some(M=>M.role==="user")&&!b&&!de){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)}Zr(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let M=ae();xe(M)})})},Pe=()=>{h&&(R?(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"),le?le.element.style.display="none":he&&(he.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"),le?le.element.style.display="":he&&(he.style.display="")))},E=(l,c="user")=>{if(!h||R===l)return;let A=R;R=l,Pe(),R&&(wn(),Yt(!0));let P={open:R,source:c,timestamp:Date.now()};R&&!A?s.emit("widget:opened",P):!R&&A&&s.emit("widget:closed",P),s.emit("widget:state",{open:R,launcherEnabled:h,voiceActive:Le.active,streaming:H.isStreaming()})},bt=l=>{D.disabled=l,$&&($.disabled=l),ft.buttons.forEach(c=>{c.disabled=l})},se=()=>{var b,Q,de,M,G,Z,ye,O,$e,Se,ce,qe,Ue,it;Lt.textContent=(Q=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?Q:"Hello \u{1F44B}",Ft.textContent=(M=(de=t.copy)==null?void 0:de.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=(ye=t.sendButton)==null?void 0:ye.useIcon)!=null?O:!1)||(D.textContent=(Se=($e=t.copy)==null?void 0:$e.sendButtonLabel)!=null?Se:"Send");let c=(qe=(ce=t.theme)==null?void 0:ce.inputFontFamily)!=null?qe:"sans-serif",A=(it=(Ue=t.theme)==null?void 0:Ue.inputFontWeight)!=null?it:"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}))}}),H=new on(t,{onMessagesChanged(l){Ve(V,l,v),H&&(l.some(P=>P.role==="user")?ft.render([],H,X,l):ft.render(t.suggestionChips,H,X,l,t.suggestionChipsConfig)),Yt(!wt),De(l);let c=[...l].reverse().find(A=>A.role==="user");Le.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),fn(l)},onStatusChanged(l){var P;let c=(P=t.statusIndicator)!=null?P:{},A=b=>{var Q,de,M,G;return b==="idle"?(Q=c.idleText)!=null?Q:mt.idle:b==="connecting"?(de=c.connectingText)!=null?de:mt.connecting:b==="connected"?(M=c.connectedText)!=null?M:mt.connected:b==="error"?(G=c.errorText)!=null?G:mt.error:mt[b]};dt.textContent=A(l)},onStreamingChanged(l){wt=l,bt(l),H&&Ve(V,H.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&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let I=l=>{var b;l.preventDefault();let c=X.value.trim(),A=(b=Ae==null?void 0:Ae.hasAttachments())!=null?b:!1;if(!c&&!A)return;let P;A&&(P=[],P.push(...Ae.getContentParts()),c&&P.push(Yn(c))),X.value="",X.style.height="auto",H.sendMessage(c,{contentParts:P}),A&&Ae.clearAttachments()},k=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),D.click())},U=null,me=!1,Te=null,Xe=null,Ie=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,_e=(l="user")=>{var Q,de,M,G;if(me||H.isStreaming())return;let c=Ie();if(!c)return;U=new c;let P=(de=((Q=t.voiceRecognition)!=null?Q:{}).pauseDuration)!=null?de:2e3;U.continuous=!0,U.interimResults=!0,U.lang="en-US";let b=X.value;U.onresult=Z=>{let ye="",O="";for(let Se=0;Se<Z.results.length;Se++){let ce=Z.results[Se],qe=ce[0].transcript;ce.isFinal?ye+=qe+" ":O=qe}let $e=b+ye+O;X.value=$e,Te&&clearTimeout(Te),(ye||O)&&(Te=window.setTimeout(()=>{let Se=X.value.trim();Se&&U&&me&&(ke(),X.value="",X.style.height="auto",H.sendMessage(Se,{viaVoice:!0}))},P))},U.onerror=Z=>{Z.error!=="no-speech"&&ke()},U.onend=()=>{if(me){let Z=X.value.trim();Z&&Z!==b.trim()&&(X.value="",X.style.height="auto",H.sendMessage(Z,{viaVoice:!0})),ke()}};try{if(U.start(),me=!0,Le.active=!0,l!=="system"&&(Le.manuallyDeactivated=!1),hn(l),jt(),$){Xe={backgroundColor:$.style.backgroundColor,color:$.style.color,borderColor:$.style.borderColor};let Z=(M=t.voiceRecognition)!=null?M:{},ye=(G=Z.recordingBackgroundColor)!=null?G:"#ef4444",O=Z.recordingIconColor,$e=Z.recordingBorderColor;if($.classList.add("tvw-voice-recording"),$.style.backgroundColor=ye,O){$.style.color=O;let Se=$.querySelector("svg");Se&&Se.setAttribute("stroke",O)}$e&&($.style.borderColor=$e),$.setAttribute("aria-label","Stop voice recognition")}}catch{ke("system")}},ke=(l="user")=>{if(me){if(me=!1,Te&&(clearTimeout(Te),Te=null),U){try{U.stop()}catch{}U=null}if(Le.active=!1,hn(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")}}},be=(l,c)=>{var qe,Ue,it,Tt,ee,Ee,Kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=g("div","tvw-send-button-wrapper"),b=g("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=(qe=l==null?void 0:l.iconName)!=null?qe:"mic",de=(Ue=c==null?void 0:c.size)!=null?Ue:"40px",M=(it=l==null?void 0:l.iconSize)!=null?it:de,G=parseFloat(M)||24,Z=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,ye=(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=ye||"currentColor",$e=oe(Q,G,O,1.5);$e?(b.appendChild($e),b.style.color=O):(b.textContent="\u{1F3A4}",b.style.color=O),Z?b.style.backgroundColor=Z:b.classList.add("tvw-bg-cw-primary"),ye?b.style.color=ye:!ye&&!(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 Se=(Ee=l==null?void 0:l.tooltipText)!=null?Ee:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&Se){let Vt=g("div","tvw-send-button-tooltip");Vt.textContent=Se,P.appendChild(Vt)}return{micButton:b,micButtonWrapper:P}},Ce=()=>{if(me){let l=X.value.trim();Le.manuallyDeactivated=!0,jt(),ke("user"),l&&(X.value="",X.style.height="auto",H.sendMessage(l))}else Le.manuallyDeactivated=!1,jt(),_e("user")};$&&($.addEventListener("click",Ce),We.push(()=>{ke("system"),$&&$.removeEventListener("click",Ce)}));let Ge=s.on("assistant:complete",()=>{mn&&(Le.active||Le.manuallyDeactivated||mn==="assistant"&&!Le.lastUserMessageWasVoice||setTimeout(()=>{!Le.active&&!Le.manuallyDeactivated&&_e("auto")},600))});We.push(Ge);let Me=s.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});We.push(Me);let Re=()=>{E(!R,"user")},le=null,he=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>kn(t,Re).element,onToggle:Re});c&&(he=c)}he||(le=kn(t,Re))}le?e.appendChild(le.element):he&&e.appendChild(he),Pe(),ft.render(t.suggestionChips,H,X,void 0,t.suggestionChipsConfig),se(),bt(H.isStreaming()),Yt(!0),Bn();let wn=()=>{var A,P,b,Q,de,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 ye=(M=(de=t==null?void 0:t.launcher)==null?void 0:de.width)!=null?M:t==null?void 0:t.launcherWidth,O=ye!=null?ye:"min(400px, calc(100vw - 24px))";_.style.width=O,_.style.maxWidth=O}if(!c){let ye=window.innerHeight,O=64,$e=(Z=(G=t.launcher)==null?void 0:G.heightOffset)!=null?Z:0,Se=Math.max(200,ye-O),ce=Math.min(640,Se),qe=Math.max(200,ce-$e);_.style.height=`${qe}px`}};wn(),window.addEventListener("resize",wn),We.push(()=>window.removeEventListener("resize",wn)),At=B.scrollTop;let Bs=()=>{let l=B.scrollTop,c=B.scrollHeight,A=B.clientHeight,P=c-l-A,b=Math.abs(l-At);if(At=l,!et&&!(b<=Ot)){if(!yt&&P<nn){Fe=!1,yt=!0;return}yt&&P>nn&&(Fe=!0,vt=Date.now()+It,yt=!1)}};B.addEventListener("scroll",Bs,{passive:!0}),We.push(()=>B.removeEventListener("scroll",Bs)),We.push(()=>{we&&cancelAnimationFrame(we)});let Is=()=>{q&&(rt&&(q.removeEventListener("click",rt),rt=null),h?(q.style.display="",rt=()=>{R=!1,Pe()},q.addEventListener("click",rt)):q.style.display="none")};Is(),(()=>{let{clearChatButton:l}=j;l&&l.addEventListener("click",()=>{H.clearMessages();try{localStorage.removeItem(gn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gn}`)}catch(A){console.error("[AgentWidget] Failed to clear default localStorage:",A)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==gn)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()})})(),lt.addEventListener("submit",I),X.addEventListener("keydown",k),We.push(()=>{lt.removeEventListener("submit",I),X.removeEventListener("keydown",k)}),We.push(()=>{H.cancel()}),le?We.push(()=>{le==null||le.destroy()}):he&&We.push(()=>{he==null||he.remove()});let Dt={update(l){var 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,ko,Wo,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,Mr;let c=t.toolCall,A=t.colorScheme;t={...t,...l},Ze(),Xn(e,t),t.colorScheme!==A&&kt();let P=Ln.getForInstance(t.plugins);if(r.length=0,r.push(...P),h=(Zs=(Qs=t.launcher)==null?void 0:Qs.enabled)!=null?Zs:!0,F=(to=(eo=t.launcher)==null?void 0:eo.autoExpand)!=null?to:!1,N=(so=(no=t.features)==null?void 0:no.showReasoning)!=null?so:!0,C=(ro=(oo=t.features)==null?void 0:oo.showToolCalls)!=null?ro:!0,((io=t.launcher)==null?void 0:io.enabled)===!1&&le&&(le.destroy(),le=null),((ao=t.launcher)==null?void 0:ao.enabled)===!1&&he&&(he.remove(),he=null),((lo=t.launcher)==null?void 0:lo.enabled)!==!1&&!le&&!he){let x=r.find(ue=>ue.renderLauncher);if(x!=null&&x.renderLauncher){let ue=x.renderLauncher({config:t,defaultRenderer:()=>kn(t,Re).element,onToggle:Re});ue&&(he=ue,e.appendChild(he))}he||(le=kn(t,Re),e.appendChild(le.element))}le&&le.update(t),ct&&((co=t.launcher)==null?void 0:co.title)!==void 0&&(ct.textContent=t.launcher.title),ut&&((uo=t.launcher)==null?void 0:uo.subtitle)!==void 0&&(ut.textContent=t.launcher.subtitle);let b=(po=t.layout)==null?void 0:po.header;if((b==null?void 0:b.layout)!==S&&Je){let x=b?rn(t,b,{showClose:h,onClose:()=>E(!1,"user")}):qt({config:t,showClose:h,onClose:()=>E(!1,"user")});Je.replaceWith(x.header),Je=x.header,fe=x.iconHolder,ct=x.headerTitle,ut=x.headerSubtitle,q=x.closeButton,S=b==null?void 0:b.layout}else if(b&&(fe&&(fe.style.display=b.showIcon===!1?"none":""),ct&&(ct.style.display=b.showTitle===!1?"none":""),ut&&(ut.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:ue}=j;ue&&!ue.classList.contains("tvw-absolute")&&(x?ue.classList.remove("tvw-ml-auto"):ue.classList.add("tvw-ml-auto"))}}let de=((go=t.layout)==null?void 0:go.showHeader)!==!1;Je&&(Je.style.display=de?"":"none");let M=((mo=t.layout)==null?void 0:mo.showFooter)!==!1;pt&&(pt.style.display=M?"":"none"),h!==y?h?E(F,"auto"):(R=!0,Pe()):F!==T&&E(F,"auto"),T=F,y=h,wn(),Is(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&H&&Ve(V,H.getMessages(),v);let O=(ho=t.launcher)!=null?ho:{},$e=(fo=O.headerIconHidden)!=null?fo:!1,Se=(yo=(wo=t.layout)==null?void 0:wo.header)==null?void 0:yo.showIcon,ce=$e||Se===!1,qe=O.headerIconName,Ue=(vo=O.headerIconSize)!=null?vo:"48px";if(fe){let x=Y.querySelector(".tvw-border-b-cw-divider"),ue=x==null?void 0:x.querySelector(".tvw-flex-col");if(ce)fe.style.display="none",x&&ue&&!x.contains(ue)&&x.insertBefore(ue,x.firstChild);else{if(fe.style.display="",fe.style.height=Ue,fe.style.width=Ue,x&&ue&&(x.contains(fe)?fe.nextSibling!==ue&&(fe.remove(),x.insertBefore(fe,ue)):x.insertBefore(fe,ue)),qe){let ne=parseFloat(Ue)||24,ve=oe(qe,ne*.6,"#ffffff",2);ve?fe.replaceChildren(ve):fe.textContent=(bo=O.agentIconText)!=null?bo:"\u{1F4AC}"}else if(O.iconUrl){let ne=fe.querySelector("img");if(ne)ne.src=O.iconUrl,ne.style.height=Ue,ne.style.width=Ue;else{let ve=document.createElement("img");ve.src=O.iconUrl,ve.alt="",ve.className="tvw-rounded-xl tvw-object-cover",ve.style.height=Ue,ve.style.width=Ue,fe.replaceChildren(ve)}}else{let ne=fe.querySelector("svg"),ve=fe.querySelector("img");(ne||ve)&&fe.replaceChildren(),fe.textContent=(Co=O.agentIconText)!=null?Co:"\u{1F4AC}"}let Oe=fe.querySelector("img");Oe&&(Oe.style.height=Ue,Oe.style.width=Ue)}}let it=(So=(xo=t.layout)==null?void 0:xo.header)==null?void 0:So.showTitle,Tt=(To=(Ao=t.layout)==null?void 0:Ao.header)==null?void 0:To.showSubtitle;if(ct&&(ct.style.display=it===!1?"none":""),ut&&(ut.style.display=Tt===!1?"none":""),q){((Eo=(Mo=t.layout)==null?void 0:Mo.header)==null?void 0:Eo.showCloseButton)===!1?q.style.display="none":q.style.display="";let ue=(ko=O.closeButtonSize)!=null?ko:"32px",Oe=(Wo=O.closeButtonPlacement)!=null?Wo:"inline";q.style.height=ue,q.style.width=ue;let{closeButtonWrapper:ne}=j,ve=Oe==="top-right",gt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&ve!==gt)if(ne.remove(),ve)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(ne);else{let re=(Po=(Lo=O.clearChat)==null?void 0:Lo.placement)!=null?Po:"inline",Qe=(Bo=(Ho=O.clearChat)==null?void 0:Ho.enabled)!=null?Bo:!0;ne.className=Qe&&re==="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 re=O.closeButtonBorderWidth||"0px",Qe=O.closeButtonBorderColor||"transparent";q.style.border=`${re} solid ${Qe}`,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 at=(Io=O.closeButtonIconName)!=null?Io:"x",Mt=(Ro=O.closeButtonIconText)!=null?Ro:"\xD7";q.innerHTML="";let ht=oe(at,"20px",O.closeButtonColor||"",2);ht?q.appendChild(ht):q.textContent=Mt;let Ne=(Fo=O.closeButtonTooltipText)!=null?Fo:"Close chat",Et=($o=O.closeButtonShowTooltip)!=null?$o:!0;if(q.setAttribute("aria-label",Ne),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),Et&&Ne)){let re=null,Qe=()=>{if(re||!q)return;re=g("div","tvw-clear-chat-tooltip"),re.textContent=Ne;let An=g("div");An.className="tvw-clear-chat-tooltip-arrow",re.appendChild(An);let Xt=q.getBoundingClientRect();re.style.position="fixed",re.style.left=`${Xt.left+Xt.width/2}px`,re.style.top=`${Xt.top-8}px`,re.style.transform="translate(-50%, -100%)",document.body.appendChild(re)},Ct=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};ne.addEventListener("mouseenter",Qe),ne.addEventListener("mouseleave",Ct),q.addEventListener("focus",Qe),q.addEventListener("blur",Ct),ne._cleanupTooltip=()=>{Ct(),ne&&(ne.removeEventListener("mouseenter",Qe),ne.removeEventListener("mouseleave",Ct)),q&&(q.removeEventListener("focus",Qe),q.removeEventListener("blur",Ct))}}}let{clearChatButton:ee,clearChatButtonWrapper:Ee}=j;if(ee){let x=(Oo=O.clearChat)!=null?Oo:{},ue=(No=x.enabled)!=null?No:!0,Oe=(Do=(jo=t.layout)==null?void 0:jo.header)==null?void 0:Do.showClearChat,ne=Oe!==void 0?Oe:ue,ve=(_o=x.placement)!=null?_o:"inline";if(Ee){Ee.style.display=ne?"":"none";let{closeButtonWrapper:gt}=j;gt&&!gt.classList.contains("tvw-absolute")&&(ne?gt.classList.remove("tvw-ml-auto"):gt.classList.add("tvw-ml-auto"));let at=ve==="top-right",Mt=Ee.classList.contains("tvw-absolute");if(at!==Mt&&ne){if(Ee.remove(),at)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 Ne=Y.querySelector(".tvw-border-b-cw-divider"),Et=j.closeButtonWrapper;Ne&&Et&&Et.parentElement===Ne?Ne.insertBefore(Ee,Et):Ne&&Ne.appendChild(Ee)}let ht=j.closeButtonWrapper;ht&&!ht.classList.contains("tvw-absolute")&&(at?ht.classList.add("tvw-ml-auto"):ht.classList.remove("tvw-ml-auto"))}}if(ne){let gt=(qo=x.size)!=null?qo:"32px";ee.style.height=gt,ee.style.width=gt;let at=(Uo=x.iconName)!=null?Uo:"refresh-cw",Mt=(zo=x.iconColor)!=null?zo:"";ee.innerHTML="";let ht=oe(at,"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 re=x.borderWidth||"0px",Qe=x.borderColor||"transparent";ee.style.border=`${re} solid ${Qe}`,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 Ne=(Jo=x.tooltipText)!=null?Jo:"Clear chat",Et=(Yo=x.showTooltip)!=null?Yo:!0;if(ee.setAttribute("aria-label",Ne),Ee&&(Ee._cleanupTooltip&&(Ee._cleanupTooltip(),delete Ee._cleanupTooltip),Et&&Ne)){let re=null,Qe=()=>{if(re||!ee)return;re=g("div","tvw-clear-chat-tooltip"),re.textContent=Ne;let An=g("div");An.className="tvw-clear-chat-tooltip-arrow",re.appendChild(An);let Xt=ee.getBoundingClientRect();re.style.position="fixed",re.style.left=`${Xt.left+Xt.width/2}px`,re.style.top=`${Xt.top-8}px`,re.style.transform="translate(-50%, -100%)",document.body.appendChild(re)},Ct=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};Ee.addEventListener("mouseenter",Qe),Ee.addEventListener("mouseleave",Ct),ee.addEventListener("focus",Qe),ee.addEventListener("blur",Ct),Ee._cleanupTooltip=()=>{Ct(),Ee&&(Ee.removeEventListener("mouseenter",Qe),Ee.removeEventListener("mouseleave",Ct)),ee&&(ee.removeEventListener("focus",Qe),ee.removeEventListener("blur",Ct))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Pn],Vt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick];w=Hn({parsers:Kt,handlers:Vt,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),v=gi(t,w),H.updateConfig(t),Ve(V,H.getMessages(),v),ft.render(t.suggestionChips,H,X,void 0,t.suggestionChipsConfig),se(),bt(H.isStreaming());let Rn=((Ko=t.voiceRecognition)==null?void 0:Ko.enabled)===!0,Fn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Rn&&Fn)if(!$||!je){let x=be(t.voiceRecognition,t.sendButton);x&&($=x.micButton,je=x.micButtonWrapper,Ht.insertBefore(je,nt),$.addEventListener("click",Ce),$.disabled=H.isStreaming())}else{let x=(Vo=t.voiceRecognition)!=null?Vo:{},ue=(Xo=t.sendButton)!=null?Xo:{},Oe=(Go=x.iconName)!=null?Go:"mic",ne=(Qo=ue.size)!=null?Qo:"40px",ve=(Zo=x.iconSize)!=null?Zo:ne,gt=parseFloat(ve)||24;$.style.width=ve,$.style.height=ve,$.style.minWidth=ve,$.style.minHeight=ve;let at=(tr=(er=x.iconColor)!=null?er:ue.textColor)!=null?tr:"currentColor";$.innerHTML="";let Mt=oe(Oe,gt,at,2);Mt?$.appendChild(Mt):$.textContent="\u{1F3A4}";let ht=(nr=x.backgroundColor)!=null?nr:ue.backgroundColor;ht?($.style.backgroundColor=ht,$.classList.remove("tvw-bg-cw-primary")):($.style.backgroundColor="",$.classList.add("tvw-bg-cw-primary")),at?($.style.color=at,$.classList.remove("tvw-text-white")):!at&&!ue.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 Ne=je==null?void 0:je.querySelector(".tvw-send-button-tooltip"),Et=(sr=x.tooltipText)!=null?sr:"Start voice recognition";if(((or=x.showTooltip)!=null?or:!1)&&Et)if(Ne)Ne.textContent=Et,Ne.style.display="";else{let Qe=document.createElement("div");Qe.className="tvw-send-button-tooltip",Qe.textContent=Et,je==null||je.insertBefore(Qe,$)}else Ne&&(Ne.style.display="none");je.style.display="",$.disabled=H.isStreaming()}else $&&je&&(je.style.display="none",me&&ke());if(((rr=t.attachments)==null?void 0:rr.enabled)===!0)if(!st||!pe){let x=(ir=t.attachments)!=null?ir:{},Oe=(lr=((ar=t.sendButton)!=null?ar:{}).size)!=null?lr:"40px";ot||(ot=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ot.style.display="none",lt.insertBefore(ot,X)),ge||(ge=document.createElement("input"),ge.type="file",ge.accept=((dr=x.allowedTypes)!=null?dr:Jt).join(","),ge.multiple=((cr=x.maxFiles)!=null?cr:4)>1,ge.style.display="none",ge.setAttribute("aria-label","Attach files"),lt.insertBefore(ge,X)),st=g("div","tvw-send-button-wrapper"),pe=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),pe.type="button",pe.setAttribute("aria-label",(ur=x.buttonTooltipText)!=null?ur:"Attach file");let ne=(pr=x.buttonIconName)!=null?pr:"paperclip",ve=Oe,gt=parseFloat(ve)||40,at=Math.round(gt*.6);pe.style.width=ve,pe.style.height=ve,pe.style.minWidth=ve,pe.style.minHeight=ve,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.style.backgroundColor="transparent",pe.style.color="var(--cw-primary, #111827)",pe.style.border="none",pe.style.borderRadius="6px",pe.style.transition="background-color 0.15s ease",pe.addEventListener("mouseenter",()=>{pe.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),pe.addEventListener("mouseleave",()=>{pe.style.backgroundColor="transparent"});let Mt=oe(ne,at,"currentColor",1.5);Mt?pe.appendChild(Mt):pe.textContent="\u{1F4CE}",pe.addEventListener("click",Et=>{Et.preventDefault(),ge==null||ge.click()}),st.appendChild(pe);let ht=(gr=x.buttonTooltipText)!=null?gr:"Attach file",Ne=g("div","tvw-send-button-tooltip");Ne.textContent=ht,st.appendChild(Ne),Pt.append(st),!Ae&&ge&&ot&&(Ae=Qt.fromConfig(x),Ae.setPreviewsContainer(ot),ge.addEventListener("change",async()=>{Ae&&(ge!=null&&ge.files)&&(await Ae.handleFileSelect(ge.files),ge.value="")}))}else{st.style.display="";let x=(mr=t.attachments)!=null?mr:{};ge&&(ge.accept=((hr=x.allowedTypes)!=null?hr:Jt).join(","),ge.multiple=((fr=x.maxFiles)!=null?fr:4)>1),Ae&&Ae.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else st&&(st.style.display="none"),Ae&&Ae.clearAttachments();let ze=(wr=t.sendButton)!=null?wr:{},$n=(yr=ze.useIcon)!=null?yr:!1,yn=(vr=ze.iconText)!=null?vr:"\u2191",vn=ze.iconName,zt=(br=ze.tooltipText)!=null?br:"Send message",bn=(Cr=ze.showTooltip)!=null?Cr:!1,Cn=(xr=ze.size)!=null?xr:"40px",On=ze.backgroundColor,Rt=ze.textColor;if($n){if(D.style.width=Cn,D.style.height=Cn,D.style.minWidth=Cn,D.style.minHeight=Cn,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",vn){let x=parseFloat(Cn)||24,ue=Rt&&typeof Rt=="string"&&Rt.trim()?Rt.trim():"currentColor",Oe=oe(vn,x,ue,2);Oe?(D.appendChild(Oe),D.style.color=ue):(D.textContent=yn,Rt?D.style.color=Rt:D.classList.add("tvw-text-white"))}else D.textContent=yn,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",On?(D.style.backgroundColor=On,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Ar=(Sr=t.copy)==null?void 0:Sr.sendButtonLabel)!=null?Ar:"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",On?(D.style.backgroundColor=On,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");ze.borderWidth?(D.style.borderWidth=ze.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),ze.borderColor?D.style.borderColor=ze.borderColor:D.style.borderColor="",ze.paddingX?(D.style.paddingLeft=ze.paddingX,D.style.paddingRight=ze.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ze.paddingY?(D.style.paddingTop=ze.paddingY,D.style.paddingBottom=ze.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let xn=nt==null?void 0:nt.querySelector(".tvw-send-button-tooltip");if(bn&&zt)if(xn)xn.textContent=zt,xn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=zt,nt==null||nt.insertBefore(x,D)}else xn&&(xn.style.display="none");let Sn=(Tr=t.statusIndicator)!=null?Tr:{},xi=(Mr=Sn.visible)!=null?Mr:!0;if(dt.style.display=xi?"":"none",H){let x=H.getStatus(),ue=Oe=>{var ne,ve,gt,at;return Oe==="idle"?(ne=Sn.idleText)!=null?ne:mt.idle:Oe==="connecting"?(ve=Sn.connectingText)!=null?ve:mt.connecting:Oe==="connected"?(gt=Sn.connectedText)!=null?gt:mt.connected:Oe==="error"?(at=Sn.errorText)!=null?at:mt.error:mt[Oe]};dt.textContent=ue(x)}},open(){h&&E(!0,"api")},close(){h&&E(!1,"api")},toggle(){h&&E(!R,"api")},clearChat(){H.clearMessages();try{localStorage.removeItem(gn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gn}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==gn)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||H.isStreaming()?!1:(!R&&h&&E(!0,"system"),X.value=l,X.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let c=(l==null?void 0:l.trim())||X.value.trim();return c?(!R&&h&&E(!0,"system"),X.value="",X.style.height="auto",H.sendMessage(c),!0):!1},startVoiceRecognition(){return me||H.isStreaming()||!Ie()?!1:(!R&&h&&E(!0,"system"),Le.manuallyDeactivated=!1,jt(),_e("user"),!0)},stopVoiceRecognition(){return me?(Le.manuallyDeactivated=!0,jt(),ke("user"),!0):!1},injectMessage(l){return!R&&h&&E(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){return!R&&h&&E(!0,"system"),H.injectAssistantMessage(l)},injectUserMessage(l){return!R&&h&&E(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!R&&h&&E(!0,"system"),H.injectSystemMessage(l)},injectTestMessage(l){!R&&h&&E(!0,"system"),H.injectTestEvent(l)},getMessages(){return H.getMessages()},getStatus(){return H.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&&R},isVoiceActive(){return Le.active},getState(){return{open:h&&R,launcherEnabled:h,voiceActive:Le.active,streaming:H.isStreaming()}},showCSATFeedback(l){!R&&h&&E(!0,"system");let c=V.querySelector(".tvw-feedback-container");c&&c.remove();let A=os({onSubmit:async(P,b)=>{var Q;H.isClientTokenMode()&&await H.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){!R&&h&&E(!0,"system");let c=V.querySelector(".tvw-feedback-container");c&&c.remove();let A=rs({onSubmit:async(P,b)=>{var Q;H.isClientTokenMode()&&await H.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 H.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return H.submitNPSFeedback(l,c)},destroy(){We.forEach(l=>l()),z.remove(),le==null||le.destroy(),he==null||he.remove(),rt&&q.removeEventListener("click",rt)}};if((((Gs=o==null?void 0:o.debugTools)!=null?Gs:!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,We.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return Dt};var Ls={},sa=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},oa=()=>{try{if(typeof Ls!="undefined"&&Ls.url)return new URL("../widget.css",Ls.url).href}catch{}return null},mi=e=>{let n=oa(),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)}},Ps=e=>{var u,f,p,m;let n=sa(e.target),o=document.createElement("div");o.className="persona-host";let t=(p=(f=(u=e.config)==null?void 0:u.launcher)==null?void 0:f.enabled)!=null?p:!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),mi(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),mi(o);let a=is(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 hi={name:"@runtypelabs/persona",version:"1.38.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=hi.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 ia(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 fi=`({ 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
@@ -132,7 +132,7 @@
132
132
  }`;function da(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 as(e){var n,o;return(o=(n=e.parserType)!=null?n:da(e.streamParser))!=null?o:"plain"}function ls(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 ds(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 cs(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 us(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 Hs(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 bi(e,n="esm",o){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let r=o?{...o,hooks:ia(o.hooks)}:void 0;return n==="esm"?ca(t,r):n==="script-installer"?ga(t):n==="script-advanced"?ha(t,r):n==="react-component"?ua(t,r):n==="react-advanced"?pa(t,r):ma(t,r)}function ca(e,n){let o=n==null?void 0:n.hooks,t=as(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(...ls(e," ")),s.push(...ds(e," ",o)),s.push(...cs(e," ")),s.push(...us(e," ")),s.push(...Hs(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
133
  `)}function ua(e,n){let o=n==null?void 0:n.hooks,t=as(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(...ls(e," ")),s.push(...ds(e," ",o)),s.push(...cs(e," ")),s.push(...us(e," ")),s.push(...Hs(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
134
  `)}function pa(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(...ls(e," ")),t.push(...ds(e," ",o)),t.push(...cs(e," ")),t.push(...us(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(${aa}),`)),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(` ${fi}`),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(` ${fi}`),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(` ${yi}`),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(` ${yi}`),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 Ci(e){var r;let n=as(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 ga(e){let n=Ci(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 ma(e,n){let o=n==null?void 0:n.hooks,t=as(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(...ls(e," ")),s.push(...ds(e," ",o)),s.push(...cs(e," ")),s.push(...us(e," ")),s.push(...Hs(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(`
135
+ `)}function Ci(e){var r;let n=as(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,p])=>{f!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(u[f]=p)}),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 ga(e){let n=Ci(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 ma(e,n){let o=n==null?void 0:n.hooks,t=as(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(...ls(e," ")),s.push(...ds(e," ",o)),s.push(...cs(e," ")),s.push(...us(e," ")),s.push(...Hs(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
136
  `)}function ha(e,n){let o=n==null?void 0:n.hooks,t=Ci(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
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(${la});`),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(` ${wi}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${wi}`),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(` ${vi}`),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(` ${vi}`),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(`