@runtypelabs/persona 1.43.6 → 1.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var fa=Object.create;var ws=Object.defineProperty;var wa=Object.getOwnPropertyDescriptor;var va=Object.getOwnPropertyNames;var ya=Object.getPrototypeOf,ba=Object.prototype.hasOwnProperty;var Ca=(e,n)=>{for(var r in n)ws(e,r,{get:n[r],enumerable:!0})},yi=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of va(n))!ba.call(e,o)&&o!==r&&ws(e,o,{get:()=>n[o],enumerable:!(t=wa(n,o))||t.enumerable});return e};var xa=(e,n,r)=>(r=e!=null?fa(ya(e)):{},yi(n||!e||!e.__esModule?ws(r,"default",{value:e,enumerable:!0}):r,e)),Sa=e=>yi(ws({},"__esModule",{value:!0}),e);var Sl={};Ca(Sl,{AgentWidgetClient:()=>hn,AgentWidgetSession:()=>kn,AttachmentManager:()=>wn,DEFAULT_DARK_THEME:()=>lr,DEFAULT_LIGHT_THEME:()=>ar,DEFAULT_WIDGET_CONFIG:()=>rt,VERSION:()=>Cn,attachHeaderToContainer:()=>vn,buildComposer:()=>Wn,buildDefaultHeader:()=>Xs,buildExpandedHeader:()=>Qs,buildHeader:()=>tn,buildHeaderWithLayout:()=>Ln,buildMinimalHeader:()=>Gs,componentRegistry:()=>Rn,createActionManager:()=>os,createAgentExperience:()=>Os,createBubbleWithLayout:()=>Yi,createCSATFeedback:()=>Fs,createComponentMiddleware:()=>sa,createComponentStreamParser:()=>Ps,createDirectivePostprocessor:()=>Ai,createFlexibleJsonStreamParser:()=>ki,createImagePart:()=>Ri,createJsonStreamParser:()=>Ss,createLocalStorageAdapter:()=>Is,createMarkdownProcessor:()=>Qn,createMarkdownProcessorFromConfig:()=>Zn,createMessageActions:()=>tr,createNPSFeedback:()=>$s,createPlainTextParser:()=>Cs,createRegexJsonParser:()=>xs,createStandardBubble:()=>In,createTextPart:()=>Es,createTypingIndicator:()=>yn,createXmlParser:()=>As,default:()=>xl,defaultActionHandlers:()=>bn,defaultJsonActionParser:()=>rs,directivePostprocessor:()=>Ei,escapeHtml:()=>vs,extractComponentDirectiveFromMessage:()=>Rs,fileToImagePart:()=>Fi,generateAssistantMessageId:()=>fn,generateCodeSnippet:()=>pa,generateMessageId:()=>Wi,generateUserMessageId:()=>Mn,getDisplayText:()=>Pi,getHeaderLayout:()=>Zs,getImageParts:()=>Bi,hasComponentDirective:()=>Bs,hasImages:()=>Hi,headerLayouts:()=>Ls,initAgentWidget:()=>gr,isComponentDirectiveType:()=>na,markdownPostprocessor:()=>Js,mergeWithDefaults:()=>Ws,normalizeContent:()=>Ii,pluginRegistry:()=>ss,renderComponentDirective:()=>Hs,renderLoadingIndicatorWithFallback:()=>er,validateImageFile:()=>$i});module.exports=Sa(Sl);var Ci=require("marked"),Aa=e=>{if(e)return e},Qn=e=>{var o,s;let n=e==null?void 0:e.markedOptions,r=new Ci.Marked({gfm:(o=n==null?void 0:n.gfm)!=null?o:!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=Aa(e==null?void 0:e.renderer);return t&&r.use({renderer:t}),i=>r.parse(i)},Zn=e=>e?Qn({markedOptions:e.options,renderer:e.renderer}):Qn(),Ea=Qn(),Js=e=>Ea(e),vs=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),xi=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),bi=e=>`%%FORM_PLACEHOLDER_${e}%%`,Si=(e,n)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=bi(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=bi(n.length);return n.push({token:s,type:o}),s}),r},Ai=e=>{let n=Zn(e);return r=>{let t=[],o=Si(r,t),s=n(o);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),w=`<div class="tvw-form-directive" data-tv-form="${xi(a)}"></div>`;s=s.replace(d,w)}),s}},Ei=e=>{let n=[],r=Si(e,n),t=Js(r);return n.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${xi(s)}"></div>`;t=t.replace(i,d)}),t};var en=require("partial-json"),ys=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ks=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)}},Ta=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),r=(a=e.startedAt)!=null?a:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Ti=e=>e.status==="complete"?Ta(e):e.status==="pending"?"Waiting":"",Ma=e=>{var o,s,i;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((i=(s=e.startedAt)!=null?s:e.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Mi=e=>e.status==="complete"?Ma(e):"Using tool...",ka=()=>{let e=null,n=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1
+ "use strict";var fa=Object.create;var Ts=Object.defineProperty;var wa=Object.getOwnPropertyDescriptor;var va=Object.getOwnPropertyNames;var ya=Object.getPrototypeOf,ba=Object.prototype.hasOwnProperty;var Ca=(e,n)=>{for(var r in n)Ts(e,r,{get:n[r],enumerable:!0})},yi=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of va(n))!ba.call(e,o)&&o!==r&&Ts(e,o,{get:()=>n[o],enumerable:!(t=wa(n,o))||t.enumerable});return e};var xa=(e,n,r)=>(r=e!=null?fa(ya(e)):{},yi(n||!e||!e.__esModule?Ts(r,"default",{value:e,enumerable:!0}):r,e)),Sa=e=>yi(Ts({},"__esModule",{value:!0}),e);var Sl={};Ca(Sl,{AgentWidgetClient:()=>yn,AgentWidgetSession:()=>Hn,AttachmentManager:()=>Cn,DEFAULT_DARK_THEME:()=>wr,DEFAULT_LIGHT_THEME:()=>fr,DEFAULT_WIDGET_CONFIG:()=>et,VERSION:()=>En,attachHeaderToContainer:()=>xn,buildComposer:()=>Rn,buildDefaultHeader:()=>or,buildExpandedHeader:()=>ar,buildHeader:()=>rn,buildHeaderWithLayout:()=>Bn,buildMinimalHeader:()=>ir,componentRegistry:()=>Dn,createActionManager:()=>us,createAgentExperience:()=>Ks,createBubbleWithLayout:()=>Yi,createCSATFeedback:()=>Us,createComponentMiddleware:()=>sa,createComponentStreamParser:()=>js,createDirectivePostprocessor:()=>Ai,createFlexibleJsonStreamParser:()=>Li,createImagePart:()=>Ri,createJsonStreamParser:()=>Ps,createLocalStorageAdapter:()=>Ds,createMarkdownProcessor:()=>rs,createMarkdownProcessorFromConfig:()=>os,createMessageActions:()=>cr,createNPSFeedback:()=>Js,createPlainTextParser:()=>Ws,createRegexJsonParser:()=>Is,createStandardBubble:()=>Fn,createTextPart:()=>Bs,createTypingIndicator:()=>Sn,createXmlParser:()=>Hs,default:()=>xl,defaultActionHandlers:()=>An,defaultJsonActionParser:()=>cs,directivePostprocessor:()=>Ei,escapeHtml:()=>Ms,extractComponentDirectiveFromMessage:()=>zs,fileToImagePart:()=>Fi,generateAssistantMessageId:()=>bn,generateCodeSnippet:()=>pa,generateMessageId:()=>Wi,generateUserMessageId:()=>Pn,getDisplayText:()=>Pi,getHeaderLayout:()=>lr,getImageParts:()=>Bi,hasComponentDirective:()=>qs,hasImages:()=>Hi,headerLayouts:()=>Os,initAgentWidget:()=>xr,isComponentDirectiveType:()=>na,markdownPostprocessor:()=>tr,mergeWithDefaults:()=>Ns,normalizeContent:()=>Ii,pluginRegistry:()=>ds,renderComponentDirective:()=>_s,renderLoadingIndicatorWithFallback:()=>dr,validateImageFile:()=>$i});module.exports=Sa(Sl);var Ci=require("marked"),Aa=e=>{if(e)return e},rs=e=>{var o,s;let n=e==null?void 0:e.markedOptions,r=new Ci.Marked({gfm:(o=n==null?void 0:n.gfm)!=null?o:!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=Aa(e==null?void 0:e.renderer);return t&&r.use({renderer:t}),i=>r.parse(i)},os=e=>e?rs({markedOptions:e.options,renderer:e.renderer}):rs(),Ea=rs(),tr=e=>Ea(e),Ms=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),xi=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),bi=e=>`%%FORM_PLACEHOLDER_${e}%%`,Si=(e,n)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=bi(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=bi(n.length);return n.push({token:s,type:o}),s}),r},Ai=e=>{let n=os(e);return r=>{let t=[],o=Si(r,t),s=n(o);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),w=`<div class="tvw-form-directive" data-tv-form="${xi(a)}"></div>`;s=s.replace(d,w)}),s}},Ei=e=>{let n=[],r=Si(e,n),t=tr(r);return n.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${xi(s)}"></div>`;t=t.replace(i,d)}),t};var sn=require("partial-json"),Ls=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),nr=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)}},Ta=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),r=(a=e.startedAt)!=null?a:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Ti=e=>e.status==="complete"?Ta(e):e.status==="pending"?"Waiting":"",Ma=e=>{var o,s,i;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((i=(s=e.startedAt)!=null?s:e.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Mi=e=>e.status==="complete"?Ma(e):"Using tool...",La=()=>{let e=null,n=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(o);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 o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},bs=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Cs=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},xs=()=>{var n;let e=ka();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Ss=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=(0,en.parse)(r,en.STR|en.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?ys(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=ys(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},ki=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?ys(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?ys(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<=r)return n!==null?{text:n,raw:s}:null;try{let a=(0,en.parse)(s,en.STR|en.OBJ),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},As=()=>{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 La="https://api.runtype.com/v1/dispatch",Li="https://api.runtype.com",Ys=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 Wa(e){switch(e){case"json":return Ss;case"regex-json":return xs;case"xml":return As;case"plain":default:return Cs}}var hn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,t,o;this.apiUrl=(r=n.apiUrl)!=null?r:La,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Wa(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var t;let r=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Li;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;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,(r=(n=this.config).onSessionInit)==null||r.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,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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 o=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Li}/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.messageId)throw new Error(`messageId 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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.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,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"nps",rating:n,comment:r})}async dispatch(n,r){return this.isAgentMode()?this.dispatchAgent(n,r):this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let f=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:f}),f}let g=await this.buildPayload(n.messages),w=g.metadata?Object.fromEntries(Object.entries(g.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,c={sessionId:d.sessionId,messages:n.messages.filter(Ys).map(f=>{var x,C,T;return{id:f.id,role:f.role,content:(T=(C=(x=f.contentParts)!=null?x:f.llmContent)!=null?C:f.rawContent)!=null?T:f.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...w&&Object.keys(w).length>0&&{metadata:w},...g.context&&{context:g.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c),signal:t.signal});if(!m.ok){let f=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 C=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:C}),C}if(m.status===429){let C=new Error(f.hint||"Message limit reached for this session.");throw r({type:"error",error:C}),C}let x=new Error(f.error||"Failed to send message");throw r({type:"error",error:x}),x}if(!m.body){let f=new Error("No response body received");throw r({type:"error",error:f}),f}r({type:"status",status:"connected"});try{await this.streamResponse(m.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let g=d instanceof Error?d:new Error(String(d));throw!g.message.includes("Session expired")&&!g.message.includes("Message limit")&&r({type:"error",error:g}),g}}async dispatchProxy(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);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(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);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(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(Ys).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),t={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}return t}async buildPayload(n){let t={messages:n.slice().filter(Ys).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(n,r,t,o,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,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,t){var ce,Ue,dt,At,Ft,Re,Se,ee,ue,Fe,Qe,St,pe,J,pt,gt,ft,$t,wt,Y,Le,vt,yt,Q,$e,bt,Lt,Et,j,Ze,ke,z,R,ge,de,te,Te,Oe,q,ae,He,Je,it,xn,at,Ut,On,sn,Jt,F,rn,Vt,ln,Nn,Xt,Gt,Sn,An,is,as,ls,Dn,En,Ke,jn,_n,Qt,ds,cs,qn,dn,Zt,us,ps,gs,zs,cn,un,ot,Tn,zn,Un,Jn,Pt,Ot;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,g=()=>a+d++,w=B=>{let we=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,De=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,et=B.tools?B.tools.map(Ye=>({...Ye,chunks:Ye.chunks?[...Ye.chunks]:void 0})):void 0;return{...B,reasoning:we,toolCall:De,tools:et}},c=B=>{r({type:"message",message:w(B)})},m=null,f={current:null},x=new Map,C=new Map,T={lastId:null,byStep:new Map},A={lastId:null,byCall:new Map},L=B=>{if(B==null)return null;try{return String(B)}catch{return null}},V=B=>{var we,De,et,Ye,Tt;return L((Tt=(Ye=(et=(De=(we=B.stepId)!=null?we:B.step_id)!=null?De:B.step)!=null?et:B.parentId)!=null?Ye:B.flowStepId)!=null?Tt:B.flow_step_id)},v=B=>{var we,De,et,Ye,Tt,tt,y;return L((y=(tt=(Tt=(Ye=(et=(De=(we=B.callId)!=null?we:B.call_id)!=null?De:B.requestId)!=null?et:B.request_id)!=null?Ye:B.toolCallId)!=null?Tt:B.tool_call_id)!=null?tt:B.stepId)!=null?y:B.step_id)},O=()=>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:g()},c(m),m),W=(B,we)=>{T.lastId=we,B&&T.byStep.set(B,we)},P=(B,we)=>{var Tt;let De=(Tt=B.reasoningId)!=null?Tt:B.id,et=V(B);if(De){let tt=String(De);return W(et,tt),tt}if(et){let tt=T.byStep.get(et);if(tt)return T.lastId=tt,tt}if(T.lastId&&!we)return T.lastId;if(!we)return null;let Ye=`reason-${g()}`;return W(et,Ye),Ye},se=B=>{let we=x.get(B);if(we)return we;let De={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:B,status:"streaming",chunks:[]}};return x.set(B,De),c(De),De},_=(B,we)=>{A.lastId=we,B&&A.byCall.set(B,we)},oe=(B,we)=>{var Tt;let De=(Tt=B.toolId)!=null?Tt:B.id,et=v(B);if(De){let tt=String(De);return _(et,tt),tt}if(et){let tt=A.byCall.get(et);if(tt)return A.lastId=tt,tt}if(A.lastId&&!we)return A.lastId;if(!we)return null;let Ye=`tool-${g()}`;return _(et,Ye),Ye},X=B=>{let we=C.get(B);if(we)return we;let De={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:B,status:"pending"}};return C.set(B,De),c(De),De},U=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let we=Number(B);if(!Number.isNaN(we)&&Number.isFinite(we))return we;let De=Date.parse(B);if(!Number.isNaN(De))return De}return Date.now()},xe=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},N=new Map,ne=new Map,D=null,Z=new Map,fe=(ce=this.config.iterationDisplay)!=null?ce:"separate";for(;;){let{done:B,value:we}=await o.read();if(B)break;i+=s.decode(we,{stream:!0});let De=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 o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},ks=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ws=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Is=()=>{var n;let e=La();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Ps=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=(0,sn.parse)(r,sn.STR|sn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Ls(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Ls(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Li=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Ls(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ls(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<=r)return n!==null?{text:n,raw:s}:null;try{let a=(0,sn.parse)(s,sn.STR|sn.OBJ),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Hs=()=>{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 ka="https://api.runtype.com/v1/dispatch",ki="https://api.runtype.com",sr=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 Wa(e){switch(e){case"json":return Ps;case"regex-json":return Is;case"xml":return Hs;case"plain":default:return Ws}}var yn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,t,o;this.apiUrl=(r=n.apiUrl)!=null?r:ka,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Wa(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var t;let r=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;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,(r=(n=this.config).onSessionInit)==null||r.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,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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 o=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/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.messageId)throw new Error(`messageId 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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.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,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"nps",rating:n,comment:r})}async dispatch(n,r){return this.isAgentMode()?this.dispatchAgent(n,r):this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let f=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:f}),f}let g=await this.buildPayload(n.messages),w=g.metadata?Object.fromEntries(Object.entries(g.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,c={sessionId:d.sessionId,messages:n.messages.filter(sr).map(f=>{var x,C,E;return{id:f.id,role:f.role,content:(E=(C=(x=f.contentParts)!=null?x:f.llmContent)!=null?C:f.rawContent)!=null?E:f.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...w&&Object.keys(w).length>0&&{metadata:w},...g.context&&{context:g.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c);let h=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c),signal:t.signal});if(!h.ok){let f=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let C=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:C}),C}if(h.status===429){let C=new Error(f.hint||"Message limit reached for this session.");throw r({type:"error",error:C}),C}let x=new Error(f.error||"Failed to send message");throw r({type:"error",error:x}),x}if(!h.body){let f=new Error("No response body received");throw r({type:"error",error:f}),f}r({type:"status",status:"connected"});try{await this.streamResponse(h.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let g=d instanceof Error?d:new Error(String(d));throw!g.message.includes("Session expired")&&!g.message.includes("Message limit")&&r({type:"error",error:g}),g}}async dispatchProxy(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);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(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);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(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(sr).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),t={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}return t}async buildPayload(n){let t={messages:n.slice().filter(sr).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(n,r,t,o,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,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,t){var pe,Ue,it,Tt,$t,Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt,Q,Oe,bt,Wt,Mt,j,Ze,We,z,R,he,ue,te,Le,Ne,q,de,Be,Je,st,Tn,rt,Jt,qn,an,Kt,F,ln,Gt,un,zn,Qt,Zt,Mn,Ln,ps,gs,ms,Un,kn,Ke,Jn,Kn,en,hs,fs,Yn,pn,tn,ws,vs,ys,Zs,gn,mn,tt,Wn,Vn,Xn,Gn,Ht,Nt,nn,Yt,Qn,hn,qt,bs,In,Cs,xs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,g=()=>a+d++,w=B=>{let ne=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,ae=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Xe=B.tools?B.tools.map(pt=>({...pt,chunks:pt.chunks?[...pt.chunks]:void 0})):void 0;return{...B,reasoning:ne,toolCall:ae,tools:Xe}},c=B=>{r({type:"message",message:w(B)})},h=null,f={current:null},x=new Map,C=new Map,E={lastId:null,byStep:new Map},S={lastId:null,byCall:new Map},k=B=>{if(B==null)return null;try{return String(B)}catch{return null}},V=B=>{var ne,ae,Xe,pt,Et;return k((Et=(pt=(Xe=(ae=(ne=B.stepId)!=null?ne:B.step_id)!=null?ae:B.step)!=null?Xe:B.parentId)!=null?pt:B.flowStepId)!=null?Et:B.flow_step_id)},y=B=>{var ne,ae,Xe,pt,Et,at,m;return k((m=(at=(Et=(pt=(Xe=(ae=(ne=B.callId)!=null?ne:B.call_id)!=null?ae:B.requestId)!=null?Xe:B.request_id)!=null?pt:B.toolCallId)!=null?Et:B.tool_call_id)!=null?at:B.stepId)!=null?m:B.step_id)},O=()=>h||(h={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g()},c(h),h),W=(B,ne)=>{E.lastId=ne,B&&E.byStep.set(B,ne)},H=(B,ne)=>{var Et;let ae=(Et=B.reasoningId)!=null?Et:B.id,Xe=V(B);if(ae){let at=String(ae);return W(Xe,at),at}if(Xe){let at=E.byStep.get(Xe);if(at)return E.lastId=at,at}if(E.lastId&&!ne)return E.lastId;if(!ne)return null;let pt=`reason-${g()}`;return W(Xe,pt),pt},oe=B=>{let ne=x.get(B);if(ne)return ne;let ae={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:B,status:"streaming",chunks:[]}};return x.set(B,ae),c(ae),ae},_=(B,ne)=>{S.lastId=ne,B&&S.byCall.set(B,ne)},le=(B,ne)=>{var Et;let ae=(Et=B.toolId)!=null?Et:B.id,Xe=y(B);if(ae){let at=String(ae);return _(Xe,at),at}if(Xe){let at=S.byCall.get(Xe);if(at)return S.lastId=at,at}if(S.lastId&&!ne)return S.lastId;if(!ne)return null;let pt=`tool-${g()}`;return _(Xe,pt),pt},X=B=>{let ne=C.get(B);if(ne)return ne;let ae={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:B,status:"pending"}};return C.set(B,ae),c(ae),ae},U=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let ne=Number(B);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let ae=Date.parse(B);if(!Number.isNaN(ae))return ae}return Date.now()},Se=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},N=new Map,re=new Map,D=null,Z=new Map,ve=(pe=this.config.iterationDisplay)!=null?pe:"separate";for(;;){let{done:B,value:ne}=await o.read();if(B)break;i+=s.decode(ne,{stream:!0});let ae=i.split(`
5
5
 
6
- `);i=(Ue=De.pop())!=null?Ue:"";for(let et of De){let Ye=et.split(`
7
- `),Tt="message",tt="";for(let H of Ye)H.startsWith("event:")?Tt=H.replace("event:","").trim():H.startsWith("data:")&&(tt+=H.replace("data:","").trim());if(!tt)continue;let y;try{y=JSON.parse(tt)}catch(H){r({type:"error",error:H instanceof Error?H:new Error("Failed to parse chat stream payload")});continue}let Ve=Tt!=="message"?Tt:(dt=y.type)!=null?dt:"message";if((At=this.onSSEEvent)==null||At.call(this,Ve,y),this.parseSSEEvent){f.current=m;let H=await this.handleCustomSSEEvent(y,r,f,c,g);if(f.current&&!m&&(m=f.current),H)continue}if(Ve==="reason_start"){let H=(Ft=P(y,!0))!=null?Ft:`reason-${g()}`,h=se(H);h.reasoning=(Re=h.reasoning)!=null?Re:{id:H,status:"streaming",chunks:[]},h.reasoning.startedAt=(ee=h.reasoning.startedAt)!=null?ee:U((Se=y.startedAt)!=null?Se:y.timestamp),h.reasoning.completedAt=void 0,h.reasoning.durationMs=void 0,h.streaming=!0,h.reasoning.status="streaming",c(h)}else if(Ve==="reason_chunk"){let H=(Fe=(ue=P(y,!1))!=null?ue:P(y,!0))!=null?Fe:`reason-${g()}`,h=se(H);h.reasoning=(Qe=h.reasoning)!=null?Qe:{id:H,status:"streaming",chunks:[]},h.reasoning.startedAt=(pe=h.reasoning.startedAt)!=null?pe:U((St=y.startedAt)!=null?St:y.timestamp);let S=(gt=(pt=(J=y.reasoningText)!=null?J:y.text)!=null?pt:y.delta)!=null?gt:"";if(S&&y.hidden!==!0&&h.reasoning.chunks.push(String(S)),h.reasoning.status=y.done?"complete":"streaming",y.done){h.reasoning.completedAt=U((ft=y.completedAt)!=null?ft:y.timestamp);let ie=($t=h.reasoning.startedAt)!=null?$t:Date.now();h.reasoning.durationMs=Math.max(0,((wt=h.reasoning.completedAt)!=null?wt:Date.now())-ie)}h.streaming=h.reasoning.status!=="complete",c(h)}else if(Ve==="reason_complete"){let H=(Le=(Y=P(y,!1))!=null?Y:P(y,!0))!=null?Le:`reason-${g()}`,h=x.get(H);if(h!=null&&h.reasoning){h.reasoning.status="complete",h.reasoning.completedAt=U((vt=y.completedAt)!=null?vt:y.timestamp);let ie=(yt=h.reasoning.startedAt)!=null?yt:Date.now();h.reasoning.durationMs=Math.max(0,((Q=h.reasoning.completedAt)!=null?Q:Date.now())-ie),h.streaming=!1,c(h)}let S=V(y);S&&T.byStep.delete(S)}else if(Ve==="tool_start"){let H=($e=oe(y,!0))!=null?$e:`tool-${g()}`,h=X(H),S=(bt=h.toolCall)!=null?bt:{id:H,status:"pending"};S.name=(Lt=y.toolName)!=null?Lt:S.name,S.status="running",y.args!==void 0&&(S.args=y.args),S.startedAt=(j=S.startedAt)!=null?j:U((Et=y.startedAt)!=null?Et:y.timestamp),S.completedAt=void 0,S.durationMs=void 0,h.toolCall=S,h.streaming=!0,c(h)}else if(Ve==="tool_chunk"){let H=(ke=(Ze=oe(y,!1))!=null?Ze:oe(y,!0))!=null?ke:`tool-${g()}`,h=X(H),S=(z=h.toolCall)!=null?z:{id:H,status:"running"};S.startedAt=(ge=S.startedAt)!=null?ge:U((R=y.startedAt)!=null?R:y.timestamp);let ie=(Te=(te=(de=y.text)!=null?de:y.delta)!=null?te:y.message)!=null?Te:"";ie&&(S.chunks=(Oe=S.chunks)!=null?Oe:[],S.chunks.push(String(ie))),S.status="running",h.toolCall=S,h.streaming=!0,c(h)}else if(Ve==="tool_complete"){let H=(ae=(q=oe(y,!1))!=null?q:oe(y,!0))!=null?ae:`tool-${g()}`,h=X(H),S=(He=h.toolCall)!=null?He:{id:H,status:"running"};if(S.status="complete",y.result!==void 0&&(S.result=y.result),typeof y.duration=="number"&&(S.duration=y.duration),S.completedAt=U((Je=y.completedAt)!=null?Je:y.timestamp),typeof y.duration=="number")S.durationMs=y.duration;else{let nt=(it=S.startedAt)!=null?it:Date.now();S.durationMs=Math.max(0,((xn=S.completedAt)!=null?xn:Date.now())-nt)}h.toolCall=S,h.streaming=!1,c(h);let ie=v(y);ie&&A.byCall.delete(ie)}else if(Ve==="step_chunk"){let H=y.stepType,h=y.executionType;if(H==="tool"||h==="context")continue;let S=O(),ie=(sn=(On=(Ut=(at=y.text)!=null?at:y.delta)!=null?Ut:y.content)!=null?On:y.chunk)!=null?sn:"";if(ie){let st=((Jt=ne.get(S.id))!=null?Jt:"")+ie;S.rawContent=st,N.has(S.id)||N.set(S.id,this.createStreamParser());let Nt=N.get(S.id),We=st.trim().startsWith("{")||st.trim().startsWith("[");if(We&&ne.set(S.id,st),Nt.__isPlainTextParser===!0){S.content+=ie,ne.delete(S.id),N.delete(S.id),S.rawContent=void 0,c(S);continue}let je=Nt.processChunk(st);if(je instanceof Promise)je.then(Ne=>{var ct;let qe=typeof Ne=="string"?Ne:(ct=Ne==null?void 0:Ne.text)!=null?ct:null;if(qe!==null&&qe.trim()!==""){let ze=m;ze&&ze.id===S.id&&(ze.content=qe,c(ze))}else if(!We&&!st.trim().startsWith("<")){let ze=m;ze&&ze.id===S.id&&(ze.content+=ie,ne.delete(ze.id),N.delete(ze.id),ze.rawContent=void 0,c(ze))}}).catch(()=>{S.content+=ie,ne.delete(S.id),N.delete(S.id),S.rawContent=void 0,c(S)});else{let Ne=typeof je=="string"?je:(F=je==null?void 0:je.text)!=null?F:null;Ne!==null&&Ne.trim()!==""?(S.content=Ne,c(S)):!We&&!st.trim().startsWith("<")&&(S.content+=ie,ne.delete(S.id),N.delete(S.id),S.rawContent=void 0,c(S))}}if(y.isComplete){let nt=(Vt=(rn=y.result)==null?void 0:rn.response)!=null?Vt:S.content;if(nt){let st=ne.get(S.id),Nt=st!=null?st:xe(nt);S.rawContent=Nt;let We=N.get(S.id),Mt=null,je=!1;if(We&&(Mt=We.getExtractedText(),Mt===null&&(Mt=bs(Nt)),Mt===null)){let Ne=We.processChunk(Nt);Ne instanceof Promise?(je=!0,Ne.then(qe=>{var ze;let ct=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(ct!==null){let Ct=m;Ct&&Ct.id===S.id&&(Ct.content=ct,Ct.streaming=!1,N.delete(Ct.id),ne.delete(Ct.id),c(Ct))}})):Mt=typeof Ne=="string"?Ne:(ln=Ne==null?void 0:Ne.text)!=null?ln:null}if(!je){Mt!==null&&Mt.trim()!==""?S.content=Mt:ne.has(S.id)||(S.content=xe(nt));let Ne=N.get(S.id);if(Ne){let qe=(Nn=Ne.close)==null?void 0:Nn.call(Ne);qe instanceof Promise&&qe.catch(()=>{}),N.delete(S.id)}ne.delete(S.id),S.streaming=!1,c(S)}}}}else if(Ve==="step_complete"){let H=y.stepType,h=y.executionType;if(H==="tool"||h==="context")continue;let S=(Xt=y.result)==null?void 0:Xt.response,ie=O();if(S!=null){let nt=N.get(ie.id),st=!1,Nt=!1;if(nt){let We=nt.getExtractedText(),Mt=ne.get(ie.id),je=Mt!=null?Mt:xe(S);if(ie.rawContent=je,We!==null&&We.trim()!=="")ie.content=We,st=!0;else{let Ne=bs(je);if(Ne!==null)ie.content=Ne,st=!0;else{let qe=nt.processChunk(je);if(qe instanceof Promise)Nt=!0,qe.then(ct=>{var Ct;let ze=typeof ct=="string"?ct:(Ct=ct==null?void 0:ct.text)!=null?Ct:null;if(ze!==null&&ze.trim()!==""){let Bt=m;Bt&&Bt.id===ie.id&&(Bt.content=ze,Bt.streaming=!1,N.delete(Bt.id),ne.delete(Bt.id),c(Bt))}else{let Bt=nt.getExtractedText(),_t=m;_t&&_t.id===ie.id&&(Bt!==null&&Bt.trim()!==""?_t.content=Bt:ne.has(_t.id)||(_t.content=xe(S)),_t.streaming=!1,N.delete(_t.id),ne.delete(_t.id),c(_t))}});else{let ct=typeof qe=="string"?qe:(Gt=qe==null?void 0:qe.text)!=null?Gt:null;if(ct!==null&&ct.trim()!=="")ie.content=ct,st=!0;else{let ze=nt.getExtractedText();ze!==null&&ze.trim()!==""&&(ie.content=ze,st=!0)}}}}}if(!Nt){if(!ie.rawContent){let We=ne.get(ie.id);ie.rawContent=We!=null?We:xe(S)}if(!st&&!ne.has(ie.id)&&(ie.content=xe(S)),nt){let We=(Sn=nt.close)==null?void 0:Sn.call(nt);We instanceof Promise&&We.catch(()=>{})}N.delete(ie.id),ne.delete(ie.id),ie.streaming=!1,c(ie)}}else N.delete(ie.id),ne.delete(ie.id),ie.streaming=!1,c(ie)}else if(Ve==="flow_complete"){let H=(An=y.result)==null?void 0:An.response;if(H!=null){let h=O(),S=ne.get(h.id),ie=S!=null?S:xe(H);h.rawContent=ie;let nt=xe(H),st=N.get(h.id);if(st){let Mt=bs(ie);if(Mt!==null)nt=Mt;else{let je=st.processChunk(ie);je instanceof Promise&&je.then(qe=>{var ze;let ct=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(ct!==null){let Ct=m;Ct&&Ct.id===h.id&&(Ct.content=ct,Ct.streaming=!1,c(Ct))}});let Ne=st.getExtractedText();Ne!==null&&(nt=Ne)}}N.delete(h.id),ne.delete(h.id);let Nt=nt!==h.content,We=h.streaming!==!1;Nt&&(h.content=nt),h.streaming=!1,(Nt||We)&&c(h)}else if(m!==null){let h=m;N.delete(h.id),ne.delete(h.id),h.streaming!==!1&&(h.streaming=!1,c(h))}r({type:"status",status:"idle"})}else if(Ve==="agent_start")D={executionId:y.executionId,agentId:(is=y.agentId)!=null?is:"virtual",agentName:(as=y.agentName)!=null?as:"",status:"running",currentIteration:0,maxIterations:(ls=y.maxIterations)!=null?ls:1,startedAt:U(y.startedAt)};else if(Ve==="agent_iteration_start"){if(D&&(D.currentIteration=y.iteration),fe==="separate"&&y.iteration>1){let H=m;H&&(H.streaming=!1,c(H),Z.set(y.iteration-1,H),m=null)}}else if(Ve!=="agent_turn_start"){if(Ve==="agent_turn_delta"){if(y.contentType==="text"){let H=O();H.content+=(Dn=y.delta)!=null?Dn:"",H.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId,agentName:D==null?void 0:D.agentName},c(H)}else if(y.contentType==="thinking"){let H=(En=y.turnId)!=null?En:`agent-think-${y.iteration}`,h=se(H);h.reasoning=(Ke=h.reasoning)!=null?Ke:{id:H,status:"streaming",chunks:[]},h.reasoning.chunks.push((jn=y.delta)!=null?jn:""),h.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId},c(h)}else if(y.contentType==="tool_input"){let H=(_n=y.toolCallId)!=null?_n:A.lastId;if(H){let h=C.get(H);h!=null&&h.toolCall&&(h.toolCall.chunks=(Qt=h.toolCall.chunks)!=null?Qt:[],h.toolCall.chunks.push((ds=y.delta)!=null?ds:""),c(h))}}}else if(Ve==="agent_turn_complete"){let H=y.turnId;if(H){let h=x.get(H);if(h!=null&&h.reasoning){h.reasoning.status="complete",h.reasoning.completedAt=U(y.completedAt);let S=(cs=h.reasoning.startedAt)!=null?cs:Date.now();h.reasoning.durationMs=Math.max(0,((qn=h.reasoning.completedAt)!=null?qn:Date.now())-S),h.streaming=!1,c(h)}}}else if(Ve==="agent_tool_start"){let H=(dn=y.toolCallId)!=null?dn:`agent-tool-${g()}`;_(v(y),H);let h=X(H),S=(Zt=h.toolCall)!=null?Zt:{id:H,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};S.name=(us=y.toolName)!=null?us:S.name,S.status="running",y.parameters!==void 0&&(S.args=y.parameters),S.startedAt=U((ps=y.startedAt)!=null?ps:y.timestamp),h.toolCall=S,h.streaming=!0,h.agentMetadata={executionId:y.executionId,iteration:y.iteration},c(h)}else if(Ve==="agent_tool_delta"){let H=(gs=y.toolCallId)!=null?gs:A.lastId;if(H){let h=(zs=C.get(H))!=null?zs:X(H);h.toolCall&&(h.toolCall.chunks=(cn=h.toolCall.chunks)!=null?cn:[],h.toolCall.chunks.push((un=y.delta)!=null?un:""),h.toolCall.status="running",h.streaming=!0,c(h))}}else if(Ve==="agent_tool_complete"){let H=(ot=y.toolCallId)!=null?ot:A.lastId;if(H){let h=(Tn=C.get(H))!=null?Tn:X(H);if(h.toolCall){h.toolCall.status="complete",y.result!==void 0&&(h.toolCall.result=y.result),typeof y.executionTime=="number"&&(h.toolCall.durationMs=y.executionTime),h.toolCall.completedAt=U((zn=y.completedAt)!=null?zn:y.timestamp),h.streaming=!1,c(h);let S=v(y);S&&A.byCall.delete(S)}}}else if(Ve!=="agent_iteration_complete")if(Ve==="agent_reflection"){let H=`agent-reflection-${y.executionId}-${y.iteration}`,h={id:H,role:"assistant",content:(Un=y.reflection)!=null?Un:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:g(),reasoning:{id:H,status:"complete",chunks:[(Jn=y.reflection)!=null?Jn:""]},agentMetadata:{executionId:y.executionId,iteration:y.iteration}};c(h)}else if(Ve==="agent_complete"){D&&(D.status=y.success?"complete":"error",D.completedAt=U(y.completedAt),D.stopReason=y.stopReason);let H=m;H&&(H.streaming=!1,c(H)),r({type:"status",status:"idle"})}else if(Ve==="agent_error"){let H=typeof y.error=="string"?y.error:(Ot=(Pt=y.error)==null?void 0:Pt.message)!=null?Ot:"Agent execution error";y.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",H):r({type:"error",error:new Error(H)})}else Ve==="agent_ping"||Ve==="error"&&y.error&&r({type:"error",error:y.error instanceof Error?y.error:new Error(String(y.error))})}}}}};function Wi(){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 fn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var kn=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,t,o,s,i,a,d;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(t=n.message.agentMetadata.agentName)!=null?t:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):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,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new hn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(r=(n=this.callbacks).onError)==null||r.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 r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}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,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new hn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:t,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:g=!1}=n,c={id:i!=null?i:r==="user"?Mn():r==="assistant"?fn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:g,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(c),c}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let t of n){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:g,sequence:w,streaming:c=!1}=t,f={id:d!=null?d:o==="user"?Mn():o==="assistant"?fn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:g!=null?g:new Date().toISOString(),sequence:w!=null?w:this.nextSequence(),streaming:c,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(f)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var g,w,c,m,f;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(g=this.abortController)==null||g.abort();let o=Mn(),s=fn(),i={id:o,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.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(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let T={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(T)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(c=(w=this.callbacks).onError)==null||c.call(w,x):(f=(m=this.callbacks).onError)==null||f.call(m,new Error(String(x))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=fn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(g){let w={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(w),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,g):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(g)))}}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.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,t)=>{var d,g;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(g=t.sequence)!=null?g:0;return i!==a?i-a:r.id.localeCompare(t.id)})}};var p=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};var Ia=xa(require("lucide"),1),re=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ia[o];return s?Pa(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Pa(e,n,r,t){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.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(([g,w])=>{g!=="stroke"&&d.setAttribute(g,String(w))}),o.appendChild(d)}}}),o}function Ii(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pi(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Hi(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Bi(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Es(e){return{type:"text",text:e}}function Ri(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 Fi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function $i(e,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Oi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ha=["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"],an=[...Oi,...Ha];function Ba(e){return Oi.includes(e)||e.startsWith("image/")}function Ts(e){return Ba(e.type)}async function Ni(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;Ts(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function Di(e,n=an,r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ra(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function ji(e,n){let r=Ra(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]||r||"FILE"}var Ms={allowedTypes:an,maxFileSize:10*1024*1024,maxFiles:4};function Fa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $a(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 wn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,t,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Ms.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Ms.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Ms.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:Ms.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,o,s,i,a,d,g;if(!n||n.length===0)return;let r=Array.from(n);for(let w of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,w,"count");continue}let c=Di(w,this.config.allowedTypes,this.config.maxFileSize);if(!c.valid){let m=(s=c.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,w,m);continue}try{let m=await Ni(w),f=Ts(w)?URL.createObjectURL(w):null,x={id:Fa(),file:w,previewUrl:f,contentPart:m};this.attachments.push(x),this.renderPreview(x)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(g=(d=this.config).onAttachmentsChange)==null||g.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(d=>d.id===n);if(r===-1)return;let t=this.attachments[r];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=Ts(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",r&&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=$a(n.file.type),d=re(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let g=p("span");g.textContent=ji(n.file.type,n.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--cw-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",i.appendChild(g),t.appendChild(i)}let o=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=re("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(o),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){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:r})}};var Vs=()=>{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"},Oa=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",r=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||Vs()==="dark"?t:r},_i=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Vs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(Vs());r.addEventListener?(r.addEventListener("change",t),n.push(()=>r.removeEventListener("change",t))):r.addListener&&(r.addListener(t),n.push(()=>r.removeListener(t)))}return()=>{n.forEach(r=>r())}},ks=(e,n)=>{let r=Oa(n);Object.entries(r).forEach(([t,o])=>{if(o==null||o==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(o))})};var qi=require("idiomorph"),zi=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;qi.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&t&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var zt={"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 es=(e,n)=>{let r=p("button");r.type="button",r.innerHTML=`
6
+ `);i=(Ue=ae.pop())!=null?Ue:"";for(let Xe of ae){let pt=Xe.split(`
7
+ `),Et="message",at="";for(let P of pt)P.startsWith("event:")?Et=P.replace("event:","").trim():P.startsWith("data:")&&(at+=P.replace("data:","").trim());if(!at)continue;let m;try{m=JSON.parse(at)}catch(P){r({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let _e=Et!=="message"?Et:(it=m.type)!=null?it:"message";if((Tt=this.onSSEEvent)==null||Tt.call(this,_e,m),this.parseSSEEvent){f.current=h;let P=await this.handleCustomSSEEvent(m,r,f,c,g);if(f.current&&!h&&(h=f.current),P)continue}if(_e==="reason_start"){let P=($t=H(m,!0))!=null?$t:`reason-${g()}`,v=oe(P);v.reasoning=(Fe=v.reasoning)!=null?Fe:{id:P,status:"streaming",chunks:[]},v.reasoning.startedAt=(ee=v.reasoning.startedAt)!=null?ee:U((Ae=m.startedAt)!=null?Ae:m.timestamp),v.reasoning.completedAt=void 0,v.reasoning.durationMs=void 0,v.streaming=!0,v.reasoning.status="streaming",c(v)}else if(_e==="reason_chunk"||_e==="reason_delta"){let P=($e=(ge=H(m,!1))!=null?ge:H(m,!0))!=null?$e:`reason-${g()}`,v=oe(P);v.reasoning=(Qe=v.reasoning)!=null?Qe:{id:P,status:"streaming",chunks:[]},v.reasoning.startedAt=(me=v.reasoning.startedAt)!=null?me:U((At=m.startedAt)!=null?At:m.timestamp);let T=(ut=(ct=(J=m.reasoningText)!=null?J:m.text)!=null?ct:m.delta)!=null?ut:"";if(T&&m.hidden!==!0&&v.reasoning.chunks.push(String(T)),v.reasoning.status=m.done?"complete":"streaming",m.done){v.reasoning.completedAt=U((ft=m.completedAt)!=null?ft:m.timestamp);let se=(Ot=v.reasoning.startedAt)!=null?Ot:Date.now();v.reasoning.durationMs=Math.max(0,((wt=v.reasoning.completedAt)!=null?wt:Date.now())-se)}v.streaming=v.reasoning.status!=="complete",c(v)}else if(_e==="reason_complete"){let P=(Ie=(Y=H(m,!1))!=null?Y:H(m,!0))!=null?Ie:`reason-${g()}`,v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U((vt=m.completedAt)!=null?vt:m.timestamp);let se=(yt=v.reasoning.startedAt)!=null?yt:Date.now();v.reasoning.durationMs=Math.max(0,((Q=v.reasoning.completedAt)!=null?Q:Date.now())-se),v.streaming=!1,c(v)}let T=V(m);T&&E.byStep.delete(T)}else if(_e==="tool_start"){let P=(Oe=le(m,!0))!=null?Oe:`tool-${g()}`,v=X(P),T=(bt=v.toolCall)!=null?bt:{id:P,status:"pending"};T.name=(Wt=m.toolName)!=null?Wt:T.name,T.status="running",m.args!==void 0?T.args=m.args:m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=(j=T.startedAt)!=null?j:U((Mt=m.startedAt)!=null?Mt:m.timestamp),T.completedAt=void 0,T.durationMs=void 0,v.toolCall=T,v.streaming=!0;let se=m.agentContext;(se||m.executionId)&&(v.agentMetadata={executionId:(Ze=se==null?void 0:se.executionId)!=null?Ze:m.executionId,iteration:(We=se==null?void 0:se.iteration)!=null?We:m.iteration}),c(v)}else if(_e==="tool_chunk"||_e==="tool_delta"){let P=(R=(z=le(m,!1))!=null?z:le(m,!0))!=null?R:`tool-${g()}`,v=X(P),T=(he=v.toolCall)!=null?he:{id:P,status:"running"};T.startedAt=(te=T.startedAt)!=null?te:U((ue=m.startedAt)!=null?ue:m.timestamp);let se=(q=(Ne=(Le=m.text)!=null?Le:m.delta)!=null?Ne:m.message)!=null?q:"";se&&(T.chunks=(de=T.chunks)!=null?de:[],T.chunks.push(String(se))),T.status="running",v.toolCall=T,v.streaming=!0;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(st=v.agentMetadata)!=null?st:{executionId:(Be=Ee==null?void 0:Ee.executionId)!=null?Be:m.executionId,iteration:(Je=Ee==null?void 0:Ee.iteration)!=null?Je:m.iteration}),c(v)}else if(_e==="tool_complete"){let P=(rt=(Tn=le(m,!1))!=null?Tn:le(m,!0))!=null?rt:`tool-${g()}`,v=X(P),T=(Jt=v.toolCall)!=null?Jt:{id:P,status:"running"};T.status="complete",m.result!==void 0&&(T.result=m.result),typeof m.duration=="number"&&(T.duration=m.duration),T.completedAt=U((qn=m.completedAt)!=null?qn:m.timestamp);let se=(an=m.duration)!=null?an:m.executionTime;if(typeof se=="number")T.durationMs=se;else{let Lt=(Kt=T.startedAt)!=null?Kt:Date.now();T.durationMs=Math.max(0,((F=T.completedAt)!=null?F:Date.now())-Lt)}v.toolCall=T,v.streaming=!1;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(un=v.agentMetadata)!=null?un:{executionId:(ln=Ee==null?void 0:Ee.executionId)!=null?ln:m.executionId,iteration:(Gt=Ee==null?void 0:Ee.iteration)!=null?Gt:m.iteration}),c(v);let Ye=y(m);Ye&&S.byCall.delete(Ye)}else if(_e==="step_chunk"||_e==="step_delta"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=O(),se=(Mn=(Zt=(Qt=(zn=m.text)!=null?zn:m.delta)!=null?Qt:m.content)!=null?Zt:m.chunk)!=null?Mn:"";if(se){let Ye=((Ln=re.get(T.id))!=null?Ln:"")+se;T.rawContent=Ye,N.has(T.id)||N.set(T.id,this.createStreamParser());let Lt=N.get(T.id),nt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(nt&&re.set(T.id,Ye),Lt.__isPlainTextParser===!0){T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T);continue}let gt=Lt.processChunk(Ye);if(gt instanceof Promise)gt.then(De=>{var lt;let qe=typeof De=="string"?De:(lt=De==null?void 0:De.text)!=null?lt:null;if(qe!==null&&qe.trim()!==""){let ze=h;ze&&ze.id===T.id&&(ze.content=qe,c(ze))}else if(!nt&&!Ye.trim().startsWith("<")){let ze=h;ze&&ze.id===T.id&&(ze.content+=se,re.delete(ze.id),N.delete(ze.id),ze.rawContent=void 0,c(ze))}}).catch(()=>{T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T)});else{let De=typeof gt=="string"?gt:(ps=gt==null?void 0:gt.text)!=null?ps:null;De!==null&&De.trim()!==""?(T.content=De,c(T)):!nt&&!Ye.trim().startsWith("<")&&(T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T))}}if(m.isComplete){let Ee=(ms=(gs=m.result)==null?void 0:gs.response)!=null?ms:T.content;if(Ee){let Ye=re.get(T.id),Lt=Ye!=null?Ye:Se(Ee);T.rawContent=Lt;let nt=N.get(T.id),Ct=null,gt=!1;if(nt&&(Ct=nt.getExtractedText(),Ct===null&&(Ct=ks(Lt)),Ct===null)){let De=nt.processChunk(Lt);De instanceof Promise?(gt=!0,De.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===T.id&&(xt.content=lt,xt.streaming=!1,N.delete(xt.id),re.delete(xt.id),c(xt))}})):Ct=typeof De=="string"?De:(Un=De==null?void 0:De.text)!=null?Un:null}if(!gt){Ct!==null&&Ct.trim()!==""?T.content=Ct:re.has(T.id)||(T.content=Se(Ee));let De=N.get(T.id);if(De){let qe=(kn=De.close)==null?void 0:kn.call(De);qe instanceof Promise&&qe.catch(()=>{}),N.delete(T.id)}re.delete(T.id),T.streaming=!1,c(T)}}}}else if(_e==="step_complete"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=(Ke=m.result)==null?void 0:Ke.response,se=O();if(T!=null){let Ee=N.get(se.id),Ye=!1,Lt=!1;if(Ee){let nt=Ee.getExtractedText(),Ct=re.get(se.id),gt=Ct!=null?Ct:Se(T);if(se.rawContent=gt,nt!==null&&nt.trim()!=="")se.content=nt,Ye=!0;else{let De=ks(gt);if(De!==null)se.content=De,Ye=!0;else{let qe=Ee.processChunk(gt);if(qe instanceof Promise)Lt=!0,qe.then(lt=>{var xt;let ze=typeof lt=="string"?lt:(xt=lt==null?void 0:lt.text)!=null?xt:null;if(ze!==null&&ze.trim()!==""){let Rt=h;Rt&&Rt.id===se.id&&(Rt.content=ze,Rt.streaming=!1,N.delete(Rt.id),re.delete(Rt.id),c(Rt))}else{let Rt=Ee.getExtractedText(),_t=h;_t&&_t.id===se.id&&(Rt!==null&&Rt.trim()!==""?_t.content=Rt:re.has(_t.id)||(_t.content=Se(T)),_t.streaming=!1,N.delete(_t.id),re.delete(_t.id),c(_t))}});else{let lt=typeof qe=="string"?qe:(Jn=qe==null?void 0:qe.text)!=null?Jn:null;if(lt!==null&&lt.trim()!=="")se.content=lt,Ye=!0;else{let ze=Ee.getExtractedText();ze!==null&&ze.trim()!==""&&(se.content=ze,Ye=!0)}}}}}if(!Lt){if(!se.rawContent){let nt=re.get(se.id);se.rawContent=nt!=null?nt:Se(T)}if(!Ye&&!re.has(se.id)&&(se.content=Se(T)),Ee){let nt=(Kn=Ee.close)==null?void 0:Kn.call(Ee);nt instanceof Promise&&nt.catch(()=>{})}N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}}else N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}else if(_e==="flow_complete"){let P=(en=m.result)==null?void 0:en.response;if(P!=null){let v=O(),T=re.get(v.id),se=T!=null?T:Se(P);v.rawContent=se;let Ee=Se(P),Ye=N.get(v.id);if(Ye){let Ct=ks(se);if(Ct!==null)Ee=Ct;else{let gt=Ye.processChunk(se);gt instanceof Promise&&gt.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===v.id&&(xt.content=lt,xt.streaming=!1,c(xt))}});let De=Ye.getExtractedText();De!==null&&(Ee=De)}}N.delete(v.id),re.delete(v.id);let Lt=Ee!==v.content,nt=v.streaming!==!1;Lt&&(v.content=Ee),v.streaming=!1,(Lt||nt)&&c(v)}else if(h!==null){let v=h;N.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,c(v))}r({type:"status",status:"idle"})}else if(_e==="agent_start")D={executionId:m.executionId,agentId:(hs=m.agentId)!=null?hs:"virtual",agentName:(fs=m.agentName)!=null?fs:"",status:"running",currentIteration:0,maxIterations:(Yn=m.maxIterations)!=null?Yn:1,startedAt:U(m.startedAt)};else if(_e==="agent_iteration_start"){if(D&&(D.currentIteration=m.iteration),ve==="separate"&&m.iteration>1){let P=h;P&&(P.streaming=!1,c(P),Z.set(m.iteration-1,P),h=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(m.contentType==="text"){let P=O();P.content+=(pn=m.delta)!=null?pn:"",P.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:D==null?void 0:D.agentName},c(P)}else if(m.contentType==="thinking"){let P=(tn=m.turnId)!=null?tn:`agent-think-${m.iteration}`,v=oe(P);v.reasoning=(ws=v.reasoning)!=null?ws:{id:P,status:"streaming",chunks:[]},v.reasoning.chunks.push((vs=m.delta)!=null?vs:""),v.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},c(v)}else if(m.contentType==="tool_input"){let P=(ys=m.toolCallId)!=null?ys:S.lastId;if(P){let v=C.get(P);v!=null&&v.toolCall&&(v.toolCall.chunks=(Zs=v.toolCall.chunks)!=null?Zs:[],v.toolCall.chunks.push((gn=m.delta)!=null?gn:""),c(v))}}}else if(_e==="agent_turn_complete"){let P=m.turnId;if(P){let v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U(m.completedAt);let T=(mn=v.reasoning.startedAt)!=null?mn:Date.now();v.reasoning.durationMs=Math.max(0,((tt=v.reasoning.completedAt)!=null?tt:Date.now())-T),v.streaming=!1,c(v)}}}else if(_e==="agent_tool_start"){let P=(Wn=m.toolCallId)!=null?Wn:`agent-tool-${g()}`;_(y(m),P);let v=X(P),T=(Vn=v.toolCall)!=null?Vn:{id:P,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};T.name=(Xn=m.toolName)!=null?Xn:T.name,T.status="running",m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=U((Gn=m.startedAt)!=null?Gn:m.timestamp),v.toolCall=T,v.streaming=!0,v.agentMetadata={executionId:m.executionId,iteration:m.iteration},c(v)}else if(_e==="agent_tool_delta"){let P=(Ht=m.toolCallId)!=null?Ht:S.lastId;if(P){let v=(Nt=C.get(P))!=null?Nt:X(P);v.toolCall&&(v.toolCall.chunks=(nn=v.toolCall.chunks)!=null?nn:[],v.toolCall.chunks.push((Yt=m.delta)!=null?Yt:""),v.toolCall.status="running",v.streaming=!0,c(v))}}else if(_e==="agent_tool_complete"){let P=(Qn=m.toolCallId)!=null?Qn:S.lastId;if(P){let v=(hn=C.get(P))!=null?hn:X(P);if(v.toolCall){v.toolCall.status="complete",m.result!==void 0&&(v.toolCall.result=m.result),typeof m.executionTime=="number"&&(v.toolCall.durationMs=m.executionTime),v.toolCall.completedAt=U((qt=m.completedAt)!=null?qt:m.timestamp),v.streaming=!1,c(v);let T=y(m);T&&S.byCall.delete(T)}}}else if(_e!=="agent_iteration_complete")if(_e==="agent_reflection"||_e==="agent_reflect"){let P=`agent-reflection-${m.executionId}-${m.iteration}`,v={id:P,role:"assistant",content:(bs=m.reflection)!=null?bs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:g(),reasoning:{id:P,status:"complete",chunks:[(In=m.reflection)!=null?In:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};c(v)}else if(_e==="agent_complete"){D&&(D.status=m.success?"complete":"error",D.completedAt=U(m.completedAt),D.stopReason=m.stopReason);let P=h;P&&(P.streaming=!1,c(P)),r({type:"status",status:"idle"})}else if(_e==="agent_error"){let P=typeof m.error=="string"?m.error:(xs=(Cs=m.error)==null?void 0:Cs.message)!=null?xs:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",P):r({type:"error",error:new Error(P)})}else _e==="agent_ping"||_e==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}};function Wi(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Pn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function bn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Hn=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,t,o,s,i,a,d;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(t=n.message.agentMetadata.agentName)!=null?t:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):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,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new yn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(r=(n=this.callbacks).onError)==null||r.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 r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}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,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new yn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:t,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:g=!1}=n,c={id:i!=null?i:r==="user"?Pn():r==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:g,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(c),c}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let t of n){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:g,sequence:w,streaming:c=!1}=t,f={id:d!=null?d:o==="user"?Pn():o==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:g!=null?g:new Date().toISOString(),sequence:w!=null?w:this.nextSequence(),streaming:c,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(f)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var g,w,c,h,f;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(g=this.abortController)==null||g.abort();let o=Pn(),s=bn(),i={id:o,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.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(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let E={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(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(c=(w=this.callbacks).onError)==null||c.call(w,x):(f=(h=this.callbacks).onError)==null||f.call(h,new Error(String(x))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=bn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(g){let w={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(w),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,g):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(g)))}}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.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,t)=>{var d,g;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(g=t.sequence)!=null?g:0;return i!==a?i-a:r.id.localeCompare(t.id)})}};var p=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};var Ia=xa(require("lucide"),1),ie=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ia[o];return s?Pa(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Pa(e,n,r,t){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.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(([g,w])=>{g!=="stroke"&&d.setAttribute(g,String(w))}),o.appendChild(d)}}}),o}function Ii(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pi(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Hi(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Bi(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Bs(e){return{type:"text",text:e}}function Ri(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 Fi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function $i(e,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Oi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ha=["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"],cn=[...Oi,...Ha];function Ba(e){return Oi.includes(e)||e.startsWith("image/")}function Rs(e){return Ba(e.type)}async function Ni(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;Rs(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function Di(e,n=cn,r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ra(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function ji(e,n){let r=Ra(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]||r||"FILE"}var Fs={allowedTypes:cn,maxFileSize:10*1024*1024,maxFiles:4};function Fa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $a(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 Cn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,t,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Fs.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Fs.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Fs.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:Fs.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,o,s,i,a,d,g;if(!n||n.length===0)return;let r=Array.from(n);for(let w of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,w,"count");continue}let c=Di(w,this.config.allowedTypes,this.config.maxFileSize);if(!c.valid){let h=(s=c.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,w,h);continue}try{let h=await Ni(w),f=Rs(w)?URL.createObjectURL(w):null,x={id:Fa(),file:w,previewUrl:f,contentPart:h};this.attachments.push(x),this.renderPreview(x)}catch(h){console.error("[AttachmentManager] Failed to process file:",h)}}this.updatePreviewsVisibility(),(g=(d=this.config).onAttachmentsChange)==null||g.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(d=>d.id===n);if(r===-1)return;let t=this.attachments[r];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=Rs(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",r&&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=$a(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let g=p("span");g.textContent=ji(n.file.type,n.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--cw-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",i.appendChild(g),t.appendChild(i)}let o=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(o),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){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:r})}};var rr=()=>{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"},Oa=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",r=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||rr()==="dark"?t:r},_i=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(rr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(rr());r.addEventListener?(r.addEventListener("change",t),n.push(()=>r.removeEventListener("change",t))):r.addListener&&(r.addListener(t),n.push(()=>r.removeListener(t)))}return()=>{n.forEach(r=>r())}},$s=(e,n)=>{let r=Oa(n);Object.entries(r).forEach(([t,o])=>{if(o==null||o==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(o))})};var qi=require("idiomorph"),zi=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;qi.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&t&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ut={"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 is=(e,n)=>{let r=p("button");r.type="button",r.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,24 +12,24 @@
12
12
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,r.addEventListener("click",n);let t=s=>{var A,L,V,v,O,W,P,se,_,oe,X,U;let i=(A=s.launcher)!=null?A:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(L=i.title)!=null?L:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(V=i.subtitle)!=null?V:"Get answers fast");let g=r.querySelector(".tvw-flex-col");g&&(i.textHidden?g.style.display="none":g.style.display="");let w=r.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let xe=(v=i.agentIconSize)!=null?v:"40px";if(w.style.height=xe,w.style.width=xe,w.innerHTML="",i.agentIconName){let N=parseFloat(xe)||24,ne=re(i.agentIconName,N*.6,"#ffffff",2);ne?(w.appendChild(ne),w.style.display=""):(w.textContent=(O=i.agentIconText)!=null?O:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(W=i.agentIconText)!=null?W:"\u{1F4AC}",w.style.display="")}let c=r.querySelector("[data-role='launcher-image']");if(c){let xe=(P=i.agentIconSize)!=null?P:"40px";c.style.height=xe,c.style.width=xe,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(c.src=i.iconUrl,c.style.display="block"):c.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let xe=(se=i.callToActionIconSize)!=null?se:"32px";m.style.height=xe,m.style.width=xe,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 N=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,N=(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 ne=parseFloat(xe)||24,D=Math.max(ne-N,8),Z=re(i.callToActionIconName,D,"currentColor",2);Z?m.appendChild(Z):m.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(oe=i.callToActionIconText)!=null?oe:"\u2197"}let f=i.position&&zt[i.position]?zt[i.position]:zt["bottom-right"],x="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${x} ${f}`;let C="1px solid #e5e7eb",T="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(X=i.border)!=null?X:C,r.style.boxShadow=(U=i.shadow)!=null?U:T},o=()=>{r.removeEventListener("click",n),r.remove()};return e&&t(e),{element:r,update:t,destroy:o}};var tn=e=>{var oe,X,U,xe,N,ne,D,Z,fe,ce,Ue,dt,At,Ft,Re,Se,ee,ue,Fe,Qe,St,pe,J,pt,gt,ft,$t,wt,Y,Le,vt,yt;let{config:n,showClose:r=!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"),o=(oe=n==null?void 0:n.launcher)!=null?oe:{},s=(X=o.headerIconSize)!=null?X:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",a=(xe=o.closeButtonPlacement)!=null?xe:"inline",d=(N=o.headerIconHidden)!=null?N:!1,g=o.headerIconName,w=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=s,w.style.width=s,!d)if(g){let Q=parseFloat(s)||24,$e=re(g,Q*.6,"#ffffff",1);$e?w.replaceChildren($e):w.textContent=(D=(ne=n==null?void 0:n.launcher)==null?void 0:ne.agentIconText)!=null?D:"\u{1F4AC}"}else if((Z=n==null?void 0:n.launcher)!=null&&Z.iconUrl){let Q=p("img");Q.src=n.launcher.iconUrl,Q.alt="",Q.className="tvw-rounded-xl tvw-object-cover",Q.style.height=s,Q.style.width=s,w.replaceChildren(Q)}else w.textContent=(ce=(fe=n==null?void 0:n.launcher)==null?void 0:fe.agentIconText)!=null?ce:"\u{1F4AC}";let c=p("div","tvw-flex tvw-flex-col"),m=p("span","tvw-text-base tvw-font-semibold");m.textContent=(dt=(Ue=n==null?void 0:n.launcher)==null?void 0:Ue.title)!=null?dt:"Chat Assistant";let f=p("span","tvw-text-xs tvw-text-cw-muted");f.textContent=(Ft=(At=n==null?void 0:n.launcher)==null?void 0:At.subtitle)!=null?Ft:"Here to help you get answers fast",c.append(m,f),d?t.append(c):t.append(w,c);let x=(Re=o.clearChat)!=null?Re:{},C=(Se=x.enabled)!=null?Se:!0,T=(ee=x.placement)!=null?ee:"inline",A=null,L=null;if(C){let Q=(ue=x.size)!=null?ue:"32px",$e=(Fe=x.iconName)!=null?Fe:"refresh-cw",bt=(Qe=x.iconColor)!=null?Qe:"",Lt=(St=x.backgroundColor)!=null?St:"",Et=(pe=x.borderWidth)!=null?pe:"",j=(J=x.borderColor)!=null?J:"",Ze=(pt=x.borderRadius)!=null?pt:"",ke=(gt=x.paddingX)!=null?gt:"",z=(ft=x.paddingY)!=null?ft:"",R=($t=x.tooltipText)!=null?$t:"Clear chat",ge=(wt=x.showTooltip)!=null?wt:!0;L=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"&&(L.style.right="48px"),A=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"),A.style.height=Q,A.style.width=Q,A.type="button",A.setAttribute("aria-label",R);let de=re($e,"20px",bt||"",1);if(de&&A.appendChild(de),bt&&(A.style.color=bt,A.classList.remove("tvw-text-cw-muted")),Lt&&(A.style.backgroundColor=Lt,A.classList.remove("hover:tvw-bg-gray-100")),Et||j){let te=Et||"0px",Te=j||"transparent";A.style.border=`${te} solid ${Te}`,A.classList.remove("tvw-border-none")}if(Ze&&(A.style.borderRadius=Ze,A.classList.remove("tvw-rounded-full")),ke?(A.style.paddingLeft=ke,A.style.paddingRight=ke):(A.style.paddingLeft="",A.style.paddingRight=""),z?(A.style.paddingTop=z,A.style.paddingBottom=z):(A.style.paddingTop="",A.style.paddingBottom=""),L.appendChild(A),ge&&R&&A&&L){let te=null,Te=()=>{if(te||!A)return;te=p("div","tvw-clear-chat-tooltip"),te.textContent=R;let q=p("div");q.className="tvw-clear-chat-tooltip-arrow",te.appendChild(q);let ae=A.getBoundingClientRect();te.style.position="fixed",te.style.left=`${ae.left+ae.width/2}px`,te.style.top=`${ae.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Oe=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};L.addEventListener("mouseenter",Te),L.addEventListener("mouseleave",Oe),A.addEventListener("focus",Te),A.addEventListener("blur",Oe),L._cleanupTooltip=()=>{Oe(),L&&(L.removeEventListener("mouseenter",Te),L.removeEventListener("mouseleave",Oe)),A&&(A.removeEventListener("focus",Te),A.removeEventListener("blur",Oe))}}T==="inline"&&t.appendChild(L)}let V=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":C&&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 O=(Y=o.closeButtonTooltipText)!=null?Y:"Close chat",W=(Le=o.closeButtonShowTooltip)!=null?Le:!0;v.setAttribute("aria-label",O),v.style.display=r?"":"none";let P=(vt=o.closeButtonIconName)!=null?vt:"x",se=(yt=o.closeButtonIconText)!=null?yt:"\xD7",_=re(P,"20px",o.closeButtonColor||"",1);if(_?v.appendChild(_):v.textContent=se,o.closeButtonColor?(v.style.color=o.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(v.style.backgroundColor=o.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Q=o.closeButtonBorderWidth||"0px",$e=o.closeButtonBorderColor||"transparent";v.style.border=`${Q} solid ${$e}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(v.style.borderRadius=o.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(v.style.paddingLeft=o.closeButtonPaddingX,v.style.paddingRight=o.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),o.closeButtonPaddingY?(v.style.paddingTop=o.closeButtonPaddingY,v.style.paddingBottom=o.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),V.appendChild(v),W&&O){let Q=null,$e=()=>{if(Q)return;Q=p("div","tvw-clear-chat-tooltip"),Q.textContent=O;let Lt=p("div");Lt.className="tvw-clear-chat-tooltip-arrow",Q.appendChild(Lt);let Et=v.getBoundingClientRect();Q.style.position="fixed",Q.style.left=`${Et.left+Et.width/2}px`,Q.style.top=`${Et.top-8}px`,Q.style.transform="translate(-50%, -100%)",document.body.appendChild(Q)},bt=()=>{Q&&Q.parentNode&&(Q.parentNode.removeChild(Q),Q=null)};V.addEventListener("mouseenter",$e),V.addEventListener("mouseleave",bt),v.addEventListener("focus",$e),v.addEventListener("blur",bt),V._cleanupTooltip=()=>{bt(),V.removeEventListener("mouseenter",$e),V.removeEventListener("mouseleave",bt),v.removeEventListener("focus",$e),v.removeEventListener("blur",bt)}}return a!=="top-right"&&t.appendChild(V),{header:t,iconHolder:w,headerTitle:m,headerSubtitle:f,closeButton:v,closeButtonWrapper:V,clearChatButton:A,clearChatButtonWrapper:L}},vn=(e,n,r)=>{var i,a,d,g;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=t.closeButtonPlacement)!=null?a:"inline",s=(g=(d=t.clearChat)==null?void 0:d.placement)!=null?g:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var Xs=e=>tn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),Gs=e=>{var x,C,T,A;let{config:n,showClose:r=!0,onClose:t}=e,o=(x=n==null?void 0:n.launcher)!=null?x:{},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=(C=o.title)!=null?C:"Chat Assistant",s.appendChild(i);let a=(T=o.closeButtonSize)!=null?T:"32px",d=p("div",""),g=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");g.style.height=a,g.style.width=a,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=r?"":"none";let w=(A=o.closeButtonIconName)!=null?A:"x",c=re(w,"20px",o.closeButtonColor||"",2);c?g.appendChild(c):g.textContent="\xD7",t&&g.addEventListener("click",t),d.appendChild(g),s.appendChild(d);let m=p("div");m.style.display="none";let f=p("span");return f.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:f,closeButton:g,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Qs=e=>{var v,O,W,P,se,_,oe,X;let{config:n,showClose:r=!0,onClose:t,onClearChat:o}=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=(O=s.headerIconSize)!=null?O:"56px",g=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");g.style.height=d,g.style.width=d;let w=s.headerIconName;if(w){let U=parseFloat(d)||24,xe=re(w,U*.5,"#ffffff",2);xe?g.replaceChildren(xe):g.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}"}else if(s.iconUrl){let U=p("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=d,U.style.width=d,g.replaceChildren(U)}else g.textContent=(P=s.agentIconText)!=null?P:"\u{1F4AC}";let c=p("div","tvw-flex tvw-flex-col tvw-flex-1"),m=p("span","tvw-text-lg tvw-font-semibold");m.textContent=(se=s.title)!=null?se:"Chat Assistant";let f=p("span","tvw-text-sm tvw-text-cw-muted");f.textContent=(_=s.subtitle)!=null?_:"Here to help you get answers fast",c.append(m,f),a.append(g,c);let x=(oe=s.closeButtonSize)!=null?oe:"32px",C=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=x,T.style.width=x,T.type="button",T.setAttribute("aria-label","Close chat"),T.style.display=r?"":"none";let A=(X=s.closeButtonIconName)!=null?X:"x",L=re(A,"20px",s.closeButtonColor||"",2);L?T.appendChild(L):T.textContent="\xD7",t&&T.addEventListener("click",t),C.appendChild(T),a.appendChild(C),i.appendChild(a);let V=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return V.textContent="Online and ready to help",i.appendChild(V),{header:i,iconHolder:g,headerTitle:m,headerSubtitle:f,closeButton:T,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}},Ls={default:Xs,minimal:Gs,expanded:Qs},Zs=e=>{var n;return(n=Ls[e])!=null?n:Ls.default},Ln=(e,n,r)=>{var i,a,d;if(n!=null&&n.render){let g=n.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),w=p("div");w.style.display="none";let c=p("span"),m=p("span"),f=p("button");f.style.display="none";let x=p("div");return x.style.display="none",{header:g,iconHolder:w,headerTitle:c,headerSubtitle:m,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=Zs(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.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 Na=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'}},Wn=e=>{var Re,Se,ee,ue,Fe,Qe,St,pe,J,pt,gt,ft,$t,wt,Y,Le,vt,yt,Q,$e,bt,Lt,Et,j,Ze,ke,z,R,ge,de;let{config:n}=e,r=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=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");o.style.outline="none";let s=p("textarea");s.placeholder=(Se=(Re=n==null?void 0:n.copy)==null?void 0:Re.inputPlaceholder)!=null?Se:"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 tvw-composer-textarea",s.rows=1;let i=(ue=(ee=n==null?void 0:n.theme)==null?void 0:ee.inputFontFamily)!=null?ue:"sans-serif",a=(Qe=(Fe=n==null?void 0:n.theme)==null?void 0:Fe.inputFontWeight)!=null?Qe:"400";s.style.fontFamily=Na(i),s.style.fontWeight=a;let w=3*20;s.style.maxHeight=`${w}px`,s.style.overflowY="auto";let c=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,w);s.style.height=`${te}px`};s.addEventListener("input",c),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=(St=n==null?void 0:n.sendButton)!=null?St:{},f=(pe=m.useIcon)!=null?pe:!1,x=(J=m.iconText)!=null?J:"\u2191",C=m.iconName,T=(pt=m.tooltipText)!=null?pt:"Send message",A=(gt=m.showTooltip)!=null?gt:!1,L=(ft=m.size)!=null?ft:"40px",V=m.backgroundColor,v=m.textColor,O=p("div","tvw-send-button-wrapper"),W=p("button",f?"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(W.type="submit",f){if(W.style.width=L,W.style.height=L,W.style.minWidth=L,W.style.minHeight=L,W.style.fontSize="18px",W.style.lineHeight="1",W.innerHTML="",C){let te=parseFloat(L)||24,Te=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Oe=re(C,te,Te,2);Oe?(W.appendChild(Oe),W.style.color=Te):(W.textContent=x,v?W.style.color=v:W.classList.add("tvw-text-white"))}else W.textContent=x,v?W.style.color=v:W.classList.add("tvw-text-white");V?W.style.backgroundColor=V:W.classList.add("tvw-bg-cw-primary")}else W.textContent=(wt=($t=n==null?void 0:n.copy)==null?void 0:$t.sendButtonLabel)!=null?wt:"Send",v?W.style.color=v:W.classList.add("tvw-text-white");if(m.borderWidth&&(W.style.borderWidth=m.borderWidth,W.style.borderStyle="solid"),m.borderColor&&(W.style.borderColor=m.borderColor),m.paddingX?(W.style.paddingLeft=m.paddingX,W.style.paddingRight=m.paddingX):(W.style.paddingLeft="",W.style.paddingRight=""),m.paddingY?(W.style.paddingTop=m.paddingY,W.style.paddingBottom=m.paddingY):(W.style.paddingTop="",W.style.paddingBottom=""),A&&T){let te=p("div","tvw-send-button-tooltip");te.textContent=T,O.appendChild(te)}O.appendChild(W);let P=(Y=n==null?void 0:n.voiceRecognition)!=null?Y:{},se=P.enabled===!0,_=null,oe=null,X=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(se&&X){oe=p("div","tvw-send-button-wrapper"),_=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),_.type="button",_.setAttribute("aria-label","Start voice recognition");let te=(Le=P.iconName)!=null?Le:"mic",Te=(vt=P.iconSize)!=null?vt:L,Oe=parseFloat(Te)||24,q=(yt=P.backgroundColor)!=null?yt:V,ae=(Q=P.iconColor)!=null?Q:v;_.style.width=Te,_.style.height=Te,_.style.minWidth=Te,_.style.minHeight=Te,_.style.fontSize="18px",_.style.lineHeight="1";let He=ae||"currentColor",Je=re(te,Oe,He,1.5);Je?(_.appendChild(Je),_.style.color=He):(_.textContent="\u{1F3A4}",_.style.color=He),q?_.style.backgroundColor=q:_.classList.add("tvw-bg-cw-primary"),ae?_.style.color=ae:!ae&&!v&&_.classList.add("tvw-text-white"),P.borderWidth&&(_.style.borderWidth=P.borderWidth,_.style.borderStyle="solid"),P.borderColor&&(_.style.borderColor=P.borderColor),P.paddingX&&(_.style.paddingLeft=P.paddingX,_.style.paddingRight=P.paddingX),P.paddingY&&(_.style.paddingTop=P.paddingY,_.style.paddingBottom=P.paddingY),oe.appendChild(_);let it=($e=P.tooltipText)!=null?$e:"Start voice recognition";if(((bt=P.showTooltip)!=null?bt:!1)&&it){let at=p("div","tvw-send-button-tooltip");at.textContent=it,oe.appendChild(at)}}let U=(Lt=n==null?void 0:n.attachments)!=null?Lt:{},xe=U.enabled===!0,N=null,ne=null,D=null,Z=null;if(xe){Z=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),Z.style.display="none",D=p("input"),D.type="file",D.accept=((Et=U.allowedTypes)!=null?Et:an).join(","),D.multiple=((j=U.maxFiles)!=null?j:4)>1,D.style.display="none",D.setAttribute("aria-label","Attach files"),ne=p("div","tvw-send-button-wrapper"),N=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),N.type="button",N.setAttribute("aria-label",(Ze=U.buttonTooltipText)!=null?Ze:"Attach file");let te=(ke=U.buttonIconName)!=null?ke:"paperclip",Te=L,Oe=parseFloat(Te)||40,q=Math.round(Oe*.6);N.style.width=Te,N.style.height=Te,N.style.minWidth=Te,N.style.minHeight=Te,N.style.fontSize="18px",N.style.lineHeight="1",N.style.backgroundColor="transparent",N.style.color="var(--cw-primary, #111827)",N.style.border="none",N.style.borderRadius="6px",N.style.transition="background-color 0.15s ease",N.addEventListener("mouseenter",()=>{N.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),N.addEventListener("mouseleave",()=>{N.style.backgroundColor="transparent"});let ae=re(te,q,"currentColor",1.5);ae?N.appendChild(ae):N.textContent="\u{1F4CE}",N.addEventListener("click",it=>{it.preventDefault(),D==null||D.click()}),ne.appendChild(N);let He=(z=U.buttonTooltipText)!=null?z:"Attach file",Je=p("div","tvw-send-button-tooltip");Je.textContent=He,ne.appendChild(Je)}o.addEventListener("click",te=>{te.target!==W&&te.target!==O&&te.target!==_&&te.target!==oe&&te.target!==N&&te.target!==ne&&s.focus()}),Z&&(Z.style.gap="8px",o.append(Z)),D&&o.append(D),o.append(s);let fe=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),ce=p("div","tvw-flex tvw-items-center tvw-gap-2");ne&&ce.append(ne);let Ue=p("div","tvw-flex tvw-items-center tvw-gap-1");oe&&Ue.append(oe),Ue.append(O),fe.append(ce,Ue),o.append(fe);let dt=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),At=(R=n==null?void 0:n.statusIndicator)!=null?R:{},Ft=(ge=At.visible)!=null?ge:!0;return dt.style.display=Ft?"":"none",dt.textContent=(de=At.idleText)!=null?de:"Online",r.append(t,o,dt),{footer:r,suggestions:t,composerForm:o,textarea:s,sendButton:W,sendButtonWrapper:O,micButton:_,micButtonWrapper:oe,statusText:dt,attachmentButton:N,attachmentButtonWrapper:ne,attachmentInput:D,attachmentPreviewsContainer:Z,actionsRow:fe,leftActions:ce,rightActions:Ue}};var Ui=e=>{var d,g,w,c,m,f,x;if(!((g=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?g:!0)){let C=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"),A=(c=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?c:"100%";return C.style.width=A,T.style.width="100%",C.appendChild(T),{wrapper:C,panel:T}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},t=r.position&&zt[r.position]?zt[r.position]:zt["bottom-right"],o=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(x=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?x:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},Ji=(e,n=!0)=>{var f,x,C,T,A,L,V;let r=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(f=e==null?void 0:e.layout)==null?void 0:f.header,o=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,s=t?Ln(e,t,{showClose:n}):tn({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=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?T:"Hello \u{1F44B}";let g=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");g.textContent=(L=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",a.append(d,g);let w=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,w);let c=Wn({config:e}),m=((V=e==null?void 0:e.layout)==null?void 0:V.showFooter)!==!1;return o?vn(r,s,e):(s.header.style.display="none",vn(r,s,e)),r.append(i),m||(c.footer.style.display="none"),r.append(c.footer),{container:r,body:i,messagesWrapper:w,suggestions:c.suggestions,textarea:c.textarea,sendButton:c.sendButton,sendButtonWrapper:c.sendButtonWrapper,micButton:c.micButton,micButtonWrapper:c.micButtonWrapper,composerForm:c.composerForm,statusText:c.statusText,introTitle:d,introSubtitle:g,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:c.footer,attachmentButton:c.attachmentButton,attachmentButtonWrapper:c.attachmentButtonWrapper,attachmentInput:c.attachmentInput,attachmentPreviewsContainer:c.attachmentPreviewsContainer,actionsRow:c.actionsRow,leftActions:c.leftActions,rightActions:c.rightActions}};var yn=()=>{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 r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(r),e.appendChild(t),e.appendChild(o),e},er=(e,n,r)=>{let t={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:yn};if(n){let o=n(t);if(o!==null)return o}return yn()},Da=(e,n)=>{let r=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=p("img");o.src=t,o.alt=n==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=n==="user"?"U":"A",r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Ki=(e,n)=>{let r=p("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?r.textContent=n.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},ja=(e,n="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},tr=(e,n,r)=>{var f,x,C,T,A,L;let t=(f=n.showCopy)!=null?f:!0,o=(x=n.showUpvote)!=null?x:!0,s=(C=n.showDownvote)!=null?C:!0,i=(T=n.visibility)!=null?T:"hover",a=(A=n.align)!=null?A:"right",d=(L=n.layout)!=null?L:"pill-inside",g={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],c=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${g} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`);c.id=`actions-${e.id}`,c.setAttribute("data-actions-for",e.id);let m=(V,v,O)=>{let W=document.createElement("button");W.className="tvw-message-action-btn",W.setAttribute("aria-label",v),W.setAttribute("title",v),W.setAttribute("data-action",O);let P=re(V,14,"currentColor",2);return P&&W.appendChild(P),W};return t&&c.appendChild(m("copy","Copy message","copy")),o&&c.appendChild(m("thumbs-up","Upvote","upvote")),s&&c.appendChild(m("thumbs-down","Downvote","downvote")),c},In=(e,n,r,t,o,s)=>{var v,O,W,P,se;let i=r!=null?r:{},a=(v=i.layout)!=null?v:"bubble",d=i.avatar,g=i.timestamp,w=(O=d==null?void 0:d.show)!=null?O:!1,c=(W=g==null?void 0:g.show)!=null?W:!1,m=(P=d==null?void 0:d.position)!=null?P:"left",f=(se=g==null?void 0:g.position)!=null?se:"below",x=ja(e.role,a),C=p("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id);let T=document.createElement("div");if(T.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),c&&f==="inline"&&e.createdAt){let _=Ki(e,g);_.classList.add("tvw-ml-2","tvw-inline"),T.appendChild(_)}if(C.appendChild(T),c&&f==="below"&&e.createdAt){let _=Ki(e,g);_.classList.add("tvw-mt-1"),C.appendChild(_)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let _=er("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);_&&C.appendChild(_)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let _=tr(e,t,o);C.appendChild(_)}if(!w||e.role==="system")return C;let L=p("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),V=Da(d,e.role);return m==="right"||m==="left"&&e.role==="user"?L.append(C,V):L.append(V,C),C.classList.remove("tvw-max-w-[85%]"),C.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),L},Yi=(e,n,r,t,o,s)=>{let i=r!=null?r:{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):In(e,n,r,t,o,s)};var Pn=new Set,Vi=(e,n)=>{let r=Pn.has(e),t=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".tvw-border-t");if(!t||!o)return;t.setAttribute("aria-expanded",r?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=re(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},nr=e=>{let n=e.reasoning,r=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let t=Pn.has(e.id),o=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false"),o.setAttribute("data-expand-header","true"),o.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=Ti(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),w=re(t?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=t?"Hide":"Show";let c=p("div","tvw-flex tvw-items-center tvw-ml-auto");c.append(d),o.append(s,c);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 f=n.chunks.join(""),x=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return x.textContent=f||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(x),(()=>{o.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let A=re(t?"chevron-up":"chevron-down",16,"currentColor",2);A?d.appendChild(A):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),r.append(o,m),r};var Hn=new Set,Xi=(e,n,r)=>{var g;let t=Hn.has(e),o=(g=r==null?void 0:r.toolCall)!=null?g:{},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 w=o.toggleTextColor||o.headerTextColor||"currentColor",c=re(t?"chevron-up":"chevron-down",16,w,2);c?d.appendChild(c):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},sr=(e,n)=>{var C;let r=e.toolCall,t=(C=n==null?void 0:n.toolCall)!=null?C:{},o=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=Hn.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=Mi(r),a.appendChild(d);let g=p("div","tvw-flex tvw-items-center"),w=t.toggleTextColor||t.headerTextColor||"currentColor",c=re(s?"chevron-up":"chevron-down",16,w,2);c?g.appendChild(c):g.textContent=s?"Hide":"Show";let m=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(g),i.append(a,m);let f=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(f.style.display=s?"":"none",t.contentBackgroundColor&&(f.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(f.style.color=t.contentTextColor),t.contentPaddingX&&(f.style.paddingLeft=t.contentPaddingX,f.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(f.style.paddingTop=t.contentPaddingY,f.style.paddingBottom=t.contentPaddingY),r.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=r.name,f.appendChild(T)}if(r.args!==void 0){let T=p("div","tvw-space-y-1"),A=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(A.style.color=t.labelTextColor),A.textContent="Arguments";let L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(L.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(L.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(L.style.color=t.codeBlockTextColor),L.textContent=Ks(r.args),T.append(A,L),f.appendChild(T)}if(r.chunks&&r.chunks.length){let T=p("div","tvw-space-y-1"),A=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(A.style.color=t.labelTextColor),A.textContent="Activity";let L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(L.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(L.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(L.style.color=t.codeBlockTextColor),L.textContent=r.chunks.join(`
16
- `),T.append(A,L),f.appendChild(T)}if(r.status==="complete"&&r.result!==void 0){let T=p("div","tvw-space-y-1"),A=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(A.style.color=t.labelTextColor),A.textContent="Result";let L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(L.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(L.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(L.style.color=t.codeBlockTextColor),L.textContent=Ks(r.result),T.append(A,L),f.appendChild(T)}if(r.status==="complete"&&typeof r.duration=="number"){let T=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(T.style.color=t.contentTextColor),T.textContent=`Duration: ${r.duration}ms`,f.appendChild(T)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),g.innerHTML="";let T=t.toggleTextColor||t.headerTextColor||"currentColor",A=re(s?"chevron-up":"chevron-down",16,T,2);A?g.appendChild(A):g.textContent=s?"Hide":"Show",f.style.display=s?"":"none"})(),o.append(i,f),o};var Gi=e=>{let n=[];return{buttons:n,render:(t,o,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(f=>f.role==="user"))return;let w=document.createDocumentFragment(),c=o?o.isStreaming():!1,m=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(f=>{let x=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");x.type="button",x.textContent=f,x.disabled=c,a!=null&&a.fontFamily&&(x.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(x.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(x.style.paddingLeft=a.paddingX,x.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(x.style.paddingTop=a.paddingY,x.style.paddingBottom=a.paddingY),x.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(f))}),w.appendChild(x),n.push(x)}),e.appendChild(w)}}};var ts=class{constructor(n=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=r}push(n){var r;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(r=this.store)==null||r.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let r=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let t of r)this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(t.type);return this.totalCaptured=n.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let r=this.getAll();return n>=r.length?r:r.slice(r.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ns=class{constructor(n="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=r}open(){return new Promise((n,r)=>{try{let t=indexedDB.open(this.dbName,1);t.onupgradeneeded=()=>{let o=t.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},t.onsuccess=()=>{this.db=t.result,n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}getAll(){return new Promise((n,r)=>{if(!this.db){n([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{n(i.result)},i.onerror=()=>{r(i.error)}}catch(t){r(t)}})}getCount(){return new Promise((n,r)=>{if(!this.db){n(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}clear(){return new Promise((n,r)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,r)=>{try{let t=indexedDB.deleteDatabase(this.dbName);t.onsuccess=()=>{n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}};function Bn(e,n){n&&n.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var _a={flow_:{bg:"#dcfce7",text:"#166534"},step_:{bg:"#dbeafe",text:"#1e40af"},reason_:{bg:"#ffedd5",text:"#9a3412"},tool_:{bg:"#f3e8ff",text:"#6b21a8"},agent_:{bg:"#ccfbf1",text:"#115e59"},error:{bg:"#fecaca",text:"#991b1b"}},qa={bg:"#f3f4f6",text:"#4b5563"},za=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ua=100;function Ja(e,n){let r={..._a,...n};if(r[e])return r[e];for(let t of Object.keys(r))if(t.endsWith("_")&&e.startsWith(t))return r[t];return qa}function Ka(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Ya(e){let n=new Date(e),r=String(n.getHours()).padStart(2,"0"),t=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${r}:${t}:${o}.${s}`}function Va(e,n){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let t of n){let o=t.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Xa(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),r()})}function Ga(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Qa(e,n,r){let t,o;try{o=JSON.parse(e.payload),t=JSON.stringify(o,null,2)}catch{o=e.payload,t=e.payload}let s=n.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=p("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),d=p("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return d.textContent=t,a.appendChild(d),a}}function rr(e,n,r,t,o,s,i,a){var m;let d=o.has(e.id),g=p("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");Bn(g,(m=t.classNames)==null?void 0:m.eventRow);let w=i.find(f=>f.renderEventStreamRow);if(w!=null&&w.renderEventStreamRow&&a){let f=w.renderEventStreamRow({event:e,index:n,config:a,defaultRenderer:()=>c(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return g.appendChild(f),g}return g.appendChild(c()),g;function c(){var U,xe;let f=p("div",""),x=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-3 tvw-py-3 hover:tvw-bg-cw-container tvw-cursor-pointer tvw-group");x.setAttribute("data-event-id",e.id);let C=p("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),T=re(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&C.appendChild(T);let A=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),L=(U=t.timestampFormat)!=null?U:"relative";A.textContent=L==="relative"?Ka(e.timestamp,r):Ya(e.timestamp);let V=null;t.showSequenceNumbers!==!1&&(V=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),V.textContent=String(n+1));let v=Ja(e.type,t.badgeColors),O=p("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded tvw-text-[11px] tvw-font-mono tvw-font-medium tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-border");O.style.backgroundColor=v.bg,O.style.color=v.text,O.style.borderColor=v.text+"50",O.textContent=e.type;let W=(xe=t.descriptionFields)!=null?xe:za,P=Va(e.payload,W),se=null;P&&(se=p("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),se.textContent=P);let _=p("div","tvw-flex-1 tvw-min-w-0"),oe=p("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),X=re("clipboard","12px","currentColor",1.5);return X&&oe.appendChild(X),oe.addEventListener("click",async N=>{N.stopPropagation(),await Xa(Ga(e)),oe.innerHTML="";let ne=re("check","12px","currentColor",1.5);ne&&oe.appendChild(ne),setTimeout(()=>{oe.innerHTML="";let D=re("clipboard","12px","currentColor",1.5);D&&oe.appendChild(D)},1500)}),x.appendChild(C),x.appendChild(A),V&&x.appendChild(V),x.appendChild(O),se&&x.appendChild(se),x.appendChild(_),x.appendChild(oe),f.appendChild(x),d&&f.appendChild(Qa(e,i,a)),f}}function Qi(e){var g,w;let{buffer:n,getFullHistory:r,onClose:t,config:o,plugins:s=[]}=e,i=(w=(g=o==null?void 0:o.features)==null?void 0:g.eventStream)!=null?w:{},a=s.find(c=>c.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let c=a.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>d().element,onClose:t});if(c)return{element:c,update:()=>{},destroy:()=>{}}}return d();function d(){let c=i.classNames,m=p("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");Bn(m,c==null?void 0:c.panel);let f=[],x="",C="",T=null,A=[],L={},V=0,v=!1,O=0,W=0,P=!1,se=null,_=!1,oe=0,X=new Set,U=new Map,xe="",N="",ne=null,D,Z,fe,ce,Ue;function dt(){let z=p("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),R=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-4 tvw-py-3 tvw-pb-0 tvw-border-cw-divider tvw-bg-cw-surface tvw-overflow-hidden");Bn(R,c==null?void 0:c.headerBar);let ge=p("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");ge.textContent="Events",D=p("span","tvw-text-[11px] tvw-font-mono tvw-bg-cw-container tvw-text-cw-muted tvw-px-2 tvw-py-0.5 tvw-rounded tvw-border tvw-border-cw-border"),D.textContent="0";let de=p("div","tvw-flex-1");Z=p("select","tvw-text-xs tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded tvw-px-2.5 tvw-py-1 tvw-text-cw-primary tvw-cursor-pointer");let te=p("option","");te.value="",te.textContent="All events",Z.appendChild(te),fe=p("button","tvw-inline-flex tvw-items-center tvw-gap-1.5 tvw-rounded tvw-text-xs tvw-text-cw-muted hover:tvw-bg-cw-container hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border tvw-border-cw-border tvw-bg-cw-surface tvw-flex-shrink-0 tvw-px-2.5 tvw-py-1"),fe.type="button",fe.title="Copy All";let Oe=re("clipboard-copy","12px","currentColor",1.5);Oe&&fe.appendChild(Oe);let q=p("span","tvw-text-xs");q.textContent="Copy All",fe.appendChild(q),R.appendChild(ge),R.appendChild(D),R.appendChild(de),R.appendChild(Z),R.appendChild(fe);let ae=p("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");Bn(ae,c==null?void 0:c.searchBar);let He=re("search","14px","var(--cw-muted, #9ca3af)",1.5),Je=p("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");He&&Je.appendChild(He),ce=p("input","tvw-text-sm tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded-md tvw-pl-8 tvw-pr-3 tvw-py-1 tvw-w-full tvw-text-cw-primary"),Bn(ce,c==null?void 0:c.searchInput),ce.type="text",ce.placeholder="Search event payloads...",Ue=p("button","tvw-absolute tvw-right-5 tvw-top-1/2 tvw--translate-y-1/2 tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-0 tvw-leading-none"),Ue.type="button",Ue.style.display="none";let it=re("x","12px","currentColor",2);return it&&Ue.appendChild(it),ae.appendChild(Je),ae.appendChild(ce),ae.appendChild(Ue),z.appendChild(R),z.appendChild(ae),z}let At,Ft=s.find(z=>z.renderEventStreamToolbar);if(Ft!=null&&Ft.renderEventStreamToolbar&&o){let z=Ft.renderEventStreamToolbar({config:o,defaultRenderer:()=>dt(),eventCount:n.getSize(),filteredCount:0,onFilterChange:R=>{x=R,gt(),wt()},onSearchChange:R=>{C=R,gt(),wt()}});At=z!=null?z:dt()}else At=dt();let Re=p("div","tvw-text-xs tvw-text-cw-muted tvw-text-center tvw-py-0.5 tvw-px-4 tvw-bg-cw-container tvw-border-b tvw-border-cw-divider tvw-italic tvw-flex-shrink-0");Re.style.display="none";let Se=p("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ee=p("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ee.style.height="100%";let ue=p("div","tvw-absolute tvw-bottom-3 tvw-left-1/2 tvw-transform tvw--translate-x-1/2 tvw-bg-cw-accent tvw-text-white tvw-text-xs tvw-px-3 tvw-py-1.5 tvw-rounded-full tvw-cursor-pointer tvw-shadow-md tvw-z-10 tvw-flex tvw-items-center tvw-gap-1");Bn(ue,c==null?void 0:c.scrollIndicator),ue.style.display="none";let Fe=re("arrow-down","12px","currentColor",2);Fe&&ue.appendChild(Fe);let Qe=p("span","");ue.appendChild(Qe);let St=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");St.style.display="none",Se.appendChild(ee),Se.appendChild(St),Se.appendChild(ue),m.setAttribute("tabindex","0"),m.appendChild(At),m.appendChild(Re),m.appendChild(Se);function pe(){let z=n.getAll(),R={};for(let q of z)R[q.type]=(R[q.type]||0)+1;let ge=Object.keys(R).sort(),de=ge.length!==A.length||!ge.every((q,ae)=>q===A[ae]),te=!de&&ge.some(q=>R[q]!==L[q]),Te=z.length!==Object.values(L).reduce((q,ae)=>q+ae,0);if(!de&&!te&&!Te||(A=ge,L=R,!Z))return;let Oe=Z.value;if(Z.options[0].textContent="All events",de){for(;Z.options.length>1;)Z.remove(1);for(let q of ge){let ae=p("option","");ae.value=q,ae.textContent=`${q} (${R[q]||0})`,Z.appendChild(ae)}Oe&&ge.includes(Oe)?Z.value=Oe:Oe&&(Z.value="",x="")}else for(let q=1;q<Z.options.length;q++){let ae=Z.options[q];ae.textContent=`${ae.value} (${R[ae.value]||0})`}}function J(){let z=n.getAll();if(x&&(z=z.filter(R=>R.type===x)),C){let R=C.toLowerCase();z=z.filter(ge=>ge.type.toLowerCase().includes(R)||ge.payload.toLowerCase().includes(R))}return z}function pt(){return x!==""||C!==""}function gt(){V=0,O=0,v=!1,ue.style.display="none"}function ft(z){X.has(z)?X.delete(z):X.add(z),ne=z;let R=ee.scrollTop,ge=v;_=!0,v=!0,wt(),ee.scrollTop=R,v=ge,_=!1}function $t(){return ee.scrollHeight-ee.scrollTop-ee.clientHeight<=50}function wt(){W=Date.now(),P=!1,pe();let z=n.getEvictedCount();z>0?(Re.textContent=`${z.toLocaleString()} older events truncated`,Re.style.display=""):Re.style.display="none",f=J();let R=f.length,ge=n.getSize()>0;D&&(D.textContent=String(n.getSize())),R===0&&ge&&pt()?(St.textContent=C?`No events matching '${C}'`:"No events matching filter",St.style.display="",ee.style.display="none"):(St.style.display="none",ee.style.display=""),fe&&(fe.title=pt()?`Copy Filtered (${R})`:"Copy All"),v&&R>V&&(O+=R-V,Qe.textContent=`${O} new event${O===1?"":"s"}`,ue.style.display=""),V=R;let de=n.getAll(),te=de.length>0?de[0].timestamp:0,Te=new Set(f.map(ae=>ae.id));for(let ae of X)Te.has(ae)||X.delete(ae);let Oe=x!==xe||C!==N,q=U.size===0&&f.length>0;if(Oe||q||f.length===0){ee.innerHTML="",U.clear();let ae=document.createDocumentFragment();for(let He=0;He<f.length;He++){let Je=rr(f[He],He,te,i,X,ft,s,o);U.set(f[He].id,Je),ae.appendChild(Je)}ee.appendChild(ae),xe=x,N=C,ne=null}else{if(ne!==null){let He=U.get(ne);if(He&&He.parentNode===ee){let Je=f.findIndex(it=>it.id===ne);if(Je>=0){let it=rr(f[Je],Je,te,i,X,ft,s,o);ee.insertBefore(it,He),He.remove(),U.set(ne,it)}}ne=null}let ae=new Set(f.map(He=>He.id));for(let[He,Je]of U)ae.has(He)||(Je.remove(),U.delete(He));for(let He=0;He<f.length;He++){let Je=f[He];if(!U.has(Je.id)){let it=rr(Je,He,te,i,X,ft,s,o);U.set(Je.id,it),ee.appendChild(it)}}}v||(ee.scrollTop=ee.scrollHeight)}function Y(){if(Date.now()-W>=Ua){se!==null&&(cancelAnimationFrame(se),se=null),wt();return}P||(P=!0,se=requestAnimationFrame(()=>{se=null,wt()}))}let Le=(z,R)=>{if(!fe)return;fe.innerHTML="";let ge=re(z,"12px","currentColor",1.5);ge&&fe.appendChild(ge);let de=p("span","tvw-text-xs");de.textContent="Copy All",fe.appendChild(de),setTimeout(()=>{fe.innerHTML="";let te=re("clipboard-copy","12px","currentColor",1.5);te&&fe.appendChild(te);let Te=p("span","tvw-text-xs");Te.textContent="Copy All",fe.appendChild(Te),fe.disabled=!1},R)},vt=async()=>{if(fe){fe.disabled=!0;try{let z;pt()?z=f:z=r?await r():n.getAll();let R=z.map(ge=>{try{return JSON.parse(ge.payload)}catch{return ge.payload}});await navigator.clipboard.writeText(JSON.stringify(R,null,2)),Le("check",1500)}catch{Le("x",1500)}}},yt=()=>{Z&&(x=Z.value,gt(),wt())},Q=()=>{!ce||!Ue||(Ue.style.display=ce.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{C=ce.value,gt(),wt()},150))},$e=()=>{!ce||!Ue||(ce.value="",C="",Ue.style.display="none",T&&clearTimeout(T),gt(),wt())},bt=()=>{if(_)return;let z=ee.scrollTop,R=z>oe;oe=z,$t()&&R?(v=!1,O=0,ue.style.display="none"):$t()||(v=!0)},Lt=z=>{z.deltaY<0&&(v=!0)},Et=()=>{ee.scrollTop=ee.scrollHeight,v=!1,O=0,ue.style.display="none"},j=z=>{let R=z.target;if(!R||R.closest("button"))return;let ge=R.closest("[data-event-id]");if(!ge)return;let de=ge.getAttribute("data-event-id");de&&ft(de)},Ze=z=>{if((z.metaKey||z.ctrlKey)&&z.key==="f"){z.preventDefault(),ce==null||ce.focus(),ce==null||ce.select();return}z.key==="Escape"&&(ce&&document.activeElement===ce?($e(),ce.blur(),m.focus()):t&&t())};fe&&fe.addEventListener("click",vt),Z&&Z.addEventListener("change",yt),ce&&ce.addEventListener("input",Q),Ue&&Ue.addEventListener("click",$e),ee.addEventListener("scroll",bt),ee.addEventListener("wheel",Lt,{passive:!0}),ee.addEventListener("click",j),ue.addEventListener("click",Et),m.addEventListener("keydown",Ze);function ke(){T&&clearTimeout(T),se!==null&&(cancelAnimationFrame(se),se=null),P=!1,U.clear(),fe&&fe.removeEventListener("click",vt),Z&&Z.removeEventListener("change",yt),ce&&ce.removeEventListener("input",Q),Ue&&Ue.removeEventListener("click",$e),ee.removeEventListener("scroll",bt),ee.removeEventListener("wheel",Lt),ee.removeEventListener("click",j),ue.removeEventListener("click",Et),m.removeEventListener("keydown",Ze)}return{element:m,update:Y,destroy:ke}}}var Zi={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"}},or=(e,n,r,t)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,C,T;if(s.dataset.enhanced==="true")return;let i=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let a=(C=Zi[i])!=null?C:Zi.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),g=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(g.textContent=a.title,d.appendChild(g),a.description){let A=p("p","tvw-text-sm tvw-text-cw-muted");A.textContent=a.description,d.appendChild(A)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(A=>{var W,P;let L=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");L.htmlFor=`${n.id}-${i}-${A.name}`;let V=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");V.textContent=A.label,L.appendChild(V);let v=(W=A.type)!=null?W:"text",O;v==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=v),O.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",O.id=`${n.id}-${i}-${A.name}`,O.name=A.name,O.placeholder=(P=A.placeholder)!=null?P:"",A.required&&(O.required=!0),L.appendChild(O),w.appendChild(L)});let c=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]"),f=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");f.type="submit",f.textContent=(T=a.submitLabel)!=null?T:"Submit",c.appendChild(m),c.appendChild(f),w.appendChild(c),s.replaceChildren(d,w),w.addEventListener("submit",async A=>{var O,W;A.preventDefault();let L=(O=r.formEndpoint)!=null?O:"/form",V=new FormData(w),v={};V.forEach((P,se)=>{v[se]=P}),v.type=i,f.disabled=!0,m.textContent="Submitting\u2026";try{let P=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let se=await P.json();m.textContent=(W=se.message)!=null?W:"Thanks! We'll be in touch soon.",se.success&&se.nextPrompt&&await t.sendMessage(String(se.nextPrompt))}catch(P){m.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var ir=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var t;let r=this.plugins.get(n);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let t=new Set(n.map(s=>s.id));return[...r.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 r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},ss=new ir;var ar={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"},lr={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"},rt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:ar,darkTheme:lr,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 Ws(e){var n,r,t,o,s,i,a,d,g,w,c,m,f,x,C,T,A,L,V;return e?{...rt,...e,theme:{...rt.theme,...e.theme},darkTheme:{...rt.darkTheme,...e.darkTheme},launcher:{...rt.launcher,...e.launcher,clearChat:{...(n=rt.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:{...rt.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...(o=rt.layout)==null?void 0:o.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=rt.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(g=(d=rt.layout)==null?void 0:d.messages)==null?void 0:g.avatar,...(c=(w=e.layout)==null?void 0:w.messages)==null?void 0:c.avatar},timestamp:{...(f=(m=rt.layout)==null?void 0:m.messages)==null?void 0:f.timestamp,...(C=(x=e.layout)==null?void 0:x.messages)==null?void 0:C.timestamp}},slots:{...(T=rt.layout)==null?void 0:T.slots,...(A=e.layout)==null?void 0:A.slots}},markdown:{...rt.markdown,...e.markdown,options:{...(L=rt.markdown)==null?void 0:L.options,...(V=e.markdown)==null?void 0:V.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var ea=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=e.get(o))==null||i.delete(s)};return{on:n,off:r,emit:(o,s)=>{var i;(i=e.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Za=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},el=e=>{let n=e.trim(),r=n.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(r,o+1)}return null},rs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Za(e),r=el(n);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},dr=e=>typeof e=="string"?e:e==null?"":String(e),bn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:dr(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=dr(r.element);if(t&&((o=n.document)!=null&&o.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:dr(r.text)}}},ta=e=>Array.isArray(e)?e.map(n=>String(n)):[],os=e=>{let n=new Set(ta(e.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(ta(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((g,w)=>g||(w==null?void 0:w({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 g of e.handlers)if(g)try{let w=()=>{e.emit("action:resubmit",d)},c=g(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:w});if(!c)continue;if(c.handled){let m=c.persistMessage!==!1;return{text:c.displayText!==void 0?c.displayText:"",persist:m,resubmit:c.resubmit}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:r}};var tl=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}},nl=e=>e.map(n=>({...n,streaming:!1})),Is=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?tl(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?nl(r.messages):void 0};t.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var cr=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}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(([r,t])=>{this.register(r,t)})}},Rn=new cr;var Fn=require("partial-json");function sl(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function rl(e,n){if(!sl(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:n}}function Ps(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e;try{let o=(0,Fn.parse)(r,Fn.STR|Fn.OBJ),s=rl(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function na(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Hs(e,n){let{config:r,message:t,onPropsUpdate:o}=n,s=Rn.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:r,updateProps:a=>{o&&o(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function sa(){let e=Ps();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Bs(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 Rs(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 ol=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fs(e){let{onSubmit:n,onDismiss:r,title:t="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:g=ol}=e,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-csat",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Customer satisfaction feedback");let c=null,m=document.createElement("div");m.className="tvw-feedback-content";let f=document.createElement("div");f.className="tvw-feedback-header";let x=document.createElement("h3");x.className="tvw-feedback-title",x.textContent=t,f.appendChild(x);let C=document.createElement("p");C.className="tvw-feedback-subtitle",C.textContent=o,f.appendChild(C),m.appendChild(f);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 A=[];for(let W=1;W<=5;W++){let P=document.createElement("button");P.type="button",P.className="tvw-feedback-rating-btn tvw-feedback-star-btn",P.setAttribute("role","radio"),P.setAttribute("aria-checked","false"),P.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${g[W-1]}`),P.title=g[W-1],P.dataset.rating=String(W),P.innerHTML=`
15
+ `,r.addEventListener("click",n);let t=s=>{var S,k,V,y,O,W,H,oe,_,le,X,U;let i=(S=s.launcher)!=null?S:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(k=i.title)!=null?k:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(V=i.subtitle)!=null?V:"Get answers fast");let g=r.querySelector(".tvw-flex-col");g&&(i.textHidden?g.style.display="none":g.style.display="");let w=r.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let Se=(y=i.agentIconSize)!=null?y:"40px";if(w.style.height=Se,w.style.width=Se,w.innerHTML="",i.agentIconName){let N=parseFloat(Se)||24,re=ie(i.agentIconName,N*.6,"#ffffff",2);re?(w.appendChild(re),w.style.display=""):(w.textContent=(O=i.agentIconText)!=null?O:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(W=i.agentIconText)!=null?W:"\u{1F4AC}",w.style.display="")}let c=r.querySelector("[data-role='launcher-image']");if(c){let Se=(H=i.agentIconSize)!=null?H:"40px";c.style.height=Se,c.style.width=Se,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(c.src=i.iconUrl,c.style.display="block"):c.style.display="none"}let h=r.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let Se=(oe=i.callToActionIconSize)!=null?oe:"32px";h.style.height=Se,h.style.width=Se,i.callToActionIconBackgroundColor?(h.style.backgroundColor=i.callToActionIconBackgroundColor,h.classList.remove("tvw-bg-cw-primary")):(h.style.backgroundColor="",h.classList.add("tvw-bg-cw-primary"));let N=0;if(i.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=i.callToActionIconPadding,N=(parseFloat(i.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),i.callToActionIconHidden)h.style.display="none";else if(h.style.display="",h.innerHTML="",i.callToActionIconName){let re=parseFloat(Se)||24,D=Math.max(re-N,8),Z=ie(i.callToActionIconName,D,"currentColor",2);Z?h.appendChild(Z):h.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}else h.textContent=(le=i.callToActionIconText)!=null?le:"\u2197"}let f=i.position&&Ut[i.position]?Ut[i.position]:Ut["bottom-right"],x="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${x} ${f}`;let C="1px solid #e5e7eb",E="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(X=i.border)!=null?X:C,r.style.boxShadow=(U=i.shadow)!=null?U:E},o=()=>{r.removeEventListener("click",n),r.remove()};return e&&t(e),{element:r,update:t,destroy:o}};var rn=e=>{var le,X,U,Se,N,re,D,Z,ve,pe,Ue,it,Tt,$t,Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt;let{config:n,showClose:r=!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"),o=(le=n==null?void 0:n.launcher)!=null?le:{},s=(X=o.headerIconSize)!=null?X:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",a=(Se=o.closeButtonPlacement)!=null?Se:"inline",d=(N=o.headerIconHidden)!=null?N:!1,g=o.headerIconName,w=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=s,w.style.width=s,!d)if(g){let Q=parseFloat(s)||24,Oe=ie(g,Q*.6,"#ffffff",1);Oe?w.replaceChildren(Oe):w.textContent=(D=(re=n==null?void 0:n.launcher)==null?void 0:re.agentIconText)!=null?D:"\u{1F4AC}"}else if((Z=n==null?void 0:n.launcher)!=null&&Z.iconUrl){let Q=p("img");Q.src=n.launcher.iconUrl,Q.alt="",Q.className="tvw-rounded-xl tvw-object-cover",Q.style.height=s,Q.style.width=s,w.replaceChildren(Q)}else w.textContent=(pe=(ve=n==null?void 0:n.launcher)==null?void 0:ve.agentIconText)!=null?pe:"\u{1F4AC}";let c=p("div","tvw-flex tvw-flex-col"),h=p("span","tvw-text-base tvw-font-semibold");h.textContent=(it=(Ue=n==null?void 0:n.launcher)==null?void 0:Ue.title)!=null?it:"Chat Assistant";let f=p("span","tvw-text-xs tvw-text-cw-muted");f.textContent=($t=(Tt=n==null?void 0:n.launcher)==null?void 0:Tt.subtitle)!=null?$t:"Here to help you get answers fast",c.append(h,f),d?t.append(c):t.append(w,c);let x=(Fe=o.clearChat)!=null?Fe:{},C=(Ae=x.enabled)!=null?Ae:!0,E=(ee=x.placement)!=null?ee:"inline",S=null,k=null;if(C){let Q=(ge=x.size)!=null?ge:"32px",Oe=($e=x.iconName)!=null?$e:"refresh-cw",bt=(Qe=x.iconColor)!=null?Qe:"",Wt=(At=x.backgroundColor)!=null?At:"",Mt=(me=x.borderWidth)!=null?me:"",j=(J=x.borderColor)!=null?J:"",Ze=(ct=x.borderRadius)!=null?ct:"",We=(ut=x.paddingX)!=null?ut:"",z=(ft=x.paddingY)!=null?ft:"",R=(Ot=x.tooltipText)!=null?Ot:"Clear chat",he=(wt=x.showTooltip)!=null?wt:!0;k=p("div",E==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),S=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),S.style.height=Q,S.style.width=Q,S.type="button",S.setAttribute("aria-label",R);let ue=ie(Oe,"20px",bt||"",1);if(ue&&S.appendChild(ue),bt&&(S.style.color=bt,S.classList.remove("tvw-text-cw-muted")),Wt&&(S.style.backgroundColor=Wt,S.classList.remove("hover:tvw-bg-gray-100")),Mt||j){let te=Mt||"0px",Le=j||"transparent";S.style.border=`${te} solid ${Le}`,S.classList.remove("tvw-border-none")}if(Ze&&(S.style.borderRadius=Ze,S.classList.remove("tvw-rounded-full")),We?(S.style.paddingLeft=We,S.style.paddingRight=We):(S.style.paddingLeft="",S.style.paddingRight=""),z?(S.style.paddingTop=z,S.style.paddingBottom=z):(S.style.paddingTop="",S.style.paddingBottom=""),k.appendChild(S),he&&R&&S&&k){let te=null,Le=()=>{if(te||!S)return;te=p("div","tvw-clear-chat-tooltip"),te.textContent=R;let q=p("div");q.className="tvw-clear-chat-tooltip-arrow",te.appendChild(q);let de=S.getBoundingClientRect();te.style.position="fixed",te.style.left=`${de.left+de.width/2}px`,te.style.top=`${de.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Ne=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};k.addEventListener("mouseenter",Le),k.addEventListener("mouseleave",Ne),S.addEventListener("focus",Le),S.addEventListener("blur",Ne),k._cleanupTooltip=()=>{Ne(),k&&(k.removeEventListener("mouseenter",Le),k.removeEventListener("mouseleave",Ne)),S&&(S.removeEventListener("focus",Le),S.removeEventListener("blur",Ne))}}E==="inline"&&t.appendChild(k)}let V=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":C&&E==="inline"?"":"tvw-ml-auto"),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=i,y.style.width=i,y.type="button";let O=(Y=o.closeButtonTooltipText)!=null?Y:"Close chat",W=(Ie=o.closeButtonShowTooltip)!=null?Ie:!0;y.setAttribute("aria-label",O),y.style.display=r?"":"none";let H=(vt=o.closeButtonIconName)!=null?vt:"x",oe=(yt=o.closeButtonIconText)!=null?yt:"\xD7",_=ie(H,"20px",o.closeButtonColor||"",1);if(_?y.appendChild(_):y.textContent=oe,o.closeButtonColor?(y.style.color=o.closeButtonColor,y.classList.remove("tvw-text-cw-muted")):(y.style.color="",y.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(y.style.backgroundColor=o.closeButtonBackgroundColor,y.classList.remove("hover:tvw-bg-gray-100")):(y.style.backgroundColor="",y.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Q=o.closeButtonBorderWidth||"0px",Oe=o.closeButtonBorderColor||"transparent";y.style.border=`${Q} solid ${Oe}`,y.classList.remove("tvw-border-none")}else y.style.border="",y.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(y.style.borderRadius=o.closeButtonBorderRadius,y.classList.remove("tvw-rounded-full")):(y.style.borderRadius="",y.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(y.style.paddingLeft=o.closeButtonPaddingX,y.style.paddingRight=o.closeButtonPaddingX):(y.style.paddingLeft="",y.style.paddingRight=""),o.closeButtonPaddingY?(y.style.paddingTop=o.closeButtonPaddingY,y.style.paddingBottom=o.closeButtonPaddingY):(y.style.paddingTop="",y.style.paddingBottom=""),V.appendChild(y),W&&O){let Q=null,Oe=()=>{if(Q)return;Q=p("div","tvw-clear-chat-tooltip"),Q.textContent=O;let Wt=p("div");Wt.className="tvw-clear-chat-tooltip-arrow",Q.appendChild(Wt);let Mt=y.getBoundingClientRect();Q.style.position="fixed",Q.style.left=`${Mt.left+Mt.width/2}px`,Q.style.top=`${Mt.top-8}px`,Q.style.transform="translate(-50%, -100%)",document.body.appendChild(Q)},bt=()=>{Q&&Q.parentNode&&(Q.parentNode.removeChild(Q),Q=null)};V.addEventListener("mouseenter",Oe),V.addEventListener("mouseleave",bt),y.addEventListener("focus",Oe),y.addEventListener("blur",bt),V._cleanupTooltip=()=>{bt(),V.removeEventListener("mouseenter",Oe),V.removeEventListener("mouseleave",bt),y.removeEventListener("focus",Oe),y.removeEventListener("blur",bt)}}return a!=="top-right"&&t.appendChild(V),{header:t,iconHolder:w,headerTitle:h,headerSubtitle:f,closeButton:y,closeButtonWrapper:V,clearChatButton:S,clearChatButtonWrapper:k}},xn=(e,n,r)=>{var i,a,d,g;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=t.closeButtonPlacement)!=null?a:"inline",s=(g=(d=t.clearChat)==null?void 0:d.placement)!=null?g:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var or=e=>rn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),ir=e=>{var x,C,E,S;let{config:n,showClose:r=!0,onClose:t}=e,o=(x=n==null?void 0:n.launcher)!=null?x:{},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=(C=o.title)!=null?C:"Chat Assistant",s.appendChild(i);let a=(E=o.closeButtonSize)!=null?E:"32px",d=p("div",""),g=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");g.style.height=a,g.style.width=a,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=r?"":"none";let w=(S=o.closeButtonIconName)!=null?S:"x",c=ie(w,"20px",o.closeButtonColor||"",2);c?g.appendChild(c):g.textContent="\xD7",t&&g.addEventListener("click",t),d.appendChild(g),s.appendChild(d);let h=p("div");h.style.display="none";let f=p("span");return f.style.display="none",{header:s,iconHolder:h,headerTitle:i,headerSubtitle:f,closeButton:g,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},ar=e=>{var y,O,W,H,oe,_,le,X;let{config:n,showClose:r=!0,onClose:t,onClearChat:o}=e,s=(y=n==null?void 0:n.launcher)!=null?y:{},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=(O=s.headerIconSize)!=null?O:"56px",g=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");g.style.height=d,g.style.width=d;let w=s.headerIconName;if(w){let U=parseFloat(d)||24,Se=ie(w,U*.5,"#ffffff",2);Se?g.replaceChildren(Se):g.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}"}else if(s.iconUrl){let U=p("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=d,U.style.width=d,g.replaceChildren(U)}else g.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}";let c=p("div","tvw-flex tvw-flex-col tvw-flex-1"),h=p("span","tvw-text-lg tvw-font-semibold");h.textContent=(oe=s.title)!=null?oe:"Chat Assistant";let f=p("span","tvw-text-sm tvw-text-cw-muted");f.textContent=(_=s.subtitle)!=null?_:"Here to help you get answers fast",c.append(h,f),a.append(g,c);let x=(le=s.closeButtonSize)!=null?le:"32px",C=p("div",""),E=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");E.style.height=x,E.style.width=x,E.type="button",E.setAttribute("aria-label","Close chat"),E.style.display=r?"":"none";let S=(X=s.closeButtonIconName)!=null?X:"x",k=ie(S,"20px",s.closeButtonColor||"",2);k?E.appendChild(k):E.textContent="\xD7",t&&E.addEventListener("click",t),C.appendChild(E),a.appendChild(C),i.appendChild(a);let V=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return V.textContent="Online and ready to help",i.appendChild(V),{header:i,iconHolder:g,headerTitle:h,headerSubtitle:f,closeButton:E,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}},Os={default:or,minimal:ir,expanded:ar},lr=e=>{var n;return(n=Os[e])!=null?n:Os.default},Bn=(e,n,r)=>{var i,a,d;if(n!=null&&n.render){let g=n.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),w=p("div");w.style.display="none";let c=p("span"),h=p("span"),f=p("button");f.style.display="none";let x=p("div");return x.style.display="none",{header:g,iconHolder:w,headerTitle:c,headerSubtitle:h,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=lr(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.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 Na=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 Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt,Q,Oe,bt,Wt,Mt,j,Ze,We,z,R,he,ue;let{config:n}=e,r=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=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");o.style.outline="none";let s=p("textarea");s.placeholder=(Ae=(Fe=n==null?void 0:n.copy)==null?void 0:Fe.inputPlaceholder)!=null?Ae:"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 tvw-composer-textarea",s.rows=1;let i=(ge=(ee=n==null?void 0:n.theme)==null?void 0:ee.inputFontFamily)!=null?ge:"sans-serif",a=(Qe=($e=n==null?void 0:n.theme)==null?void 0:$e.inputFontWeight)!=null?Qe:"400";s.style.fontFamily=Na(i),s.style.fontWeight=a;let w=3*20;s.style.maxHeight=`${w}px`,s.style.overflowY="auto";let c=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,w);s.style.height=`${te}px`};s.addEventListener("input",c),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 h=(At=n==null?void 0:n.sendButton)!=null?At:{},f=(me=h.useIcon)!=null?me:!1,x=(J=h.iconText)!=null?J:"\u2191",C=h.iconName,E=(ct=h.tooltipText)!=null?ct:"Send message",S=(ut=h.showTooltip)!=null?ut:!1,k=(ft=h.size)!=null?ft:"40px",V=h.backgroundColor,y=h.textColor,O=p("div","tvw-send-button-wrapper"),W=p("button",f?"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(W.type="submit",f){if(W.style.width=k,W.style.height=k,W.style.minWidth=k,W.style.minHeight=k,W.style.fontSize="18px",W.style.lineHeight="1",W.innerHTML="",C){let te=parseFloat(k)||24,Le=y&&typeof y=="string"&&y.trim()?y.trim():"currentColor",Ne=ie(C,te,Le,2);Ne?(W.appendChild(Ne),W.style.color=Le):(W.textContent=x,y?W.style.color=y:W.classList.add("tvw-text-white"))}else W.textContent=x,y?W.style.color=y:W.classList.add("tvw-text-white");V?W.style.backgroundColor=V:W.classList.add("tvw-bg-cw-primary")}else W.textContent=(wt=(Ot=n==null?void 0:n.copy)==null?void 0:Ot.sendButtonLabel)!=null?wt:"Send",y?W.style.color=y:W.classList.add("tvw-text-white");if(h.borderWidth&&(W.style.borderWidth=h.borderWidth,W.style.borderStyle="solid"),h.borderColor&&(W.style.borderColor=h.borderColor),h.paddingX?(W.style.paddingLeft=h.paddingX,W.style.paddingRight=h.paddingX):(W.style.paddingLeft="",W.style.paddingRight=""),h.paddingY?(W.style.paddingTop=h.paddingY,W.style.paddingBottom=h.paddingY):(W.style.paddingTop="",W.style.paddingBottom=""),S&&E){let te=p("div","tvw-send-button-tooltip");te.textContent=E,O.appendChild(te)}O.appendChild(W);let H=(Y=n==null?void 0:n.voiceRecognition)!=null?Y:{},oe=H.enabled===!0,_=null,le=null,X=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(oe&&X){le=p("div","tvw-send-button-wrapper"),_=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),_.type="button",_.setAttribute("aria-label","Start voice recognition");let te=(Ie=H.iconName)!=null?Ie:"mic",Le=(vt=H.iconSize)!=null?vt:k,Ne=parseFloat(Le)||24,q=(yt=H.backgroundColor)!=null?yt:V,de=(Q=H.iconColor)!=null?Q:y;_.style.width=Le,_.style.height=Le,_.style.minWidth=Le,_.style.minHeight=Le,_.style.fontSize="18px",_.style.lineHeight="1";let Be=de||"currentColor",Je=ie(te,Ne,Be,1.5);Je?(_.appendChild(Je),_.style.color=Be):(_.textContent="\u{1F3A4}",_.style.color=Be),q?_.style.backgroundColor=q:_.classList.add("tvw-bg-cw-primary"),de?_.style.color=de:!de&&!y&&_.classList.add("tvw-text-white"),H.borderWidth&&(_.style.borderWidth=H.borderWidth,_.style.borderStyle="solid"),H.borderColor&&(_.style.borderColor=H.borderColor),H.paddingX&&(_.style.paddingLeft=H.paddingX,_.style.paddingRight=H.paddingX),H.paddingY&&(_.style.paddingTop=H.paddingY,_.style.paddingBottom=H.paddingY),le.appendChild(_);let st=(Oe=H.tooltipText)!=null?Oe:"Start voice recognition";if(((bt=H.showTooltip)!=null?bt:!1)&&st){let rt=p("div","tvw-send-button-tooltip");rt.textContent=st,le.appendChild(rt)}}let U=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},Se=U.enabled===!0,N=null,re=null,D=null,Z=null;if(Se){Z=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),Z.style.display="none",D=p("input"),D.type="file",D.accept=((Mt=U.allowedTypes)!=null?Mt:cn).join(","),D.multiple=((j=U.maxFiles)!=null?j:4)>1,D.style.display="none",D.setAttribute("aria-label","Attach files"),re=p("div","tvw-send-button-wrapper"),N=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),N.type="button",N.setAttribute("aria-label",(Ze=U.buttonTooltipText)!=null?Ze:"Attach file");let te=(We=U.buttonIconName)!=null?We:"paperclip",Le=k,Ne=parseFloat(Le)||40,q=Math.round(Ne*.6);N.style.width=Le,N.style.height=Le,N.style.minWidth=Le,N.style.minHeight=Le,N.style.fontSize="18px",N.style.lineHeight="1",N.style.backgroundColor="transparent",N.style.color="var(--cw-primary, #111827)",N.style.border="none",N.style.borderRadius="6px",N.style.transition="background-color 0.15s ease",N.addEventListener("mouseenter",()=>{N.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),N.addEventListener("mouseleave",()=>{N.style.backgroundColor="transparent"});let de=ie(te,q,"currentColor",1.5);de?N.appendChild(de):N.textContent="\u{1F4CE}",N.addEventListener("click",st=>{st.preventDefault(),D==null||D.click()}),re.appendChild(N);let Be=(z=U.buttonTooltipText)!=null?z:"Attach file",Je=p("div","tvw-send-button-tooltip");Je.textContent=Be,re.appendChild(Je)}o.addEventListener("click",te=>{te.target!==W&&te.target!==O&&te.target!==_&&te.target!==le&&te.target!==N&&te.target!==re&&s.focus()}),Z&&(Z.style.gap="8px",o.append(Z)),D&&o.append(D),o.append(s);let ve=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),pe=p("div","tvw-flex tvw-items-center tvw-gap-2");re&&pe.append(re);let Ue=p("div","tvw-flex tvw-items-center tvw-gap-1");le&&Ue.append(le),Ue.append(O),ve.append(pe,Ue),o.append(ve);let it=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Tt=(R=n==null?void 0:n.statusIndicator)!=null?R:{},$t=(he=Tt.visible)!=null?he:!0;return it.style.display=$t?"":"none",it.textContent=(ue=Tt.idleText)!=null?ue:"Online",r.append(t,o,it),{footer:r,suggestions:t,composerForm:o,textarea:s,sendButton:W,sendButtonWrapper:O,micButton:_,micButtonWrapper:le,statusText:it,attachmentButton:N,attachmentButtonWrapper:re,attachmentInput:D,attachmentPreviewsContainer:Z,actionsRow:ve,leftActions:pe,rightActions:Ue}};var Ui=e=>{var d,g,w,c,h,f,x;if(!((g=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?g:!0)){let C=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),E=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),S=(c=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?c:"100%";return C.style.width=S,E.style.width="100%",C.appendChild(E),{wrapper:C,panel:E}}let r=(h=e==null?void 0:e.launcher)!=null?h:{},t=r.position&&Ut[r.position]?Ut[r.position]:Ut["bottom-right"],o=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(x=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?x:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},Ji=(e,n=!0)=>{var f,x,C,E,S,k,V;let r=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(f=e==null?void 0:e.layout)==null?void 0:f.header,o=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,s=t?Bn(e,t,{showClose:n}):rn({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=(E=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?E:"Hello \u{1F44B}";let g=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");g.textContent=(k=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",a.append(d,g);let w=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,w);let c=Rn({config:e}),h=((V=e==null?void 0:e.layout)==null?void 0:V.showFooter)!==!1;return o?xn(r,s,e):(s.header.style.display="none",xn(r,s,e)),r.append(i),h||(c.footer.style.display="none"),r.append(c.footer),{container:r,body:i,messagesWrapper:w,suggestions:c.suggestions,textarea:c.textarea,sendButton:c.sendButton,sendButtonWrapper:c.sendButtonWrapper,micButton:c.micButton,micButtonWrapper:c.micButtonWrapper,composerForm:c.composerForm,statusText:c.statusText,introTitle:d,introSubtitle:g,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:c.footer,attachmentButton:c.attachmentButton,attachmentButtonWrapper:c.attachmentButtonWrapper,attachmentInput:c.attachmentInput,attachmentPreviewsContainer:c.attachmentPreviewsContainer,actionsRow:c.actionsRow,leftActions:c.leftActions,rightActions:c.rightActions}};var Sn=()=>{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 r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(r),e.appendChild(t),e.appendChild(o),e},dr=(e,n,r)=>{let t={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:Sn};if(n){let o=n(t);if(o!==null)return o}return Sn()},Da=(e,n)=>{let r=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=p("img");o.src=t,o.alt=n==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=n==="user"?"U":"A",r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Ki=(e,n)=>{let r=p("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?r.textContent=n.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},ja=(e,n="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},cr=(e,n,r)=>{var f,x,C,E,S,k;let t=(f=n.showCopy)!=null?f:!0,o=(x=n.showUpvote)!=null?x:!0,s=(C=n.showDownvote)!=null?C:!0,i=(E=n.visibility)!=null?E:"hover",a=(S=n.align)!=null?S:"right",d=(k=n.layout)!=null?k:"pill-inside",g={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],c=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${g} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`);c.id=`actions-${e.id}`,c.setAttribute("data-actions-for",e.id);let h=(V,y,O)=>{let W=document.createElement("button");W.className="tvw-message-action-btn",W.setAttribute("aria-label",y),W.setAttribute("title",y),W.setAttribute("data-action",O);let H=ie(V,14,"currentColor",2);return H&&W.appendChild(H),W};return t&&c.appendChild(h("copy","Copy message","copy")),o&&c.appendChild(h("thumbs-up","Upvote","upvote")),s&&c.appendChild(h("thumbs-down","Downvote","downvote")),c},Fn=(e,n,r,t,o,s)=>{var y,O,W,H,oe;let i=r!=null?r:{},a=(y=i.layout)!=null?y:"bubble",d=i.avatar,g=i.timestamp,w=(O=d==null?void 0:d.show)!=null?O:!1,c=(W=g==null?void 0:g.show)!=null?W:!1,h=(H=d==null?void 0:d.position)!=null?H:"left",f=(oe=g==null?void 0:g.position)!=null?oe:"below",x=ja(e.role,a),C=p("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id);let E=document.createElement("div");if(E.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),c&&f==="inline"&&e.createdAt){let _=Ki(e,g);_.classList.add("tvw-ml-2","tvw-inline"),E.appendChild(_)}if(C.appendChild(E),c&&f==="below"&&e.createdAt){let _=Ki(e,g);_.classList.add("tvw-mt-1"),C.appendChild(_)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let _=dr("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);_&&C.appendChild(_)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let _=cr(e,t,o);C.appendChild(_)}if(!w||e.role==="system")return C;let k=p("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),V=Da(d,e.role);return h==="right"||h==="left"&&e.role==="user"?k.append(C,V):k.append(V,C),C.classList.remove("tvw-max-w-[85%]"),C.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),k},Yi=(e,n,r,t,o,s)=>{let i=r!=null?r:{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Fn(e,n,r,t,o,s)};var $n=new Set,Vi=(e,n)=>{let r=$n.has(e),t=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".tvw-border-t");if(!t||!o)return;t.setAttribute("aria-expanded",r?"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=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},ur=e=>{let n=e.reasoning,r=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let t=$n.has(e.id),o=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false"),o.setAttribute("data-expand-header","true"),o.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=Ti(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),w=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=t?"Hide":"Show";let c=p("div","tvw-flex tvw-items-center tvw-ml-auto");c.append(d),o.append(s,c);let h=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");h.style.display=t?"":"none";let f=n.chunks.join(""),x=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return x.textContent=f||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),h.appendChild(x),(()=>{o.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let S=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);S?d.appendChild(S):d.textContent=t?"Hide":"Show",h.style.display=t?"":"none"})(),r.append(o,h),r};var On=new Set,Xi=(e,n,r)=>{var g;let t=On.has(e),o=(g=r==null?void 0:r.toolCall)!=null?g:{},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 w=o.toggleTextColor||o.headerTextColor||"currentColor",c=ie(t?"chevron-up":"chevron-down",16,w,2);c?d.appendChild(c):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},pr=(e,n)=>{var C;let r=e.toolCall,t=(C=n==null?void 0:n.toolCall)!=null?C:{},o=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=On.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=Mi(r),a.appendChild(d);let g=p("div","tvw-flex tvw-items-center"),w=t.toggleTextColor||t.headerTextColor||"currentColor",c=ie(s?"chevron-up":"chevron-down",16,w,2);c?g.appendChild(c):g.textContent=s?"Hide":"Show";let h=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");h.append(g),i.append(a,h);let f=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(f.style.display=s?"":"none",t.contentBackgroundColor&&(f.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(f.style.color=t.contentTextColor),t.contentPaddingX&&(f.style.paddingLeft=t.contentPaddingX,f.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(f.style.paddingTop=t.contentPaddingY,f.style.paddingBottom=t.contentPaddingY),r.name){let E=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?E.style.color=t.contentTextColor:t.headerTextColor&&(E.style.color=t.headerTextColor),E.textContent=r.name,f.appendChild(E)}if(r.args!==void 0){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Arguments";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=nr(r.args),E.append(S,k),f.appendChild(E)}if(r.chunks&&r.chunks.length){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Activity";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=r.chunks.join(`
16
+ `),E.append(S,k),f.appendChild(E)}if(r.status==="complete"&&r.result!==void 0){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Result";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=nr(r.result),E.append(S,k),f.appendChild(E)}if(r.status==="complete"&&typeof r.duration=="number"){let E=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(E.style.color=t.contentTextColor),E.textContent=`Duration: ${r.duration}ms`,f.appendChild(E)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),g.innerHTML="";let E=t.toggleTextColor||t.headerTextColor||"currentColor",S=ie(s?"chevron-up":"chevron-down",16,E,2);S?g.appendChild(S):g.textContent=s?"Hide":"Show",f.style.display=s?"":"none"})(),o.append(i,f),o};var Gi=e=>{let n=[];return{buttons:n,render:(t,o,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(f=>f.role==="user"))return;let w=document.createDocumentFragment(),c=o?o.isStreaming():!1,h=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(f=>{let x=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");x.type="button",x.textContent=f,x.disabled=c,a!=null&&a.fontFamily&&(x.style.fontFamily=h(a.fontFamily)),a!=null&&a.fontWeight&&(x.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(x.style.paddingLeft=a.paddingX,x.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(x.style.paddingTop=a.paddingY,x.style.paddingBottom=a.paddingY),x.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(f))}),w.appendChild(x),n.push(x)}),e.appendChild(w)}}};var as=class{constructor(n=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=r}push(n){var r;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(r=this.store)==null||r.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let r=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let t of r)this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(t.type);return this.totalCaptured=n.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let r=this.getAll();return n>=r.length?r:r.slice(r.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ls=class{constructor(n="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=r}open(){return new Promise((n,r)=>{try{let t=indexedDB.open(this.dbName,1);t.onupgradeneeded=()=>{let o=t.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},t.onsuccess=()=>{this.db=t.result,n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}getAll(){return new Promise((n,r)=>{if(!this.db){n([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{n(i.result)},i.onerror=()=>{r(i.error)}}catch(t){r(t)}})}getCount(){return new Promise((n,r)=>{if(!this.db){n(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}clear(){return new Promise((n,r)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,r)=>{try{let t=indexedDB.deleteDatabase(this.dbName);t.onsuccess=()=>{n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}};function Nn(e,n){n&&n.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var _a={flow_:{bg:"#dcfce7",text:"#166534"},step_:{bg:"#dbeafe",text:"#1e40af"},reason_:{bg:"#ffedd5",text:"#9a3412"},tool_:{bg:"#f3e8ff",text:"#6b21a8"},agent_:{bg:"#ccfbf1",text:"#115e59"},error:{bg:"#fecaca",text:"#991b1b"}},qa={bg:"#f3f4f6",text:"#4b5563"},za=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ua=100;function Ja(e,n){let r={..._a,...n};if(r[e])return r[e];for(let t of Object.keys(r))if(t.endsWith("_")&&e.startsWith(t))return r[t];return qa}function Ka(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Ya(e){let n=new Date(e),r=String(n.getHours()).padStart(2,"0"),t=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${r}:${t}:${o}.${s}`}function Va(e,n){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let t of n){let o=t.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Xa(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),r()})}function Ga(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Qa(e,n,r){let t,o;try{o=JSON.parse(e.payload),t=JSON.stringify(o,null,2)}catch{o=e.payload,t=e.payload}let s=n.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=p("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),d=p("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return d.textContent=t,a.appendChild(d),a}}function gr(e,n,r,t,o,s,i,a){var h;let d=o.has(e.id),g=p("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");Nn(g,(h=t.classNames)==null?void 0:h.eventRow);let w=i.find(f=>f.renderEventStreamRow);if(w!=null&&w.renderEventStreamRow&&a){let f=w.renderEventStreamRow({event:e,index:n,config:a,defaultRenderer:()=>c(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return g.appendChild(f),g}return g.appendChild(c()),g;function c(){var U,Se;let f=p("div",""),x=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-3 tvw-py-3 hover:tvw-bg-cw-container tvw-cursor-pointer tvw-group");x.setAttribute("data-event-id",e.id);let C=p("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),E=ie(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&C.appendChild(E);let S=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),k=(U=t.timestampFormat)!=null?U:"relative";S.textContent=k==="relative"?Ka(e.timestamp,r):Ya(e.timestamp);let V=null;t.showSequenceNumbers!==!1&&(V=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),V.textContent=String(n+1));let y=Ja(e.type,t.badgeColors),O=p("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded tvw-text-[11px] tvw-font-mono tvw-font-medium tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-border");O.style.backgroundColor=y.bg,O.style.color=y.text,O.style.borderColor=y.text+"50",O.textContent=e.type;let W=(Se=t.descriptionFields)!=null?Se:za,H=Va(e.payload,W),oe=null;H&&(oe=p("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),oe.textContent=H);let _=p("div","tvw-flex-1 tvw-min-w-0"),le=p("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),X=ie("clipboard","12px","currentColor",1.5);return X&&le.appendChild(X),le.addEventListener("click",async N=>{N.stopPropagation(),await Xa(Ga(e)),le.innerHTML="";let re=ie("check","12px","currentColor",1.5);re&&le.appendChild(re),setTimeout(()=>{le.innerHTML="";let D=ie("clipboard","12px","currentColor",1.5);D&&le.appendChild(D)},1500)}),x.appendChild(C),x.appendChild(S),V&&x.appendChild(V),x.appendChild(O),oe&&x.appendChild(oe),x.appendChild(_),x.appendChild(le),f.appendChild(x),d&&f.appendChild(Qa(e,i,a)),f}}function Qi(e){var g,w;let{buffer:n,getFullHistory:r,onClose:t,config:o,plugins:s=[]}=e,i=(w=(g=o==null?void 0:o.features)==null?void 0:g.eventStream)!=null?w:{},a=s.find(c=>c.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let c=a.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>d().element,onClose:t});if(c)return{element:c,update:()=>{},destroy:()=>{}}}return d();function d(){let c=i.classNames,h=p("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");Nn(h,c==null?void 0:c.panel);let f=[],x="",C="",E=null,S=[],k={},V=0,y=!1,O=0,W=0,H=!1,oe=null,_=!1,le=0,X=new Set,U=new Map,Se="",N="",re=null,D,Z,ve,pe,Ue;function it(){let z=p("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),R=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-4 tvw-py-3 tvw-pb-0 tvw-border-cw-divider tvw-bg-cw-surface tvw-overflow-hidden");Nn(R,c==null?void 0:c.headerBar);let he=p("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");he.textContent="Events",D=p("span","tvw-text-[11px] tvw-font-mono tvw-bg-cw-container tvw-text-cw-muted tvw-px-2 tvw-py-0.5 tvw-rounded tvw-border tvw-border-cw-border"),D.textContent="0";let ue=p("div","tvw-flex-1");Z=p("select","tvw-text-xs tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded tvw-px-2.5 tvw-py-1 tvw-text-cw-primary tvw-cursor-pointer");let te=p("option","");te.value="",te.textContent="All events",Z.appendChild(te),ve=p("button","tvw-inline-flex tvw-items-center tvw-gap-1.5 tvw-rounded tvw-text-xs tvw-text-cw-muted hover:tvw-bg-cw-container hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border tvw-border-cw-border tvw-bg-cw-surface tvw-flex-shrink-0 tvw-px-2.5 tvw-py-1"),ve.type="button",ve.title="Copy All";let Ne=ie("clipboard-copy","12px","currentColor",1.5);Ne&&ve.appendChild(Ne);let q=p("span","tvw-text-xs");q.textContent="Copy All",ve.appendChild(q),R.appendChild(he),R.appendChild(D),R.appendChild(ue),R.appendChild(Z),R.appendChild(ve);let de=p("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");Nn(de,c==null?void 0:c.searchBar);let Be=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),Je=p("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Be&&Je.appendChild(Be),pe=p("input","tvw-text-sm tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded-md tvw-pl-8 tvw-pr-3 tvw-py-1 tvw-w-full tvw-text-cw-primary"),Nn(pe,c==null?void 0:c.searchInput),pe.type="text",pe.placeholder="Search event payloads...",Ue=p("button","tvw-absolute tvw-right-5 tvw-top-1/2 tvw--translate-y-1/2 tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-0 tvw-leading-none"),Ue.type="button",Ue.style.display="none";let st=ie("x","12px","currentColor",2);return st&&Ue.appendChild(st),de.appendChild(Je),de.appendChild(pe),de.appendChild(Ue),z.appendChild(R),z.appendChild(de),z}let Tt,$t=s.find(z=>z.renderEventStreamToolbar);if($t!=null&&$t.renderEventStreamToolbar&&o){let z=$t.renderEventStreamToolbar({config:o,defaultRenderer:()=>it(),eventCount:n.getSize(),filteredCount:0,onFilterChange:R=>{x=R,ut(),wt()},onSearchChange:R=>{C=R,ut(),wt()}});Tt=z!=null?z:it()}else Tt=it();let Fe=p("div","tvw-text-xs tvw-text-cw-muted tvw-text-center tvw-py-0.5 tvw-px-4 tvw-bg-cw-container tvw-border-b tvw-border-cw-divider tvw-italic tvw-flex-shrink-0");Fe.style.display="none";let Ae=p("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ee=p("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ee.style.height="100%";let ge=p("div","tvw-absolute tvw-bottom-3 tvw-left-1/2 tvw-transform tvw--translate-x-1/2 tvw-bg-cw-accent tvw-text-white tvw-text-xs tvw-px-3 tvw-py-1.5 tvw-rounded-full tvw-cursor-pointer tvw-shadow-md tvw-z-10 tvw-flex tvw-items-center tvw-gap-1");Nn(ge,c==null?void 0:c.scrollIndicator),ge.style.display="none";let $e=ie("arrow-down","12px","currentColor",2);$e&&ge.appendChild($e);let Qe=p("span","");ge.appendChild(Qe);let At=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");At.style.display="none",Ae.appendChild(ee),Ae.appendChild(At),Ae.appendChild(ge),h.setAttribute("tabindex","0"),h.appendChild(Tt),h.appendChild(Fe),h.appendChild(Ae);function me(){let z=n.getAll(),R={};for(let q of z)R[q.type]=(R[q.type]||0)+1;let he=Object.keys(R).sort(),ue=he.length!==S.length||!he.every((q,de)=>q===S[de]),te=!ue&&he.some(q=>R[q]!==k[q]),Le=z.length!==Object.values(k).reduce((q,de)=>q+de,0);if(!ue&&!te&&!Le||(S=he,k=R,!Z))return;let Ne=Z.value;if(Z.options[0].textContent="All events",ue){for(;Z.options.length>1;)Z.remove(1);for(let q of he){let de=p("option","");de.value=q,de.textContent=`${q} (${R[q]||0})`,Z.appendChild(de)}Ne&&he.includes(Ne)?Z.value=Ne:Ne&&(Z.value="",x="")}else for(let q=1;q<Z.options.length;q++){let de=Z.options[q];de.textContent=`${de.value} (${R[de.value]||0})`}}function J(){let z=n.getAll();if(x&&(z=z.filter(R=>R.type===x)),C){let R=C.toLowerCase();z=z.filter(he=>he.type.toLowerCase().includes(R)||he.payload.toLowerCase().includes(R))}return z}function ct(){return x!==""||C!==""}function ut(){V=0,O=0,y=!1,ge.style.display="none"}function ft(z){X.has(z)?X.delete(z):X.add(z),re=z;let R=ee.scrollTop,he=y;_=!0,y=!0,wt(),ee.scrollTop=R,y=he,_=!1}function Ot(){return ee.scrollHeight-ee.scrollTop-ee.clientHeight<=50}function wt(){W=Date.now(),H=!1,me();let z=n.getEvictedCount();z>0?(Fe.textContent=`${z.toLocaleString()} older events truncated`,Fe.style.display=""):Fe.style.display="none",f=J();let R=f.length,he=n.getSize()>0;D&&(D.textContent=String(n.getSize())),R===0&&he&&ct()?(At.textContent=C?`No events matching '${C}'`:"No events matching filter",At.style.display="",ee.style.display="none"):(At.style.display="none",ee.style.display=""),ve&&(ve.title=ct()?`Copy Filtered (${R})`:"Copy All"),y&&R>V&&(O+=R-V,Qe.textContent=`${O} new event${O===1?"":"s"}`,ge.style.display=""),V=R;let ue=n.getAll(),te=ue.length>0?ue[0].timestamp:0,Le=new Set(f.map(de=>de.id));for(let de of X)Le.has(de)||X.delete(de);let Ne=x!==Se||C!==N,q=U.size===0&&f.length>0;if(Ne||q||f.length===0){ee.innerHTML="",U.clear();let de=document.createDocumentFragment();for(let Be=0;Be<f.length;Be++){let Je=gr(f[Be],Be,te,i,X,ft,s,o);U.set(f[Be].id,Je),de.appendChild(Je)}ee.appendChild(de),Se=x,N=C,re=null}else{if(re!==null){let Be=U.get(re);if(Be&&Be.parentNode===ee){let Je=f.findIndex(st=>st.id===re);if(Je>=0){let st=gr(f[Je],Je,te,i,X,ft,s,o);ee.insertBefore(st,Be),Be.remove(),U.set(re,st)}}re=null}let de=new Set(f.map(Be=>Be.id));for(let[Be,Je]of U)de.has(Be)||(Je.remove(),U.delete(Be));for(let Be=0;Be<f.length;Be++){let Je=f[Be];if(!U.has(Je.id)){let st=gr(Je,Be,te,i,X,ft,s,o);U.set(Je.id,st),ee.appendChild(st)}}}y||(ee.scrollTop=ee.scrollHeight)}function Y(){if(Date.now()-W>=Ua){oe!==null&&(cancelAnimationFrame(oe),oe=null),wt();return}H||(H=!0,oe=requestAnimationFrame(()=>{oe=null,wt()}))}let Ie=(z,R)=>{if(!ve)return;ve.innerHTML="";let he=ie(z,"12px","currentColor",1.5);he&&ve.appendChild(he);let ue=p("span","tvw-text-xs");ue.textContent="Copy All",ve.appendChild(ue),setTimeout(()=>{ve.innerHTML="";let te=ie("clipboard-copy","12px","currentColor",1.5);te&&ve.appendChild(te);let Le=p("span","tvw-text-xs");Le.textContent="Copy All",ve.appendChild(Le),ve.disabled=!1},R)},vt=async()=>{if(ve){ve.disabled=!0;try{let z;ct()?z=f:z=r?await r():n.getAll();let R=z.map(he=>{try{return JSON.parse(he.payload)}catch{return he.payload}});await navigator.clipboard.writeText(JSON.stringify(R,null,2)),Ie("check",1500)}catch{Ie("x",1500)}}},yt=()=>{Z&&(x=Z.value,ut(),wt())},Q=()=>{!pe||!Ue||(Ue.style.display=pe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{C=pe.value,ut(),wt()},150))},Oe=()=>{!pe||!Ue||(pe.value="",C="",Ue.style.display="none",E&&clearTimeout(E),ut(),wt())},bt=()=>{if(_)return;let z=ee.scrollTop,R=z>le;le=z,Ot()&&R?(y=!1,O=0,ge.style.display="none"):Ot()||(y=!0)},Wt=z=>{z.deltaY<0&&(y=!0)},Mt=()=>{ee.scrollTop=ee.scrollHeight,y=!1,O=0,ge.style.display="none"},j=z=>{let R=z.target;if(!R||R.closest("button"))return;let he=R.closest("[data-event-id]");if(!he)return;let ue=he.getAttribute("data-event-id");ue&&ft(ue)},Ze=z=>{if((z.metaKey||z.ctrlKey)&&z.key==="f"){z.preventDefault(),pe==null||pe.focus(),pe==null||pe.select();return}z.key==="Escape"&&(pe&&document.activeElement===pe?(Oe(),pe.blur(),h.focus()):t&&t())};ve&&ve.addEventListener("click",vt),Z&&Z.addEventListener("change",yt),pe&&pe.addEventListener("input",Q),Ue&&Ue.addEventListener("click",Oe),ee.addEventListener("scroll",bt),ee.addEventListener("wheel",Wt,{passive:!0}),ee.addEventListener("click",j),ge.addEventListener("click",Mt),h.addEventListener("keydown",Ze);function We(){E&&clearTimeout(E),oe!==null&&(cancelAnimationFrame(oe),oe=null),H=!1,U.clear(),ve&&ve.removeEventListener("click",vt),Z&&Z.removeEventListener("change",yt),pe&&pe.removeEventListener("input",Q),Ue&&Ue.removeEventListener("click",Oe),ee.removeEventListener("scroll",bt),ee.removeEventListener("wheel",Wt),ee.removeEventListener("click",j),ge.removeEventListener("click",Mt),h.removeEventListener("keydown",Ze)}return{element:h,update:Y,destroy:We}}}var Zi={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"}},mr=(e,n,r,t)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,C,E;if(s.dataset.enhanced==="true")return;let i=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let a=(C=Zi[i])!=null?C:Zi.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),g=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(g.textContent=a.title,d.appendChild(g),a.description){let S=p("p","tvw-text-sm tvw-text-cw-muted");S.textContent=a.description,d.appendChild(S)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(S=>{var W,H;let k=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");k.htmlFor=`${n.id}-${i}-${S.name}`;let V=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");V.textContent=S.label,k.appendChild(V);let y=(W=S.type)!=null?W:"text",O;y==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=y),O.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",O.id=`${n.id}-${i}-${S.name}`,O.name=S.name,O.placeholder=(H=S.placeholder)!=null?H:"",S.required&&(O.required=!0),k.appendChild(O),w.appendChild(k)});let c=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),h=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=(E=a.submitLabel)!=null?E:"Submit",c.appendChild(h),c.appendChild(f),w.appendChild(c),s.replaceChildren(d,w),w.addEventListener("submit",async S=>{var O,W;S.preventDefault();let k=(O=r.formEndpoint)!=null?O:"/form",V=new FormData(w),y={};V.forEach((H,oe)=>{y[oe]=H}),y.type=i,f.disabled=!0,h.textContent="Submitting\u2026";try{let H=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let oe=await H.json();h.textContent=(W=oe.message)!=null?W:"Thanks! We'll be in touch soon.",oe.success&&oe.nextPrompt&&await t.sendMessage(String(oe.nextPrompt))}catch(H){h.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var hr=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var t;let r=this.plugins.get(n);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let t=new Set(n.map(s=>s.id));return[...r.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 r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},ds=new hr;var fr={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"},wr={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"},et={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:fr,darkTheme:wr,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 Ns(e){var n,r,t,o,s,i,a,d,g,w,c,h,f,x,C,E,S,k,V;return e?{...et,...e,theme:{...et.theme,...e.theme},darkTheme:{...et.darkTheme,...e.darkTheme},launcher:{...et.launcher,...e.launcher,clearChat:{...(n=et.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...et.copy,...e.copy},sendButton:{...et.sendButton,...e.sendButton},statusIndicator:{...et.statusIndicator,...e.statusIndicator},voiceRecognition:{...et.voiceRecognition,...e.voiceRecognition},features:{...et.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:et.suggestionChips,suggestionChipsConfig:{...et.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...et.layout,...e.layout,header:{...(o=et.layout)==null?void 0:o.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=et.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(g=(d=et.layout)==null?void 0:d.messages)==null?void 0:g.avatar,...(c=(w=e.layout)==null?void 0:w.messages)==null?void 0:c.avatar},timestamp:{...(f=(h=et.layout)==null?void 0:h.messages)==null?void 0:f.timestamp,...(C=(x=e.layout)==null?void 0:x.messages)==null?void 0:C.timestamp}},slots:{...(E=et.layout)==null?void 0:E.slots,...(S=e.layout)==null?void 0:S.slots}},markdown:{...et.markdown,...e.markdown,options:{...(k=et.markdown)==null?void 0:k.options,...(V=e.markdown)==null?void 0:V.options}},messageActions:{...et.messageActions,...e.messageActions}}:et}var ea=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=e.get(o))==null||i.delete(s)};return{on:n,off:r,emit:(o,s)=>{var i;(i=e.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Za=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},el=e=>{let n=e.trim(),r=n.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(r,o+1)}return null},cs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Za(e),r=el(n);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},vr=e=>typeof e=="string"?e:e==null?"":String(e),An={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:vr(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=vr(r.element);if(t&&((o=n.document)!=null&&o.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:vr(r.text)}}},ta=e=>Array.isArray(e)?e.map(n=>String(n)):[],us=e=>{let n=new Set(ta(e.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(ta(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((g,w)=>g||(w==null?void 0:w({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 g of e.handlers)if(g)try{let w=()=>{e.emit("action:resubmit",d)},c=g(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:w});if(!c)continue;if(c.handled){let h=c.persistMessage!==!1;return{text:c.displayText!==void 0?c.displayText:"",persist:h,resubmit:c.resubmit}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:r}};var tl=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}},nl=e=>e.map(n=>({...n,streaming:!1})),Ds=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?tl(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?nl(r.messages):void 0};t.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var yr=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}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(([r,t])=>{this.register(r,t)})}},Dn=new yr;var jn=require("partial-json");function sl(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function rl(e,n){if(!sl(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:n}}function js(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e;try{let o=(0,jn.parse)(r,jn.STR|jn.OBJ),s=rl(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function na(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _s(e,n){let{config:r,message:t,onPropsUpdate:o}=n,s=Dn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:a=>{o&&o(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function sa(){let e=js();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function qs(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 zs(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 ol=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Us(e){let{onSubmit:n,onDismiss:r,title:t="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:g=ol}=e,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-csat",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Customer satisfaction feedback");let c=null,h=document.createElement("div");h.className="tvw-feedback-content";let f=document.createElement("div");f.className="tvw-feedback-header";let x=document.createElement("h3");x.className="tvw-feedback-title",x.textContent=t,f.appendChild(x);let C=document.createElement("p");C.className="tvw-feedback-subtitle",C.textContent=o,f.appendChild(C),h.appendChild(f);let E=document.createElement("div");E.className="tvw-feedback-rating tvw-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let W=1;W<=5;W++){let H=document.createElement("button");H.type="button",H.className="tvw-feedback-rating-btn tvw-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${g[W-1]}`),H.title=g[W-1],H.dataset.rating=String(W),H.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
- `,P.addEventListener("click",()=>{c=W,A.forEach((se,_)=>{let oe=_<W;se.classList.toggle("selected",oe),se.setAttribute("aria-checked",_===W-1?"true":"false")})}),A.push(P),T.appendChild(P)}m.appendChild(T);let L=null;if(d){let W=document.createElement("div");W.className="tvw-feedback-comment-container",L=document.createElement("textarea"),L.className="tvw-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),W.appendChild(L),m.appendChild(W)}let V=document.createElement("div");V.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",()=>{r==null||r(),w.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(c===null){T.classList.add("tvw-feedback-shake"),setTimeout(()=>T.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let W=(L==null?void 0:L.value.trim())||void 0;await n(c,W),w.remove()}catch(W){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",W)}}),V.appendChild(v),V.appendChild(O),m.appendChild(V),w.appendChild(m),w}function $s(e){let{onSubmit:n,onDismiss:r,title:t="How likely are you to recommend us?",subtitle:o="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:g="Not likely",highLabel:w="Very likely"}=e,c=document.createElement("div");c.className="tvw-feedback-container tvw-feedback-nps",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Net Promoter Score feedback");let m=null,f=document.createElement("div");f.className="tvw-feedback-content";let x=document.createElement("div");x.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=t,x.appendChild(C);let T=document.createElement("p");T.className="tvw-feedback-subtitle",T.textContent=o,x.appendChild(T),f.appendChild(x);let A=document.createElement("div");A.className="tvw-feedback-rating tvw-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="tvw-feedback-labels";let V=document.createElement("span");V.className="tvw-feedback-label-low",V.textContent=g;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=w,L.appendChild(V),L.appendChild(v);let O=document.createElement("div");O.className="tvw-feedback-numbers";let W=[];for(let X=0;X<=10;X++){let U=document.createElement("button");U.type="button",U.className="tvw-feedback-rating-btn tvw-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${X} out of 10`),U.textContent=String(X),U.dataset.rating=String(X),X<=6?U.classList.add("tvw-feedback-detractor"):X<=8?U.classList.add("tvw-feedback-passive"):U.classList.add("tvw-feedback-promoter"),U.addEventListener("click",()=>{m=X,W.forEach((xe,N)=>{xe.classList.toggle("selected",N===X),xe.setAttribute("aria-checked",N===X?"true":"false")})}),W.push(U),O.appendChild(U)}A.appendChild(L),A.appendChild(O),f.appendChild(A);let P=null;if(d){let X=document.createElement("div");X.className="tvw-feedback-comment-container",P=document.createElement("textarea"),P.className="tvw-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),X.appendChild(P),f.appendChild(X)}let se=document.createElement("div");se.className="tvw-feedback-actions";let _=document.createElement("button");_.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-skip",_.textContent=a,_.addEventListener("click",()=>{r==null||r(),c.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="tvw-feedback-btn tvw-feedback-btn-submit",oe.textContent=i,oe.addEventListener("click",async()=>{if(m===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let X=(P==null?void 0:P.value.trim())||void 0;await n(m,X),c.remove()}catch(X){oe.disabled=!1,oe.textContent=i,console.error("[NPS Feedback] Failed to submit:",X)}}),se.appendChild(_),se.appendChild(oe),f.appendChild(se),c.appendChild(f),c}var $n="persona-chat-history",il=30*1e3;function al(e){var n,r,t,o,s,i,a,d,g;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(t=e.persist)==null?void 0:t.openState)!=null?o:!0,voiceState:(i=(s=e.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=e.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(g=e.clearOnChatClear)!=null?g:!0}:null}function ll(e){try{let n=e==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var ur=e=>!e||typeof e!="object"?{}:{...e},ra=e=>e.map(n=>({...n,streaming:!1})),oa=(e,n,r)=>{let t=e!=null&&e.markdown?Zn(e.markdown):null;return o=>{var a,d,g;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(n){let w=n.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});w!==null&&(s=w.text,w.persist||(o.message.__skipPersist=!0),w.resubmit&&!o.streaming&&r&&r())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(g=i!=null?i:o.text)!=null?g:""}):t?t(s):vs(s)}},Os=(e,n,r)=>{var Ne,qe,ct,ze,Ct,Bt,_t,hr,fr,wr,vr,yr,br,Cr,xr,Sr,Ar,Er,Tr,Mr,kr,Lr,Wr,Ir,Pr,Hr,Br,Rr,Fr,$r,Or,Nr;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let t=Ws(n),o=ss.getForInstance(t.plugins);t.components&&Rn.registerAll(t.components);let s=ea(),i=(Ne=t.storageAdapter)!=null?Ne:Is(),a={},d=null,g=l=>{if(t.onStateLoaded)try{return t.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(u=>{let b=u!=null?u:{messages:[],metadata:{}};return g(b)});else{let u=l!=null?l:{messages:[],metadata:{}},b=g(u);b.metadata&&(a=ur(b.metadata)),(qe=b.messages)!=null&&qe.length&&(t={...t,initialMessages:b.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(t.onStateLoaded)try{let l=g({messages:[],metadata:{}});(ct=l.messages)!=null&&ct.length&&(t={...t,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let w=()=>a,c=l=>{var b;a=(b=l({...a}))!=null?b:{},qn()},m=t.actionParsers&&t.actionParsers.length?t.actionParsers:[rs],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[bn.message,bn.messageAndClick],x=os({parsers:m,handlers:f,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null});x.syncFromMetadata();let C=(Ct=(ze=t.launcher)==null?void 0:ze.enabled)!=null?Ct:!0,T=(_t=(Bt=t.launcher)==null?void 0:Bt.autoExpand)!=null?_t:!1,A=T,L=C,V=(fr=(hr=t.layout)==null?void 0:hr.header)==null?void 0:fr.layout,v=C?T:!0,O=!1,W=null,P=()=>{O=!0,W&&clearTimeout(W),W=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},se=oa(t,x,P),_=(vr=(wr=t.features)==null?void 0:wr.showReasoning)!=null?vr:!0,oe=(br=(yr=t.features)==null?void 0:yr.showToolCalls)!=null?br:!0,X=(xr=(Cr=t.features)==null?void 0:Cr.showEventStreamToggle)!=null?xr:!1,xe=`${(Ar=typeof t.persistState=="object"?(Sr=t.persistState)==null?void 0:Sr.keyPrefix:void 0)!=null?Ar:"persona-"}event-stream`,N=X?new ns(xe):null,ne=(Mr=(Tr=(Er=t.features)==null?void 0:Er.eventStream)==null?void 0:Tr.maxEvents)!=null?Mr:2e3,D=X?new ts(ne,N):null,Z=null,fe=!1,ce=null,Ue=0;N==null||N.open().then(()=>D==null?void 0:D.restore()).catch(l=>{t.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let dt={onCopy:l=>{var u,b;s.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(k=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",k)}),(b=(u=t.messageActions)==null?void 0:u.onCopy)==null||b.call(u,l)},onFeedback:l=>{var u,b;s.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(k=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",k)}),(b=(u=t.messageActions)==null?void 0:u.onFeedback)==null||b.call(u,l)}},At=(kr=t.statusIndicator)!=null?kr:{},Ft=l=>{var u,b,k,E;return l==="idle"?(u=At.idleText)!=null?u:It.idle:l==="connecting"?(b=At.connectingText)!=null?b:It.connecting:l==="connected"?(k=At.connectedText)!=null?k:It.connected:l==="error"?(E=At.errorText)!=null?E:It.error:It[l]},{wrapper:Re,panel:Se}=Ui(t),ee=Ji(t,C),{container:ue,body:Fe,messagesWrapper:Qe,suggestions:St,textarea:pe,sendButton:J,sendButtonWrapper:pt,composerForm:gt,statusText:ft,introTitle:$t,introSubtitle:wt,closeButton:Y,iconHolder:Le,headerTitle:vt,headerSubtitle:yt,header:Q,footer:$e,actionsRow:bt,leftActions:Lt,rightActions:Et}=ee,j=ee.micButton,Ze=ee.micButtonWrapper,ke=ee.attachmentButton,z=ee.attachmentButtonWrapper,R=ee.attachmentInput,ge=ee.attachmentPreviewsContainer,de=null;(Lr=t.attachments)!=null&&Lr.enabled&&R&&ge&&(de=wn.fromConfig(t.attachments),de.setPreviewsContainer(ge),R.addEventListener("change",l=>{let u=l.target;de==null||de.handleFileSelect(u.files),u.value=""}));let te=o.find(l=>l.renderHeader);if(te!=null&&te.renderHeader){let l=te.renderHeader({config:t,defaultRenderer:()=>{let u=tn({config:t,showClose:C});return vn(ue,u,t),u.header},onClose:()=>ot(!1,"user")});if(l){let u=ue.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),Q=l)}}let Te=()=>{var u,b,k,E;if(!D)return;if(fe=!0,!Z&&D&&(Z=Qi({buffer:D,getFullHistory:()=>D.getAllFromStore(),onClose:()=>Oe(),config:t,plugins:o})),Z&&(Fe.style.display="none",(u=$e.parentNode)==null||u.insertBefore(Z.element,$e),Z.update()),q){q.classList.remove("tvw-text-cw-muted"),q.classList.add("tvw-text-cw-accent"),q.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let $=(E=(k=(b=t.features)==null?void 0:b.eventStream)==null?void 0:k.classNames)==null?void 0:E.toggleButtonActive;$&&$.split(/\s+/).forEach(ve=>ve&&q.classList.add(ve))}let l=()=>{if(!fe)return;let $=Date.now();$-Ue>=200&&(Z==null||Z.update(),Ue=$),ce=requestAnimationFrame(l)};Ue=0,ce=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},Oe=()=>{var l,u,b;if(fe){if(fe=!1,Z&&Z.element.remove(),Fe.style.display="",q){q.classList.remove("tvw-text-cw-accent"),q.classList.add("tvw-text-cw-muted"),q.style.boxShadow="";let k=(b=(u=(l=t.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:b.toggleButtonActive;k&&k.split(/\s+/).forEach(E=>E&&q.classList.remove(E))}ce!==null&&(cancelAnimationFrame(ce),ce=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},q=null;if(X){let l=(Ir=(Wr=t.features)==null?void 0:Wr.eventStream)==null?void 0:Ir.classNames,u="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 tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");q=p("button",u),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let b=re("activity","18px","currentColor",1.5);b&&q.appendChild(b);let k=ee.clearChatButtonWrapper,E=ee.closeButtonWrapper,$=k||E;$&&$.parentNode===Q?Q.insertBefore(q,$):Q.appendChild(q),q.addEventListener("click",()=>{fe?Oe():Te()})}let ae=o.find(l=>l.renderComposer);if(ae!=null&&ae.renderComposer){let l=ae.renderComposer({config:t,defaultRenderer:()=>Wn({config:t}).footer,onSubmit:u=>{F&&!F.isStreaming()&&F.sendMessage(u)},disabled:!1});l&&($e.replaceWith(l),$e=l)}(()=>{var k,E;let l=(E=(k=t.layout)==null?void 0:k.slots)!=null?E:{},u=$=>{switch($){case"body-top":return ue.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Qe;case"footer-top":return St;case"composer":return gt;case"footer-bottom":return ft;default:return null}},b=($,ve)=>{var le;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Q.insertBefore(ve,Q.firstChild);else if($==="header-right")Q.appendChild(ve);else{let ye=Q.querySelector(".tvw-flex-col");ye?(le=ye.parentNode)==null||le.insertBefore(ve,ye.nextSibling):Q.appendChild(ve)}break;case"body-top":{let ye=Fe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ye?ye.replaceWith(ve):Fe.insertBefore(ve,Fe.firstChild);break}case"body-bottom":Fe.appendChild(ve);break;case"footer-top":St.replaceWith(ve);break;case"footer-bottom":ft.replaceWith(ve);break;default:break}};for(let[$,ve]of Object.entries(l))if(ve)try{let le=ve({config:t,defaultContent:()=>u($)});le&&b($,le)}catch(le){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,le)}})();let Je=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let k=b.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!k)return;let E=k.getAttribute("data-message-id");if(!E)return;let $=b.getAttribute("data-bubble-type");$==="reasoning"?(Pn.has(E)?Pn.delete(E):Pn.add(E),Vi(E,k)):$==="tool"&&(Hn.has(E)?Hn.delete(E):Hn.add(E),Xi(E,k,t))};Qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),Qe.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))});let it=new Map;Qe.addEventListener("click",l=>{var ve;let b=l.target.closest(".tvw-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let k=b.closest("[data-actions-for]");if(!k)return;let E=k.getAttribute("data-actions-for");if(!E)return;let $=b.getAttribute("data-action");if($==="copy"){let ye=F.getMessages().find(Ae=>Ae.id===E);if(ye&&dt.onCopy){let Ae=ye.content||"";navigator.clipboard.writeText(Ae).then(()=>{b.classList.add("tvw-message-action-success");let be=re("check",14,"currentColor",2);be&&(b.innerHTML="",b.appendChild(be)),setTimeout(()=>{b.classList.remove("tvw-message-action-success");let Ie=re("copy",14,"currentColor",2);Ie&&(b.innerHTML="",b.appendChild(Ie))},2e3)}).catch(be=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",be)}),dt.onCopy(ye)}}else if($==="upvote"||$==="downvote")if(((ve=it.get(E))!=null?ve:null)===$)it.delete(E),b.classList.remove("tvw-message-action-active");else{let Ae=$==="upvote"?"downvote":"upvote",be=k.querySelector(`[data-action="${Ae}"]`);be&&be.classList.remove("tvw-message-action-active"),it.set(E,$),b.classList.add("tvw-message-action-active");let G=F.getMessages().find(I=>I.id===E);G&&dt.onFeedback&&dt.onFeedback({type:$,messageId:G.id,message:G})}}),Se.appendChild(ue),e.appendChild(Re);let xn=()=>{var he,Ce,Xe,Pe,mt,Wt,K,_e,Kt,qt,on,ms,Us,ut,hs,Kn;let l=(Ce=(he=t.launcher)==null?void 0:he.sidebarMode)!=null?Ce:!1,u=l||((Pe=(Xe=t.launcher)==null?void 0:Xe.fullHeight)!=null?Pe:!1),b=(mt=t.theme)!=null?mt:{},k=(K=(Wt=t.launcher)==null?void 0:Wt.position)!=null?K:"bottom-left",E=k==="bottom-left"||k==="top-left",$=l?"none":"1px solid var(--tvw-cw-border)",ve=l?E?"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)",le=l?"0":"16px",ye=(_e=b.panelBorder)!=null?_e:$,Ae=(Kt=b.panelShadow)!=null?Kt:ve,be=(qt=b.panelBorderRadius)!=null?qt:le;e.style.cssText="",Re.style.cssText="",Se.style.cssText="",ue.style.cssText="",Fe.style.cssText="",$e.style.cssText="";let Ie=(ms=(on=t==null?void 0:t.launcher)==null?void 0:on.width)!=null?ms:t==null?void 0:t.launcherWidth,G=Ie!=null?Ie:"min(400px, calc(100vw - 24px))";l||(Se.style.width=G,Se.style.maxWidth=G),Se.style.boxShadow=Ae,Se.style.borderRadius=be,ue.style.border=ye,ue.style.borderRadius=be;let I=((Us=t.launcher)==null?void 0:Us.enabled)===!1;if(u&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",Re.style.display="flex",Re.style.flexDirection="column",Re.style.flex="1 1 0%",Re.style.minHeight="0",Re.style.maxHeight="100%",Re.style.height="100%",I&&(Re.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",Se.style.overflow="hidden",ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.overflowY="auto",$e.style.flexShrink="0"),Re.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&&!I&&((ut=zt[k])!=null?ut:zt["bottom-right"]).split(" ").forEach(gn=>Re.classList.add(gn)),l){let pn=(Kn=(hs=t.launcher)==null?void 0:hs.sidebarWidth)!=null?Kn:"420px";Re.style.cssText=`
20
+ `,H.addEventListener("click",()=>{c=W,S.forEach((oe,_)=>{let le=_<W;oe.classList.toggle("selected",le),oe.setAttribute("aria-checked",_===W-1?"true":"false")})}),S.push(H),E.appendChild(H)}h.appendChild(E);let k=null;if(d){let W=document.createElement("div");W.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"),W.appendChild(k),h.appendChild(W)}let V=document.createElement("div");V.className="tvw-feedback-actions";let y=document.createElement("button");y.type="button",y.className="tvw-feedback-btn tvw-feedback-btn-skip",y.textContent=a,y.addEventListener("click",()=>{r==null||r(),w.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(c===null){E.classList.add("tvw-feedback-shake"),setTimeout(()=>E.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let W=(k==null?void 0:k.value.trim())||void 0;await n(c,W),w.remove()}catch(W){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",W)}}),V.appendChild(y),V.appendChild(O),h.appendChild(V),w.appendChild(h),w}function Js(e){let{onSubmit:n,onDismiss:r,title:t="How likely are you to recommend us?",subtitle:o="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:g="Not likely",highLabel:w="Very likely"}=e,c=document.createElement("div");c.className="tvw-feedback-container tvw-feedback-nps",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Net Promoter Score feedback");let h=null,f=document.createElement("div");f.className="tvw-feedback-content";let x=document.createElement("div");x.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=t,x.appendChild(C);let E=document.createElement("p");E.className="tvw-feedback-subtitle",E.textContent=o,x.appendChild(E),f.appendChild(x);let S=document.createElement("div");S.className="tvw-feedback-rating tvw-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="tvw-feedback-labels";let V=document.createElement("span");V.className="tvw-feedback-label-low",V.textContent=g;let y=document.createElement("span");y.className="tvw-feedback-label-high",y.textContent=w,k.appendChild(V),k.appendChild(y);let O=document.createElement("div");O.className="tvw-feedback-numbers";let W=[];for(let X=0;X<=10;X++){let U=document.createElement("button");U.type="button",U.className="tvw-feedback-rating-btn tvw-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${X} out of 10`),U.textContent=String(X),U.dataset.rating=String(X),X<=6?U.classList.add("tvw-feedback-detractor"):X<=8?U.classList.add("tvw-feedback-passive"):U.classList.add("tvw-feedback-promoter"),U.addEventListener("click",()=>{h=X,W.forEach((Se,N)=>{Se.classList.toggle("selected",N===X),Se.setAttribute("aria-checked",N===X?"true":"false")})}),W.push(U),O.appendChild(U)}S.appendChild(k),S.appendChild(O),f.appendChild(S);let H=null;if(d){let X=document.createElement("div");X.className="tvw-feedback-comment-container",H=document.createElement("textarea"),H.className="tvw-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),X.appendChild(H),f.appendChild(X)}let oe=document.createElement("div");oe.className="tvw-feedback-actions";let _=document.createElement("button");_.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-skip",_.textContent=a,_.addEventListener("click",()=>{r==null||r(),c.remove()});let le=document.createElement("button");return le.type="button",le.className="tvw-feedback-btn tvw-feedback-btn-submit",le.textContent=i,le.addEventListener("click",async()=>{if(h===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}le.disabled=!0,le.textContent="Submitting...";try{let X=(H==null?void 0:H.value.trim())||void 0;await n(h,X),c.remove()}catch(X){le.disabled=!1,le.textContent=i,console.error("[NPS Feedback] Failed to submit:",X)}}),oe.appendChild(_),oe.appendChild(le),f.appendChild(oe),c.appendChild(f),c}var _n="persona-chat-history",il=30*1e3;function al(e){var n,r,t,o,s,i,a,d,g;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(t=e.persist)==null?void 0:t.openState)!=null?o:!0,voiceState:(i=(s=e.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=e.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(g=e.clearOnChatClear)!=null?g:!0}:null}function ll(e){try{let n=e==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var br=e=>!e||typeof e!="object"?{}:{...e},ra=e=>e.map(n=>({...n,streaming:!1})),oa=(e,n,r)=>{let t=e!=null&&e.markdown?os(e.markdown):null;return o=>{var a,d,g;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(n){let w=n.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});w!==null&&(s=w.text,w.persist||(o.message.__skipPersist=!0),w.resubmit&&!o.streaming&&r&&r())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(g=i!=null?i:o.text)!=null?g:""}):t?t(s):Ms(s)}},Ks=(e,n,r)=>{var v,T,se,Ee,Ye,Lt,nt,Ct,gt,De,qe,lt,ze,xt,Rt,_t,Ar,Er,Tr,Mr,Lr,kr,Wr,Ir,Pr,Hr,Br,Rr,Fr,$r,Or,Nr;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let t=Ns(n),o=ds.getForInstance(t.plugins);t.components&&Dn.registerAll(t.components);let s=ea(),i=(v=t.storageAdapter)!=null?v:Ds(),a={},d=null,g=l=>{if(t.onStateLoaded)try{return t.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(u=>{let b=u!=null?u:{messages:[],metadata:{}};return g(b)});else{let u=l!=null?l:{messages:[],metadata:{}},b=g(u);b.metadata&&(a=br(b.metadata)),(T=b.messages)!=null&&T.length&&(t={...t,initialMessages:b.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(t.onStateLoaded)try{let l=g({messages:[],metadata:{}});(se=l.messages)!=null&&se.length&&(t={...t,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let w=()=>a,c=l=>{var b;a=(b=l({...a}))!=null?b:{},Yn()},h=t.actionParsers&&t.actionParsers.length?t.actionParsers:[cs],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[An.message,An.messageAndClick],x=us({parsers:h,handlers:f,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null});x.syncFromMetadata();let C=(Ye=(Ee=t.launcher)==null?void 0:Ee.enabled)!=null?Ye:!0,E=(nt=(Lt=t.launcher)==null?void 0:Lt.autoExpand)!=null?nt:!1,S=E,k=C,V=(gt=(Ct=t.layout)==null?void 0:Ct.header)==null?void 0:gt.layout,y=C?E:!0,O=!1,W=null,H=()=>{O=!0,W&&clearTimeout(W),W=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},oe=oa(t,x,H),_=(qe=(De=t.features)==null?void 0:De.showReasoning)!=null?qe:!0,le=(ze=(lt=t.features)==null?void 0:lt.showToolCalls)!=null?ze:!0,X=(Rt=(xt=t.features)==null?void 0:xt.showEventStreamToggle)!=null?Rt:!1,Se=`${(Ar=typeof t.persistState=="object"?(_t=t.persistState)==null?void 0:_t.keyPrefix:void 0)!=null?Ar:"persona-"}event-stream`,N=X?new ls(Se):null,re=(Mr=(Tr=(Er=t.features)==null?void 0:Er.eventStream)==null?void 0:Tr.maxEvents)!=null?Mr:2e3,D=X?new as(re,N):null,Z=null,ve=!1,pe=null,Ue=0;N==null||N.open().then(()=>D==null?void 0:D.restore()).catch(l=>{t.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let it={onCopy:l=>{var u,b;s.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(L=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",L)}),(b=(u=t.messageActions)==null?void 0:u.onCopy)==null||b.call(u,l)},onFeedback:l=>{var u,b;s.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(L=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",L)}),(b=(u=t.messageActions)==null?void 0:u.onFeedback)==null||b.call(u,l)}},Tt=(Lr=t.statusIndicator)!=null?Lr:{},$t=l=>{var u,b,L,A;return l==="idle"?(u=Tt.idleText)!=null?u:Pt.idle:l==="connecting"?(b=Tt.connectingText)!=null?b:Pt.connecting:l==="connected"?(L=Tt.connectedText)!=null?L:Pt.connected:l==="error"?(A=Tt.errorText)!=null?A:Pt.error:Pt[l]},{wrapper:Fe,panel:Ae}=Ui(t),ee=Ji(t,C),{container:ge,body:$e,messagesWrapper:Qe,suggestions:At,textarea:me,sendButton:J,sendButtonWrapper:ct,composerForm:ut,statusText:ft,introTitle:Ot,introSubtitle:wt,closeButton:Y,iconHolder:Ie,headerTitle:vt,headerSubtitle:yt,header:Q,footer:Oe,actionsRow:bt,leftActions:Wt,rightActions:Mt}=ee,j=ee.micButton,Ze=ee.micButtonWrapper,We=ee.attachmentButton,z=ee.attachmentButtonWrapper,R=ee.attachmentInput,he=ee.attachmentPreviewsContainer,ue=null;(kr=t.attachments)!=null&&kr.enabled&&R&&he&&(ue=Cn.fromConfig(t.attachments),ue.setPreviewsContainer(he),R.addEventListener("change",l=>{let u=l.target;ue==null||ue.handleFileSelect(u.files),u.value=""}));let te=o.find(l=>l.renderHeader);if(te!=null&&te.renderHeader){let l=te.renderHeader({config:t,defaultRenderer:()=>{let u=rn({config:t,showClose:C});return xn(ge,u,t),u.header},onClose:()=>tt(!1,"user")});if(l){let u=ge.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),Q=l)}}let Le=()=>{var u,b,L,A;if(!D)return;if(ve=!0,!Z&&D&&(Z=Qi({buffer:D,getFullHistory:()=>D.getAllFromStore(),onClose:()=>Ne(),config:t,plugins:o})),Z&&($e.style.display="none",(u=Oe.parentNode)==null||u.insertBefore(Z.element,Oe),Z.update()),q){q.classList.remove("tvw-text-cw-muted"),q.classList.add("tvw-text-cw-accent"),q.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let $=(A=(L=(b=t.features)==null?void 0:b.eventStream)==null?void 0:L.classNames)==null?void 0:A.toggleButtonActive;$&&$.split(/\s+/).forEach(ye=>ye&&q.classList.add(ye))}let l=()=>{if(!ve)return;let $=Date.now();$-Ue>=200&&(Z==null||Z.update(),Ue=$),pe=requestAnimationFrame(l)};Ue=0,pe=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},Ne=()=>{var l,u,b;if(ve){if(ve=!1,Z&&Z.element.remove(),$e.style.display="",q){q.classList.remove("tvw-text-cw-accent"),q.classList.add("tvw-text-cw-muted"),q.style.boxShadow="";let L=(b=(u=(l=t.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:b.toggleButtonActive;L&&L.split(/\s+/).forEach(A=>A&&q.classList.remove(A))}pe!==null&&(cancelAnimationFrame(pe),pe=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},q=null;if(X){let l=(Ir=(Wr=t.features)==null?void 0:Wr.eventStream)==null?void 0:Ir.classNames,u="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 tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");q=p("button",u),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let b=ie("activity","18px","currentColor",1.5);b&&q.appendChild(b);let L=ee.clearChatButtonWrapper,A=ee.closeButtonWrapper,$=L||A;$&&$.parentNode===Q?Q.insertBefore(q,$):Q.appendChild(q),q.addEventListener("click",()=>{ve?Ne():Le()})}let de=o.find(l=>l.renderComposer);if(de!=null&&de.renderComposer){let l=de.renderComposer({config:t,defaultRenderer:()=>Rn({config:t}).footer,onSubmit:u=>{F&&!F.isStreaming()&&F.sendMessage(u)},disabled:!1});l&&(Oe.replaceWith(l),Oe=l)}(()=>{var L,A;let l=(A=(L=t.layout)==null?void 0:L.slots)!=null?A:{},u=$=>{switch($){case"body-top":return ge.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Qe;case"footer-top":return At;case"composer":return ut;case"footer-bottom":return ft;default:return null}},b=($,ye)=>{var ce;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Q.insertBefore(ye,Q.firstChild);else if($==="header-right")Q.appendChild(ye);else{let be=Q.querySelector(".tvw-flex-col");be?(ce=be.parentNode)==null||ce.insertBefore(ye,be.nextSibling):Q.appendChild(ye)}break;case"body-top":{let be=$e.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");be?be.replaceWith(ye):$e.insertBefore(ye,$e.firstChild);break}case"body-bottom":$e.appendChild(ye);break;case"footer-top":At.replaceWith(ye);break;case"footer-bottom":ft.replaceWith(ye);break;default:break}};for(let[$,ye]of Object.entries(l))if(ye)try{let ce=ye({config:t,defaultContent:()=>u($)});ce&&b($,ce)}catch(ce){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,ce)}})();let Je=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let L=b.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!L)return;let A=L.getAttribute("data-message-id");if(!A)return;let $=b.getAttribute("data-bubble-type");$==="reasoning"?($n.has(A)?$n.delete(A):$n.add(A),Vi(A,L)):$==="tool"&&(On.has(A)?On.delete(A):On.add(A),Xi(A,L,t))};Qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),Qe.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))});let st=new Map;Qe.addEventListener("click",l=>{var ye;let b=l.target.closest(".tvw-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let L=b.closest("[data-actions-for]");if(!L)return;let A=L.getAttribute("data-actions-for");if(!A)return;let $=b.getAttribute("data-action");if($==="copy"){let be=F.getMessages().find(Te=>Te.id===A);if(be&&it.onCopy){let Te=be.content||"";navigator.clipboard.writeText(Te).then(()=>{b.classList.add("tvw-message-action-success");let Ce=ie("check",14,"currentColor",2);Ce&&(b.innerHTML="",b.appendChild(Ce)),setTimeout(()=>{b.classList.remove("tvw-message-action-success");let Pe=ie("copy",14,"currentColor",2);Pe&&(b.innerHTML="",b.appendChild(Pe))},2e3)}).catch(Ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ce)}),it.onCopy(be)}}else if($==="upvote"||$==="downvote")if(((ye=st.get(A))!=null?ye:null)===$)st.delete(A),b.classList.remove("tvw-message-action-active");else{let Te=$==="upvote"?"downvote":"upvote",Ce=L.querySelector(`[data-action="${Te}"]`);Ce&&Ce.classList.remove("tvw-message-action-active"),st.set(A,$),b.classList.add("tvw-message-action-active");let G=F.getMessages().find(I=>I.id===A);G&&it.onFeedback&&it.onFeedback({type:$,messageId:G.id,message:G})}}),Ae.appendChild(ge),e.appendChild(Fe);let Tn=()=>{var we,xe,Ve,He,mt,It,K,je,Vt,zt,dn,Ss,er,dt,As,Zn;let l=(xe=(we=t.launcher)==null?void 0:we.sidebarMode)!=null?xe:!1,u=l||((He=(Ve=t.launcher)==null?void 0:Ve.fullHeight)!=null?He:!1),b=(mt=t.theme)!=null?mt:{},L=(K=(It=t.launcher)==null?void 0:It.position)!=null?K:"bottom-left",A=L==="bottom-left"||L==="top-left",$=l?"none":"1px solid var(--tvw-cw-border)",ye=l?A?"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)",ce=l?"0":"16px",be=(je=b.panelBorder)!=null?je:$,Te=(Vt=b.panelShadow)!=null?Vt:ye,Ce=(zt=b.panelBorderRadius)!=null?zt:ce;e.style.cssText="",Fe.style.cssText="",Ae.style.cssText="",ge.style.cssText="",$e.style.cssText="",Oe.style.cssText="";let Pe=(Ss=(dn=t==null?void 0:t.launcher)==null?void 0:dn.width)!=null?Ss:t==null?void 0:t.launcherWidth,G=Pe!=null?Pe:"min(400px, calc(100vw - 24px))";l||(Ae.style.width=G,Ae.style.maxWidth=G),Ae.style.boxShadow=Te,Ae.style.borderRadius=Ce,ge.style.border=be,ge.style.borderRadius=Ce;let I=((er=t.launcher)==null?void 0:er.enabled)===!1;if(u&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",Fe.style.display="flex",Fe.style.flexDirection="column",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.maxHeight="100%",Fe.style.height="100%",I&&(Fe.style.overflow="hidden"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",Ae.style.overflow="hidden",ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.overflow="hidden",$e.style.flex="1 1 0%",$e.style.minHeight="0",$e.style.overflowY="auto",Oe.style.flexShrink="0"),Fe.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&&!I&&((dt=Ut[L])!=null?dt:Ut["bottom-right"]).split(" ").forEach(wn=>Fe.classList.add(wn)),l){let fn=(Zn=(As=t.launcher)==null?void 0:As.sidebarWidth)!=null?Zn:"420px";Fe.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
24
- width: ${pn} !important;
24
+ width: ${fn} !important;
25
25
  height: 100vh !important;
26
26
  max-height: 100vh !important;
27
27
  margin: 0 !important;
28
28
  padding: 0 !important;
29
29
  display: flex !important;
30
30
  flex-direction: column !important;
31
- ${E?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
- `,Se.style.cssText=`
31
+ ${A?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
+ `,Ae.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
35
35
  flex-direction: column !important;
@@ -40,9 +40,9 @@
40
40
  min-height: 0 !important;
41
41
  margin: 0 !important;
42
42
  padding: 0 !important;
43
- box-shadow: ${Ae} !important;
44
- border-radius: ${be} !important;
45
- `,Se.style.setProperty("width","100%","important"),Se.style.setProperty("max-width","100%","important"),ue.style.cssText=`
43
+ box-shadow: ${Te} !important;
44
+ border-radius: ${Ce} !important;
45
+ `,Ae.style.setProperty("width","100%","important"),Ae.style.setProperty("max-width","100%","important"),ge.style.cssText=`
46
46
  display: flex !important;
47
47
  flex-direction: column !important;
48
48
  flex: 1 1 0% !important;
@@ -51,13 +51,13 @@
51
51
  min-height: 0 !important;
52
52
  max-height: 100% !important;
53
53
  overflow: hidden !important;
54
- border-radius: ${be} !important;
55
- border: ${ye} !important;
56
- `,$e.style.cssText=`
54
+ border-radius: ${Ce} !important;
55
+ border: ${be} !important;
56
+ `,Oe.style.cssText=`
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!I){let pn="max-height: -moz-available !important; max-height: stretch !important;",gn=l?"":"padding-top: 1.25em !important;";Re.style.cssText+=pn+gn}};xn(),ks(e,t);let at=[];X&&at.push(()=>{ce!==null&&(cancelAnimationFrame(ce),ce=null),Z==null||Z.destroy(),Z=null,D==null||D.destroy(),D=null,N=null});let Ut=null,On=()=>{Ut&&(Ut(),Ut=null),t.colorScheme==="auto"&&(Ut=_i(()=>{ks(e,t)}))};On(),at.push(()=>{Ut&&(Ut(),Ut=null)});let sn=Gi(St),Jt=null,F,rn=!1,Vt=!0,ln=0,Nn=0,Xt=null,Gt=!1,Sn=0,An=!1,is=125,as=2e3,ls=5,Dn=50,En=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},jn=(Hr=(Pr=t.voiceRecognition)==null?void 0:Pr.autoResume)!=null?Hr:!1,_n=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},Qt=()=>{c(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},ds=()=>{var k,E;if(((k=t.voiceRecognition)==null?void 0:k.enabled)===!1)return;let l=ur(a.voiceState),u=!!l.active,b=Number((E=l.timestamp)!=null?E:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-b<il&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,et("restore"))},1e3)},cs=()=>F?ra(F.getMessages()).filter(l=>!l.__skipPersist):[];function qn(l){if(!(i!=null&&i.save))return;let b={messages:l?ra(l):F?cs():[],metadata:a};try{let k=i.save(b);k instanceof Promise&&k.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)})}catch(k){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)}}let dn=(l=!1)=>{if(!Vt)return;let u=Date.now();Gt&&u<Sn&&!l||(Gt&&u>=Sn&&(Gt=!1),!(!l&&!rn)&&(u-Nn<is||(Nn=u,Xt&&cancelAnimationFrame(Xt),Xt=requestAnimationFrame(()=>{Gt||!Vt||(An=!0,Fe.scrollTop=Fe.scrollHeight,ln=Fe.scrollTop,requestAnimationFrame(()=>{An=!1}),Xt=null)}))))},Zt=null,us=()=>Re.querySelector("#persona-scroll-container")||Fe,ps=(l,u=500)=>{let b=l.scrollTop,k=l.clientHeight,E=l.scrollHeight,$=E-b;if(b+k>=E-2||Math.abs($)<5)return;Zt!==null&&(cancelAnimationFrame(Zt),Zt=null);let le=performance.now(),ye=be=>1-Math.pow(1-be,3),Ae=be=>{let Ie=l.scrollHeight;Ie!==E&&(E=Ie,$=E-b);let G=be-le,I=Math.min(G/u,1),he=ye(I),Ce=b+$*he;l.scrollTop=Ce,I<1?Zt=requestAnimationFrame(Ae):(l.scrollTop=l.scrollHeight,Zt=null)};Zt=requestAnimationFrame(Ae)},gs=l=>{let u=new Map;l.forEach(b=>{let k=En.get(b.id);u.set(b.id,{streaming:b.streaming,role:b.role}),!k&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(k!=null&&k.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b)}),En.clear(),u.forEach((b,k)=>{En.set(k,b)})},cn=(l,u,b)=>{var Ae,be,Ie,G;let k=document.createElement("div"),$=(()=>{var he;let I=o.find(Ce=>Ce.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((he=t.loadingIndicator)!=null&&he.render)return t.loadingIndicator.render})();u.forEach(I=>{var mt,Wt;let he=null,Ce=o.find(K=>!!(I.variant==="reasoning"&&K.renderReasoning||I.variant==="tool"&&K.renderToolCall||!I.variant&&K.renderMessage)),Xe=(mt=t.layout)==null?void 0:mt.messages;if(Ce)if(I.variant==="reasoning"&&I.reasoning&&Ce.renderReasoning){if(!_)return;he=Ce.renderReasoning({message:I,defaultRenderer:()=>nr(I),config:t})}else if(I.variant==="tool"&&I.toolCall&&Ce.renderToolCall){if(!oe)return;he=Ce.renderToolCall({message:I,defaultRenderer:()=>sr(I,t),config:t})}else Ce.renderMessage&&(he=Ce.renderMessage({message:I,defaultRenderer:()=>{let K=In(I,b,Xe,t.messageActions,dt,{loadingIndicatorRenderer:$,widgetConfig:t});return I.role!=="user"&&or(K,I,t,F),K},config:t}));if(!he&&I.role==="assistant"&&!I.variant&&t.enableComponentStreaming!==!1&&Bs(I)){let _e=Rs(I);if(_e){let Kt=Hs(_e,{config:t,message:I,transform:b});if(Kt){let qt=document.createElement("div");if(qt.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(" "),qt.id=`bubble-${I.id}`,qt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let on=document.createElement("div");on.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",on.innerHTML=b({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),qt.appendChild(on)}qt.appendChild(Kt),he=qt}}}if(!he)if(I.variant==="reasoning"&&I.reasoning){if(!_)return;he=nr(I)}else if(I.variant==="tool"&&I.toolCall){if(!oe)return;he=sr(I,t)}else{let K=(Wt=t.layout)==null?void 0:Wt.messages;K!=null&&K.renderUserMessage&&I.role==="user"?he=K.renderUserMessage({message:I,config:t,streaming:!!I.streaming}):K!=null&&K.renderAssistantMessage&&I.role==="assistant"?he=K.renderAssistantMessage({message:I,config:t,streaming:!!I.streaming}):he=In(I,b,K,t.messageActions,dt,{loadingIndicatorRenderer:$,widgetConfig:t}),I.role!=="user"&&he&&or(he,I,t,F)}let Pe=document.createElement("div");Pe.className="tvw-flex",Pe.id=`wrapper-${I.id}`,Pe.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Pe.classList.add("tvw-justify-end"),Pe.appendChild(he),k.appendChild(Pe)});let ve=u.some(I=>I.role==="assistant"&&I.streaming),le=u[u.length-1],ye=(le==null?void 0:le.role)==="assistant"&&!le.streaming;if(rn&&u.some(I=>I.role==="user")&&!ve&&!ye){let I={config:t,streaming:!0,location:"standalone",defaultRenderer:yn},he=o.find(Xe=>Xe.renderLoadingIndicator),Ce=null;if(he!=null&&he.renderLoadingIndicator&&(Ce=he.renderLoadingIndicator(I)),Ce===null&&((Ae=t.loadingIndicator)!=null&&Ae.render)&&(Ce=t.loadingIndicator.render(I)),Ce===null&&(Ce=yn()),Ce){let Xe=document.createElement("div"),Pe=((be=t.loadingIndicator)==null?void 0:be.showBubble)!==!1;Xe.className=Pe?["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(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Xe.setAttribute("data-typing-indicator","true"),Xe.appendChild(Ce);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Xe),k.appendChild(mt)}}if(!rn&&u.length>0){let I=u[u.length-1],he={config:t,lastMessage:I,messageCount:u.length},Ce=o.find(Pe=>Pe.renderIdleIndicator),Xe=null;if(Ce!=null&&Ce.renderIdleIndicator&&(Xe=Ce.renderIdleIndicator(he)),Xe===null&&((Ie=t.loadingIndicator)!=null&&Ie.renderIdle)&&(Xe=t.loadingIndicator.renderIdle(he)),Xe){let Pe=document.createElement("div"),mt=((G=t.loadingIndicator)==null?void 0:G.showBubble)!==!1;Pe.className=mt?["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(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(Xe);let Wt=document.createElement("div");Wt.className="tvw-flex",Wt.id="wrapper-idle-indicator",Wt.setAttribute("data-wrapper-id","idle-indicator"),Wt.appendChild(Pe),k.appendChild(Wt)}}zi(l,k),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=us();ps(I)})})},un=()=>{C&&(v?(Re.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Se.classList.remove("tvw-scale-95","tvw-opacity-0"),Se.classList.add("tvw-scale-100","tvw-opacity-100"),h?h.element.style.display="none":S&&(S.style.display="none")):(Re.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Se.classList.remove("tvw-scale-100","tvw-opacity-100"),Se.classList.add("tvw-scale-95","tvw-opacity-0"),h?h.element.style.display="":S&&(S.style.display="")))},ot=(l,u="user")=>{if(!C||v===l)return;let b=v;v=l,un(),v&&(ie(),dn(!0));let k={open:v,source:u,timestamp:Date.now()};v&&!b?s.emit("widget:opened",k):!v&&b&&s.emit("widget:closed",k),s.emit("widget:state",{open:v,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()})},Tn=l=>{J.disabled=l,j&&(j.disabled=l),sn.buttons.forEach(u=>{u.disabled=l})},zn=()=>{var E,$,ve,le,ye,Ae,be,Ie,G,I,he,Ce,Xe,Pe;$t.textContent=($=(E=t.copy)==null?void 0:E.welcomeTitle)!=null?$:"Hello \u{1F44B}",wt.textContent=(le=(ve=t.copy)==null?void 0:ve.welcomeSubtitle)!=null?le:"Ask anything about your account or products.",pe.placeholder=(Ae=(ye=t.copy)==null?void 0:ye.inputPlaceholder)!=null?Ae:"How can I help...",((Ie=(be=t.sendButton)==null?void 0:be.useIcon)!=null?Ie:!1)||(J.textContent=(I=(G=t.copy)==null?void 0:G.sendButtonLabel)!=null?I:"Send");let u=(Ce=(he=t.theme)==null?void 0:he.inputFontFamily)!=null?Ce:"sans-serif",b=(Pe=(Xe=t.theme)==null?void 0:Xe.inputFontWeight)!=null?Pe:"400",k=mt=>{switch(mt){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'}};pe.style.fontFamily=k(u),pe.style.fontWeight=b};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{c(u=>({...u,sessionId:l}))}}),F=new kn(t,{onMessagesChanged(l){cn(Qe,l,se),F&&(l.some(E=>E.role==="user")?sn.render([],F,pe,l):sn.render(t.suggestionChips,F,pe,l,t.suggestionChipsConfig)),dn(!rn),gs(l);let u=[...l].reverse().find(k=>k.role==="user"),b=Ke.lastUserMessageId;u&&u.id!==b&&(Ke.lastUserMessageId=u.id,s.emit("user:message",u)),Ke.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),qn(l)},onStatusChanged(l){var k;let u=(k=t.statusIndicator)!=null?k:{},b=E=>{var $,ve,le,ye;return E==="idle"?($=u.idleText)!=null?$:It.idle:E==="connecting"?(ve=u.connectingText)!=null?ve:It.connecting:E==="connected"?(le=u.connectedText)!=null?le:It.connected:E==="error"?(ye=u.errorText)!=null?ye:It.error:It[E]};ft.textContent=b(l)},onStreamingChanged(l){rn=l,Tn(l),F&&cn(Qe,F.getMessages(),se),l||dn(!0)}}),t.clientToken&&F.initClientSession().catch(l=>{t.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&F.setSSEEventCallback((l,u)=>{D==null||D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(a=ur(l.metadata),x.syncFromMetadata()),(u=l.messages)!=null&&u.length&&F.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Un=l=>{var E;l.preventDefault();let u=pe.value.trim(),b=(E=de==null?void 0:de.hasAttachments())!=null?E:!1;if(!u&&!b)return;let k;b&&(k=[],k.push(...de.getContentParts()),u&&k.push(Es(u))),pe.value="",pe.style.height="auto",F.sendMessage(u,{contentParts:k}),b&&de.clearAttachments()},Jn=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},Pt=null,Ot=!1,B=null,we=null,De=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,et=(l="user")=>{var $,ve,le,ye;if(Ot||F.isStreaming())return;let u=De();if(!u)return;Pt=new u;let k=(ve=(($=t.voiceRecognition)!=null?$:{}).pauseDuration)!=null?ve:2e3;Pt.continuous=!0,Pt.interimResults=!0,Pt.lang="en-US";let E=pe.value;Pt.onresult=Ae=>{let be="",Ie="";for(let I=0;I<Ae.results.length;I++){let he=Ae.results[I],Ce=he[0].transcript;he.isFinal?be+=Ce+" ":Ie=Ce}let G=E+be+Ie;pe.value=G,B&&clearTimeout(B),(be||Ie)&&(B=window.setTimeout(()=>{let I=pe.value.trim();I&&Pt&&Ot&&(Ye(),pe.value="",pe.style.height="auto",F.sendMessage(I,{viaVoice:!0}))},k))},Pt.onerror=Ae=>{Ae.error!=="no-speech"&&Ye()},Pt.onend=()=>{if(Ot){let Ae=pe.value.trim();Ae&&Ae!==E.trim()&&(pe.value="",pe.style.height="auto",F.sendMessage(Ae,{viaVoice:!0})),Ye()}};try{if(Pt.start(),Ot=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),_n(l),Qt(),j){we={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let Ae=(le=t.voiceRecognition)!=null?le:{},be=(ye=Ae.recordingBackgroundColor)!=null?ye:"#ef4444",Ie=Ae.recordingIconColor,G=Ae.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=be,Ie){j.style.color=Ie;let I=j.querySelector("svg");I&&I.setAttribute("stroke",Ie)}G&&(j.style.borderColor=G),j.setAttribute("aria-label","Stop voice recognition")}}catch{Ye("system")}},Ye=(l="user")=>{if(Ot){if(Ot=!1,B&&(clearTimeout(B),B=null),Pt){try{Pt.stop()}catch{}Pt=null}if(Ke.active=!1,_n(l),Qt(),j){if(j.classList.remove("tvw-voice-recording"),we){j.style.backgroundColor=we.backgroundColor,j.style.color=we.color,j.style.borderColor=we.borderColor;let u=j.querySelector("svg");u&&u.setAttribute("stroke",we.color||"currentColor"),we=null}j.setAttribute("aria-label","Start voice recognition")}}},Tt=(l,u)=>{var Ce,Xe,Pe,mt,Wt,K,_e;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let k=p("div","tvw-send-button-wrapper"),E=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");E.type="button",E.setAttribute("aria-label","Start voice recognition");let $=(Ce=l==null?void 0:l.iconName)!=null?Ce:"mic",ve=(Xe=u==null?void 0:u.size)!=null?Xe:"40px",le=(Pe=l==null?void 0:l.iconSize)!=null?Pe:ve,ye=parseFloat(le)||24,Ae=(mt=l==null?void 0:l.backgroundColor)!=null?mt:u==null?void 0:u.backgroundColor,be=(Wt=l==null?void 0:l.iconColor)!=null?Wt:u==null?void 0:u.textColor;E.style.width=le,E.style.height=le,E.style.minWidth=le,E.style.minHeight=le,E.style.fontSize="18px",E.style.lineHeight="1";let Ie=be||"currentColor",G=re($,ye,Ie,1.5);G?(E.appendChild(G),E.style.color=Ie):(E.textContent="\u{1F3A4}",E.style.color=Ie),Ae?E.style.backgroundColor=Ae:E.classList.add("tvw-bg-cw-primary"),be?E.style.color=be:!be&&!(u!=null&&u.textColor)&&E.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(E.style.borderWidth=l.borderWidth,E.style.borderStyle="solid"),l!=null&&l.borderColor&&(E.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(E.style.paddingLeft=l.paddingX,E.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(E.style.paddingTop=l.paddingY,E.style.paddingBottom=l.paddingY),k.appendChild(E);let I=(K=l==null?void 0:l.tooltipText)!=null?K:"Start voice recognition";if(((_e=l==null?void 0:l.showTooltip)!=null?_e:!1)&&I){let Kt=p("div","tvw-send-button-tooltip");Kt.textContent=I,k.appendChild(Kt)}return{micButton:E,micButtonWrapper:k}},tt=()=>{if(Ot){let l=pe.value.trim();Ke.manuallyDeactivated=!0,Qt(),Ye("user"),l&&(pe.value="",pe.style.height="auto",F.sendMessage(l))}else Ke.manuallyDeactivated=!1,Qt(),et("user")};j&&(j.addEventListener("click",tt),at.push(()=>{Ye("system"),j&&j.removeEventListener("click",tt)}));let y=s.on("assistant:complete",()=>{jn&&(Ke.active||Ke.manuallyDeactivated||jn==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&et("auto")},600))});at.push(y);let Ve=s.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});at.push(Ve);let H=()=>{ot(!v,"user")},h=null,S=null;if(C){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:t,defaultRenderer:()=>es(t,H).element,onToggle:H});u&&(S=u)}S||(h=es(t,H))}h?e.appendChild(h.element):S&&e.appendChild(S),un(),sn.render(t.suggestionChips,F,pe,void 0,t.suggestionChipsConfig),zn(),Tn(F.isStreaming()),dn(!0),ds();let ie=()=>{var b,k,E,$,ve,le,ye,Ae;let l=(k=(b=t.launcher)==null?void 0:b.sidebarMode)!=null?k:!1,u=l||(($=(E=t.launcher)==null?void 0:E.fullHeight)!=null?$:!1);if(!C){Se.style.height="",Se.style.width="";return}if(!l){let be=(le=(ve=t==null?void 0:t.launcher)==null?void 0:ve.width)!=null?le:t==null?void 0:t.launcherWidth,Ie=be!=null?be:"min(400px, calc(100vw - 24px))";Se.style.width=Ie,Se.style.maxWidth=Ie}if(!u){let be=window.innerHeight,Ie=64,G=(Ae=(ye=t.launcher)==null?void 0:ye.heightOffset)!=null?Ae:0,I=Math.max(200,be-Ie),he=Math.min(640,I),Ce=Math.max(200,he-G);Se.style.height=`${Ce}px`}};ie(),window.addEventListener("resize",ie),at.push(()=>window.removeEventListener("resize",ie)),ln=Fe.scrollTop;let nt=()=>{let l=Fe.scrollTop,u=Fe.scrollHeight,b=Fe.clientHeight,k=u-l-b,E=Math.abs(l-ln);if(ln=l,!An&&!(E<=ls)){if(!Vt&&k<Dn){Gt=!1,Vt=!0;return}Vt&&k>Dn&&(Gt=!0,Sn=Date.now()+as,Vt=!1)}};Fe.addEventListener("scroll",nt,{passive:!0}),at.push(()=>Fe.removeEventListener("scroll",nt)),at.push(()=>{Xt&&cancelAnimationFrame(Xt)});let st=()=>{Y&&(Jt&&(Y.removeEventListener("click",Jt),Jt=null),C?(Y.style.display="",Jt=()=>{v=!1,un()},Y.addEventListener("click",Jt)):Y.style.display="none")};st(),(()=>{let{clearChatButton:l}=ee;l&&l.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem($n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${$n}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==$n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",k)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()})})(),gt.addEventListener("submit",Un),pe.addEventListener("keydown",Jn),at.push(()=>{gt.removeEventListener("submit",Un),pe.removeEventListener("keydown",Jn)}),at.push(()=>{F.cancel()}),h?at.push(()=>{h==null||h.destroy()}):S&&at.push(()=>{S==null||S.remove()});let We={update(l){var Dr,jr,_r,qr,zr,Ur,Jr,Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,ko,Lo,Wo,Io,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,jo,_o,qo,zo,Uo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,hi,fi,wi,vi;let u=t.toolCall,b=t.colorScheme;t={...t,...l},xn(),ks(e,t),t.colorScheme!==b&&On();let k=ss.getForInstance(t.plugins);o.length=0,o.push(...k),C=(jr=(Dr=t.launcher)==null?void 0:Dr.enabled)!=null?jr:!0,T=(qr=(_r=t.launcher)==null?void 0:_r.autoExpand)!=null?qr:!1,_=(Ur=(zr=t.features)==null?void 0:zr.showReasoning)!=null?Ur:!0,oe=(Kr=(Jr=t.features)==null?void 0:Jr.showToolCalls)!=null?Kr:!0;let E=X;if(X=(Vr=(Yr=t.features)==null?void 0:Yr.showEventStreamToggle)!=null?Vr:!1,X&&!E){if(D||(N=new ns(xe),D=new ts(ne,N),N.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),F.setSSEEventCallback((M,Ee)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:M,timestamp:Date.now(),payload:JSON.stringify(Ee)})})),!q&&Q){let M=(Gr=(Xr=t.features)==null?void 0:Xr.eventStream)==null?void 0:Gr.classNames,Ee="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 tvw-bg-transparent tvw-p-1"+(M!=null&&M.toggleButton?" "+M.toggleButton:"");q=p("button",Ee),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let Ge=re("activity","18px","currentColor",1.5);Ge&&q.appendChild(Ge);let me=ee.clearChatButtonWrapper,Be=ee.closeButtonWrapper,ht=me||Be;ht&&ht.parentNode===Q?Q.insertBefore(q,ht):Q.appendChild(q),q.addEventListener("click",()=>{fe?Oe():Te()})}}else!X&&E&&(Oe(),q&&(q.remove(),q=null),D==null||D.clear(),N==null||N.destroy(),D=null,N=null);if(((Qr=t.launcher)==null?void 0:Qr.enabled)===!1&&h&&(h.destroy(),h=null),((Zr=t.launcher)==null?void 0:Zr.enabled)===!1&&S&&(S.remove(),S=null),((eo=t.launcher)==null?void 0:eo.enabled)!==!1&&!h&&!S){let M=o.find(Ee=>Ee.renderLauncher);if(M!=null&&M.renderLauncher){let Ee=M.renderLauncher({config:t,defaultRenderer:()=>es(t,H).element,onToggle:H});Ee&&(S=Ee,e.appendChild(S))}S||(h=es(t,H),e.appendChild(h.element))}h&&h.update(t),vt&&((to=t.launcher)==null?void 0:to.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((no=t.launcher)==null?void 0:no.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let $=(so=t.layout)==null?void 0:so.header;if(($==null?void 0:$.layout)!==V&&Q){let M=$?Ln(t,$,{showClose:C,onClose:()=>ot(!1,"user")}):tn({config:t,showClose:C,onClose:()=>ot(!1,"user")});Q.replaceWith(M.header),Q=M.header,Le=M.iconHolder,vt=M.headerTitle,yt=M.headerSubtitle,Y=M.closeButton,V=$==null?void 0:$.layout}else if($&&(Le&&(Le.style.display=$.showIcon===!1?"none":""),vt&&(vt.style.display=$.showTitle===!1?"none":""),yt&&(yt.style.display=$.showSubtitle===!1?"none":""),Y&&(Y.style.display=$.showCloseButton===!1?"none":""),ee.clearChatButtonWrapper)){let M=$.showClearChat;if(M!==void 0){ee.clearChatButtonWrapper.style.display=M?"":"none";let{closeButtonWrapper:Ee}=ee;Ee&&!Ee.classList.contains("tvw-absolute")&&(M?Ee.classList.remove("tvw-ml-auto"):Ee.classList.add("tvw-ml-auto"))}}let le=((ro=t.layout)==null?void 0:ro.showHeader)!==!1;Q&&(Q.style.display=le?"":"none");let ye=((oo=t.layout)==null?void 0:oo.showFooter)!==!1;$e&&($e.style.display=ye?"":"none"),C!==L?C?ot(T,"auto"):(v=!0,un()):T!==A&&ot(T,"auto"),A=T,L=C,ie(),st(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&F&&cn(Qe,F.getMessages(),se);let G=(io=t.launcher)!=null?io:{},I=(ao=G.headerIconHidden)!=null?ao:!1,he=(co=(lo=t.layout)==null?void 0:lo.header)==null?void 0:co.showIcon,Ce=I||he===!1,Xe=G.headerIconName,Pe=(uo=G.headerIconSize)!=null?uo:"48px";if(Le){let M=ue.querySelector(".tvw-border-b-cw-divider"),Ee=M==null?void 0:M.querySelector(".tvw-flex-col");if(Ce)Le.style.display="none",M&&Ee&&!M.contains(Ee)&&M.insertBefore(Ee,M.firstChild);else{if(Le.style.display="",Le.style.height=Pe,Le.style.width=Pe,M&&Ee&&(M.contains(Le)?Le.nextSibling!==Ee&&(Le.remove(),M.insertBefore(Le,Ee)):M.insertBefore(Le,Ee)),Xe){let me=parseFloat(Pe)||24,Be=re(Xe,me*.6,"#ffffff",2);Be?Le.replaceChildren(Be):Le.textContent=(po=G.agentIconText)!=null?po:"\u{1F4AC}"}else if(G.iconUrl){let me=Le.querySelector("img");if(me)me.src=G.iconUrl,me.style.height=Pe,me.style.width=Pe;else{let Be=document.createElement("img");Be.src=G.iconUrl,Be.alt="",Be.className="tvw-rounded-xl tvw-object-cover",Be.style.height=Pe,Be.style.width=Pe,Le.replaceChildren(Be)}}else{let me=Le.querySelector("svg"),Be=Le.querySelector("img");(me||Be)&&Le.replaceChildren(),Le.textContent=(go=G.agentIconText)!=null?go:"\u{1F4AC}"}let Ge=Le.querySelector("img");Ge&&(Ge.style.height=Pe,Ge.style.width=Pe)}}let mt=(ho=(mo=t.layout)==null?void 0:mo.header)==null?void 0:ho.showTitle,Wt=(wo=(fo=t.layout)==null?void 0:fo.header)==null?void 0:wo.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=Wt===!1?"none":""),Y){((yo=(vo=t.layout)==null?void 0:vo.header)==null?void 0:yo.showCloseButton)===!1?Y.style.display="none":Y.style.display="";let Ee=(bo=G.closeButtonSize)!=null?bo:"32px",Ge=(Co=G.closeButtonPlacement)!=null?Co:"inline";Y.style.height=Ee,Y.style.width=Ee;let{closeButtonWrapper:me}=ee,Be=Ge==="top-right",ht=me==null?void 0:me.classList.contains("tvw-absolute");if(me&&Be!==ht)if(me.remove(),Be)me.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",ue.style.position="relative",ue.appendChild(me);else{let Me=(So=(xo=G.clearChat)==null?void 0:xo.placement)!=null?So:"inline",xt=(Eo=(Ao=G.clearChat)==null?void 0:Ao.enabled)!=null?Eo:!0;me.className=xt&&Me==="inline"?"":"tvw-ml-auto";let Rt=ue.querySelector(".tvw-border-b-cw-divider");Rt&&Rt.appendChild(me)}if(G.closeButtonColor?(Y.style.color=G.closeButtonColor,Y.classList.remove("tvw-text-cw-muted")):(Y.style.color="",Y.classList.add("tvw-text-cw-muted")),G.closeButtonBackgroundColor?(Y.style.backgroundColor=G.closeButtonBackgroundColor,Y.classList.remove("hover:tvw-bg-gray-100")):(Y.style.backgroundColor="",Y.classList.add("hover:tvw-bg-gray-100")),G.closeButtonBorderWidth||G.closeButtonBorderColor){let Me=G.closeButtonBorderWidth||"0px",xt=G.closeButtonBorderColor||"transparent";Y.style.border=`${Me} solid ${xt}`,Y.classList.remove("tvw-border-none")}else Y.style.border="",Y.classList.add("tvw-border-none");G.closeButtonBorderRadius?(Y.style.borderRadius=G.closeButtonBorderRadius,Y.classList.remove("tvw-rounded-full")):(Y.style.borderRadius="",Y.classList.add("tvw-rounded-full")),G.closeButtonPaddingX?(Y.style.paddingLeft=G.closeButtonPaddingX,Y.style.paddingRight=G.closeButtonPaddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),G.closeButtonPaddingY?(Y.style.paddingTop=G.closeButtonPaddingY,Y.style.paddingBottom=G.closeButtonPaddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let kt=(To=G.closeButtonIconName)!=null?To:"x",Dt=(Mo=G.closeButtonIconText)!=null?Mo:"\xD7";Y.innerHTML="";let Ht=re(kt,"20px",G.closeButtonColor||"",2);Ht?Y.appendChild(Ht):Y.textContent=Dt;let lt=(ko=G.closeButtonTooltipText)!=null?ko:"Close chat",jt=(Lo=G.closeButtonShowTooltip)!=null?Lo:!0;if(Y.setAttribute("aria-label",lt),me&&(me._cleanupTooltip&&(me._cleanupTooltip(),delete me._cleanupTooltip),jt&&lt)){let Me=null,xt=()=>{if(Me||!Y)return;Me=p("div","tvw-clear-chat-tooltip"),Me.textContent=lt;let Gn=p("div");Gn.className="tvw-clear-chat-tooltip-arrow",Me.appendChild(Gn);let mn=Y.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${mn.left+mn.width/2}px`,Me.style.top=`${mn.top-8}px`,Me.style.transform="translate(-50%, -100%)",document.body.appendChild(Me)},Rt=()=>{Me&&Me.parentNode&&(Me.parentNode.removeChild(Me),Me=null)};me.addEventListener("mouseenter",xt),me.addEventListener("mouseleave",Rt),Y.addEventListener("focus",xt),Y.addEventListener("blur",Rt),me._cleanupTooltip=()=>{Rt(),me&&(me.removeEventListener("mouseenter",xt),me.removeEventListener("mouseleave",Rt)),Y&&(Y.removeEventListener("focus",xt),Y.removeEventListener("blur",Rt))}}}let{clearChatButton:K,clearChatButtonWrapper:_e}=ee;if(K){let M=(Wo=G.clearChat)!=null?Wo:{},Ee=(Io=M.enabled)!=null?Io:!0,Ge=(Ho=(Po=t.layout)==null?void 0:Po.header)==null?void 0:Ho.showClearChat,me=Ge!==void 0?Ge:Ee,Be=(Bo=M.placement)!=null?Bo:"inline";if(_e){_e.style.display=me?"":"none";let{closeButtonWrapper:ht}=ee;ht&&!ht.classList.contains("tvw-absolute")&&(me?ht.classList.remove("tvw-ml-auto"):ht.classList.add("tvw-ml-auto"));let kt=Be==="top-right",Dt=_e.classList.contains("tvw-absolute");if(kt!==Dt&&me){if(_e.remove(),kt)_e.className="tvw-absolute tvw-top-4 tvw-z-50",_e.style.right="48px",ue.style.position="relative",ue.appendChild(_e);else{_e.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",_e.style.right="";let lt=ue.querySelector(".tvw-border-b-cw-divider"),jt=ee.closeButtonWrapper;lt&&jt&&jt.parentElement===lt?lt.insertBefore(_e,jt):lt&&lt.appendChild(_e)}let Ht=ee.closeButtonWrapper;Ht&&!Ht.classList.contains("tvw-absolute")&&(kt?Ht.classList.add("tvw-ml-auto"):Ht.classList.remove("tvw-ml-auto"))}}if(me){let ht=(Ro=M.size)!=null?Ro:"32px";K.style.height=ht,K.style.width=ht;let kt=(Fo=M.iconName)!=null?Fo:"refresh-cw",Dt=($o=M.iconColor)!=null?$o:"";K.innerHTML="";let Ht=re(kt,"20px",Dt||"",2);if(Ht&&K.appendChild(Ht),Dt?(K.style.color=Dt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),M.backgroundColor?(K.style.backgroundColor=M.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let Me=M.borderWidth||"0px",xt=M.borderColor||"transparent";K.style.border=`${Me} solid ${xt}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");M.borderRadius?(K.style.borderRadius=M.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),M.paddingX?(K.style.paddingLeft=M.paddingX,K.style.paddingRight=M.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),M.paddingY?(K.style.paddingTop=M.paddingY,K.style.paddingBottom=M.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let lt=(Oo=M.tooltipText)!=null?Oo:"Clear chat",jt=(No=M.showTooltip)!=null?No:!0;if(K.setAttribute("aria-label",lt),_e&&(_e._cleanupTooltip&&(_e._cleanupTooltip(),delete _e._cleanupTooltip),jt&&lt)){let Me=null,xt=()=>{if(Me||!K)return;Me=p("div","tvw-clear-chat-tooltip"),Me.textContent=lt;let Gn=p("div");Gn.className="tvw-clear-chat-tooltip-arrow",Me.appendChild(Gn);let mn=K.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${mn.left+mn.width/2}px`,Me.style.top=`${mn.top-8}px`,Me.style.transform="translate(-50%, -100%)",document.body.appendChild(Me)},Rt=()=>{Me&&Me.parentNode&&(Me.parentNode.removeChild(Me),Me=null)};_e.addEventListener("mouseenter",xt),_e.addEventListener("mouseleave",Rt),K.addEventListener("focus",xt),K.addEventListener("blur",Rt),_e._cleanupTooltip=()=>{Rt(),_e&&(_e.removeEventListener("mouseenter",xt),_e.removeEventListener("mouseleave",Rt)),K&&(K.removeEventListener("focus",xt),K.removeEventListener("blur",Rt))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[rs],qt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[bn.message,bn.messageAndClick];x=os({parsers:Kt,handlers:qt,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),se=oa(t,x,P),F.updateConfig(t),cn(Qe,F.getMessages(),se),sn.render(t.suggestionChips,F,pe,void 0,t.suggestionChipsConfig),zn(),Tn(F.isStreaming());let on=((Do=t.voiceRecognition)==null?void 0:Do.enabled)===!0,ms=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(on&&ms)if(!j||!Ze){let M=Tt(t.voiceRecognition,t.sendButton);M&&(j=M.micButton,Ze=M.micButtonWrapper,Et.insertBefore(Ze,pt),j.addEventListener("click",tt),j.disabled=F.isStreaming())}else{let M=(jo=t.voiceRecognition)!=null?jo:{},Ee=(_o=t.sendButton)!=null?_o:{},Ge=(qo=M.iconName)!=null?qo:"mic",me=(zo=Ee.size)!=null?zo:"40px",Be=(Uo=M.iconSize)!=null?Uo:me,ht=parseFloat(Be)||24;j.style.width=Be,j.style.height=Be,j.style.minWidth=Be,j.style.minHeight=Be;let kt=(Ko=(Jo=M.iconColor)!=null?Jo:Ee.textColor)!=null?Ko:"currentColor";j.innerHTML="";let Dt=re(Ge,ht,kt,2);Dt?j.appendChild(Dt):j.textContent="\u{1F3A4}";let Ht=(Yo=M.backgroundColor)!=null?Yo:Ee.backgroundColor;Ht?(j.style.backgroundColor=Ht,j.classList.remove("tvw-bg-cw-primary")):(j.style.backgroundColor="",j.classList.add("tvw-bg-cw-primary")),kt?(j.style.color=kt,j.classList.remove("tvw-text-white")):!kt&&!Ee.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),M.borderWidth?(j.style.borderWidth=M.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),M.borderColor?j.style.borderColor=M.borderColor:j.style.borderColor="",M.paddingX?(j.style.paddingLeft=M.paddingX,j.style.paddingRight=M.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),M.paddingY?(j.style.paddingTop=M.paddingY,j.style.paddingBottom=M.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let lt=Ze==null?void 0:Ze.querySelector(".tvw-send-button-tooltip"),jt=(Vo=M.tooltipText)!=null?Vo:"Start voice recognition";if(((Xo=M.showTooltip)!=null?Xo:!1)&&jt)if(lt)lt.textContent=jt,lt.style.display="";else{let xt=document.createElement("div");xt.className="tvw-send-button-tooltip",xt.textContent=jt,Ze==null||Ze.insertBefore(xt,j)}else lt&&(lt.style.display="none");Ze.style.display="",j.disabled=F.isStreaming()}else j&&Ze&&(Ze.style.display="none",Ot&&Ye());if(((Go=t.attachments)==null?void 0:Go.enabled)===!0)if(!z||!ke){let M=(Qo=t.attachments)!=null?Qo:{},Ge=(ei=((Zo=t.sendButton)!=null?Zo:{}).size)!=null?ei:"40px";ge||(ge=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ge.style.display="none",gt.insertBefore(ge,pe)),R||(R=document.createElement("input"),R.type="file",R.accept=((ti=M.allowedTypes)!=null?ti:an).join(","),R.multiple=((ni=M.maxFiles)!=null?ni:4)>1,R.style.display="none",R.setAttribute("aria-label","Attach files"),gt.insertBefore(R,pe)),z=p("div","tvw-send-button-wrapper"),ke=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),ke.type="button",ke.setAttribute("aria-label",(si=M.buttonTooltipText)!=null?si:"Attach file");let me=(ri=M.buttonIconName)!=null?ri:"paperclip",Be=Ge,ht=parseFloat(Be)||40,kt=Math.round(ht*.6);ke.style.width=Be,ke.style.height=Be,ke.style.minWidth=Be,ke.style.minHeight=Be,ke.style.fontSize="18px",ke.style.lineHeight="1",ke.style.backgroundColor="transparent",ke.style.color="var(--cw-primary, #111827)",ke.style.border="none",ke.style.borderRadius="6px",ke.style.transition="background-color 0.15s ease",ke.addEventListener("mouseenter",()=>{ke.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),ke.addEventListener("mouseleave",()=>{ke.style.backgroundColor="transparent"});let Dt=re(me,kt,"currentColor",1.5);Dt?ke.appendChild(Dt):ke.textContent="\u{1F4CE}",ke.addEventListener("click",jt=>{jt.preventDefault(),R==null||R.click()}),z.appendChild(ke);let Ht=(oi=M.buttonTooltipText)!=null?oi:"Attach file",lt=p("div","tvw-send-button-tooltip");lt.textContent=Ht,z.appendChild(lt),Lt.append(z),!de&&R&&ge&&(de=wn.fromConfig(M),de.setPreviewsContainer(ge),R.addEventListener("change",async()=>{de&&(R!=null&&R.files)&&(await de.handleFileSelect(R.files),R.value="")}))}else{z.style.display="";let M=(ii=t.attachments)!=null?ii:{};R&&(R.accept=((ai=M.allowedTypes)!=null?ai:an).join(","),R.multiple=((li=M.maxFiles)!=null?li:4)>1),de&&de.updateConfig({allowedTypes:M.allowedTypes,maxFileSize:M.maxFileSize,maxFiles:M.maxFiles})}else z&&(z.style.display="none"),de&&de.clearAttachments();let ut=(di=t.sendButton)!=null?di:{},hs=(ci=ut.useIcon)!=null?ci:!1,Kn=(ui=ut.iconText)!=null?ui:"\u2191",pn=ut.iconName,gn=(pi=ut.tooltipText)!=null?pi:"Send message",ma=(gi=ut.showTooltip)!=null?gi:!1,Yn=(mi=ut.size)!=null?mi:"40px",fs=ut.backgroundColor,Yt=ut.textColor;if(hs){if(J.style.width=Yn,J.style.height=Yn,J.style.minWidth=Yn,J.style.minHeight=Yn,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",pn){let M=parseFloat(Yn)||24,Ee=Yt&&typeof Yt=="string"&&Yt.trim()?Yt.trim():"currentColor",Ge=re(pn,M,Ee,2);Ge?(J.appendChild(Ge),J.style.color=Ee):(J.textContent=Kn,Yt?J.style.color=Yt:J.classList.add("tvw-text-white"))}else J.textContent=Kn,Yt?J.style.color=Yt:J.classList.add("tvw-text-white");J.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",fs?(J.style.backgroundColor=fs,J.classList.remove("tvw-bg-cw-primary")):J.classList.add("tvw-bg-cw-primary")}else J.textContent=(fi=(hi=t.copy)==null?void 0:hi.sendButtonLabel)!=null?fi:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.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",fs?(J.style.backgroundColor=fs,J.classList.remove("tvw-bg-cw-accent")):J.classList.add("tvw-bg-cw-accent"),Yt?J.style.color=Yt:J.classList.add("tvw-text-white");ut.borderWidth?(J.style.borderWidth=ut.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),ut.borderColor?J.style.borderColor=ut.borderColor:J.style.borderColor="",ut.paddingX?(J.style.paddingLeft=ut.paddingX,J.style.paddingRight=ut.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),ut.paddingY?(J.style.paddingTop=ut.paddingY,J.style.paddingBottom=ut.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let Vn=pt==null?void 0:pt.querySelector(".tvw-send-button-tooltip");if(ma&&gn)if(Vn)Vn.textContent=gn,Vn.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=gn,pt==null||pt.insertBefore(M,J)}else Vn&&(Vn.style.display="none");let Xn=(wi=t.statusIndicator)!=null?wi:{},ha=(vi=Xn.visible)!=null?vi:!0;if(ft.style.display=ha?"":"none",F){let M=F.getStatus(),Ee=Ge=>{var me,Be,ht,kt;return Ge==="idle"?(me=Xn.idleText)!=null?me:It.idle:Ge==="connecting"?(Be=Xn.connectingText)!=null?Be:It.connecting:Ge==="connected"?(ht=Xn.connectedText)!=null?ht:It.connected:Ge==="error"?(kt=Xn.errorText)!=null?kt:It.error:It[Ge]};ft.textContent=Ee(M)}},open(){C&&ot(!0,"api")},close(){C&&ot(!1,"api")},toggle(){C&&ot(!v,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem($n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${$n}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==$n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()},setMessage(l){return!pe||F.isStreaming()?!1:(!v&&C&&ot(!0,"system"),pe.value=l,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let u=(l==null?void 0:l.trim())||pe.value.trim();return u?(!v&&C&&ot(!0,"system"),pe.value="",pe.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){return Ot||F.isStreaming()||!De()?!1:(!v&&C&&ot(!0,"system"),Ke.manuallyDeactivated=!1,Qt(),et("user"),!0)},stopVoiceRecognition(){return Ot?(Ke.manuallyDeactivated=!0,Qt(),Ye("user"),!0):!1},injectMessage(l){return!v&&C&&ot(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!v&&C&&ot(!0,"system");let u=F.injectAssistantMessage(l);return O&&(O=!1,W&&(clearTimeout(W),W=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),u},injectUserMessage(l){return!v&&C&&ot(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!v&&C&&ot(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!v&&C&&ot(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!v&&C&&ot(!0,"system"),F.injectTestEvent(l)},__pushEventStreamEvent(l){D&&D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!X||!D||Te()},hideEventStream(){fe&&Oe()},isEventStreamVisible(){return fe},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){c(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return C&&v},isVoiceActive(){return Ke.active},getState(){return{open:C&&v,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()}},showCSATFeedback(l){!v&&C&&ot(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Fs({onSubmit:async(k,E)=>{var $;F.isClientTokenMode()&&await F.submitCSATFeedback(k,E),($=l==null?void 0:l.onSubmit)==null||$.call(l,k,E)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!v&&C&&ot(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=$s({onSubmit:async(k,E)=>{var $;F.isClientTokenMode()&&await F.submitNPSFeedback(k,E),($=l==null?void 0:l.onSubmit)==null||$.call(l,k,E)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return F.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return F.submitNPSFeedback(l,u)},destroy(){at.forEach(l=>l()),Re.remove(),h==null||h.destroy(),S==null||S.remove(),Jt&&Y.removeEventListener("click",Jt)}};if((((Br=r==null?void 0:r.debugTools)!=null?Br:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:We,getMessages:We.getMessages,getStatus:We.getStatus,getMetadata:We.getPersistentMetadata,updateMetadata:We.updatePersistentMetadata,clearHistory:()=>We.clearChat(),setVoiceActive:b=>b?We.startVoiceRecognition():We.stopVoiceRecognition()};window.AgentWidgetBrowser=u,at.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(X&&typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=k=>{let E=k.detail;(!(E!=null&&E.instanceId)||E.instanceId===l)&&We.showEventStream()},b=k=>{let E=k.detail;(!(E!=null&&E.instanceId)||E.instanceId===l)&&We.hideEventStream()};window.addEventListener("persona:showEventStream",u),window.addEventListener("persona:hideEventStream",b),at.push(()=>{window.removeEventListener("persona:showEventStream",u),window.removeEventListener("persona:hideEventStream",b)})}let je=al(t.persistState);if(je&&C){let l=ll(je.storage),u=`${je.keyPrefix}widget-open`,b=`${je.keyPrefix}widget-voice`,k=`${je.keyPrefix}widget-voice-mode`;if(l){let E=((Rr=je.persist)==null?void 0:Rr.openState)&&l.getItem(u)==="true",$=((Fr=je.persist)==null?void 0:Fr.voiceState)&&l.getItem(b)==="true",ve=(($r=je.persist)==null?void 0:$r.voiceState)&&l.getItem(k)==="true";if(E&&setTimeout(()=>{We.open(),setTimeout(()=>{var le;if($||ve)We.startVoiceRecognition();else if((le=je.persist)!=null&&le.focusInput){let ye=e.querySelector("textarea");ye&&ye.focus()}},100)},0),(Or=je.persist)!=null&&Or.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Nr=je.persist)!=null&&Nr.voiceState&&(s.on("voice:state",le=>{l.setItem(b,le.active?"true":"false")}),s.on("user:message",le=>{l.setItem(k,le.viaVoice?"true":"false")})),je.clearOnChatClear){let le=()=>{l.removeItem(u),l.removeItem(b),l.removeItem(k)},ye=()=>le();window.addEventListener("persona:clear-chat",ye),at.push(()=>{window.removeEventListener("persona:clear-chat",ye)})}}}return We};var pr={},dl=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},cl=()=>{try{if(typeof pr!="undefined"&&pr.url)return new URL("../widget.css",pr.url).href}catch{}return null},ia=e=>{let n=cl(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,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 r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},gr=e=>{var g,w,c,m;let n=dl(e.target),r=document.createElement("div");r.className="persona-host";let t=(c=(w=(g=e.config)==null?void 0:g.launcher)==null?void 0:w.enabled)!=null?c:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let f=r.attachShadow({mode:"open"});i=f,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"),f.appendChild(s),ia(f)}else i=r,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"),r.appendChild(s),ia(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=Os(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var aa={name:"@runtypelabs/persona",version:"1.43.6",description:"Themeable, pluggable 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","fake-indexeddb":"^6.2.5",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:["ai","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 Cn=aa.version;function nn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function pl(e){if(e)return{getHeaders:nn(e.getHeaders),onFeedback:nn(e.onFeedback),onCopy:nn(e.onCopy),requestMiddleware:nn(e.requestMiddleware),actionHandlers:nn(e.actionHandlers),actionParsers:nn(e.actionParsers),postprocessMessage:nn(e.postprocessMessage),contextProviders:nn(e.contextProviders),streamParser:nn(e.streamParser)}}var la=`({ text, message }: any) => {
60
+ `}if(!I){let fn="max-height: -moz-available !important; max-height: stretch !important;",wn=l?"":"padding-top: 1.25em !important;";Fe.style.cssText+=fn+wn}};Tn(),$s(e,t);let rt=[];X&&rt.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),Z==null||Z.destroy(),Z=null,D==null||D.destroy(),D=null,N=null});let Jt=null,qn=()=>{Jt&&(Jt(),Jt=null),t.colorScheme==="auto"&&(Jt=_i(()=>{$s(e,t)}))};qn(),rt.push(()=>{Jt&&(Jt(),Jt=null)});let an=Gi(At),Kt=null,F,ln=!1,Gt=!0,un=0,zn=0,Qt=null,Zt=!1,Mn=0,Ln=!1,ps=125,gs=2e3,ms=5,Un=50,kn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Jn=(Hr=(Pr=t.voiceRecognition)==null?void 0:Pr.autoResume)!=null?Hr:!1,Kn=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},en=()=>{c(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},hs=()=>{var L,A;if(((L=t.voiceRecognition)==null?void 0:L.enabled)===!1)return;let l=br(a.voiceState),u=!!l.active,b=Number((A=l.timestamp)!=null?A:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-b<il&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,hn("restore"))},1e3)},fs=()=>F?ra(F.getMessages()).filter(l=>!l.__skipPersist):[];function Yn(l){if(!(i!=null&&i.save))return;let b={messages:l?ra(l):F?fs():[],metadata:a};try{let L=i.save(b);L instanceof Promise&&L.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(L){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)}}let pn=(l=!1)=>{if(!Gt)return;let u=Date.now();Zt&&u<Mn&&!l||(Zt&&u>=Mn&&(Zt=!1),!(!l&&!ln)&&(u-zn<ps||(zn=u,Qt&&cancelAnimationFrame(Qt),Qt=requestAnimationFrame(()=>{Zt||!Gt||(Ln=!0,$e.scrollTop=$e.scrollHeight,un=$e.scrollTop,requestAnimationFrame(()=>{Ln=!1}),Qt=null)}))))},tn=null,ws=()=>Fe.querySelector("#persona-scroll-container")||$e,vs=(l,u=500)=>{let b=l.scrollTop,L=l.clientHeight,A=l.scrollHeight,$=A-b;if(b+L>=A-2||Math.abs($)<5)return;tn!==null&&(cancelAnimationFrame(tn),tn=null);let ce=performance.now(),be=Ce=>1-Math.pow(1-Ce,3),Te=Ce=>{let Pe=l.scrollHeight;Pe!==A&&(A=Pe,$=A-b);let G=Ce-ce,I=Math.min(G/u,1),we=be(I),xe=b+$*we;l.scrollTop=xe,I<1?tn=requestAnimationFrame(Te):(l.scrollTop=l.scrollHeight,tn=null)};tn=requestAnimationFrame(Te)},ys=l=>{let u=new Map;l.forEach(b=>{let L=kn.get(b.id);u.set(b.id,{streaming:b.streaming,role:b.role}),!L&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(L!=null&&L.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b)}),kn.clear(),u.forEach((b,L)=>{kn.set(L,b)})},gn=(l,u,b)=>{var Te,Ce,Pe,G;let L=document.createElement("div"),$=(()=>{var we;let I=o.find(xe=>xe.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((we=t.loadingIndicator)!=null&&we.render)return t.loadingIndicator.render})();u.forEach(I=>{var mt,It;let we=null,xe=o.find(K=>!!(I.variant==="reasoning"&&K.renderReasoning||I.variant==="tool"&&K.renderToolCall||!I.variant&&K.renderMessage)),Ve=(mt=t.layout)==null?void 0:mt.messages;if(xe)if(I.variant==="reasoning"&&I.reasoning&&xe.renderReasoning){if(!_)return;we=xe.renderReasoning({message:I,defaultRenderer:()=>ur(I),config:t})}else if(I.variant==="tool"&&I.toolCall&&xe.renderToolCall){if(!le)return;we=xe.renderToolCall({message:I,defaultRenderer:()=>pr(I,t),config:t})}else xe.renderMessage&&(we=xe.renderMessage({message:I,defaultRenderer:()=>{let K=Fn(I,b,Ve,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t});return I.role!=="user"&&mr(K,I,t,F),K},config:t}));if(!we&&I.role==="assistant"&&!I.variant&&t.enableComponentStreaming!==!1&&qs(I)){let je=zs(I);if(je){let Vt=_s(je,{config:t,message:I,transform:b});if(Vt){let zt=document.createElement("div");if(zt.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(" "),zt.id=`bubble-${I.id}`,zt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let dn=document.createElement("div");dn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",dn.innerHTML=b({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),zt.appendChild(dn)}zt.appendChild(Vt),we=zt}}}if(!we)if(I.variant==="reasoning"&&I.reasoning){if(!_)return;we=ur(I)}else if(I.variant==="tool"&&I.toolCall){if(!le)return;we=pr(I,t)}else{let K=(It=t.layout)==null?void 0:It.messages;K!=null&&K.renderUserMessage&&I.role==="user"?we=K.renderUserMessage({message:I,config:t,streaming:!!I.streaming}):K!=null&&K.renderAssistantMessage&&I.role==="assistant"?we=K.renderAssistantMessage({message:I,config:t,streaming:!!I.streaming}):we=Fn(I,b,K,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t}),I.role!=="user"&&we&&mr(we,I,t,F)}let He=document.createElement("div");He.className="tvw-flex",He.id=`wrapper-${I.id}`,He.setAttribute("data-wrapper-id",I.id),I.role==="user"&&He.classList.add("tvw-justify-end"),He.appendChild(we),L.appendChild(He)});let ye=u.some(I=>I.role==="assistant"&&I.streaming),ce=u[u.length-1],be=(ce==null?void 0:ce.role)==="assistant"&&!ce.streaming;if(ln&&u.some(I=>I.role==="user")&&!ye&&!be){let I={config:t,streaming:!0,location:"standalone",defaultRenderer:Sn},we=o.find(Ve=>Ve.renderLoadingIndicator),xe=null;if(we!=null&&we.renderLoadingIndicator&&(xe=we.renderLoadingIndicator(I)),xe===null&&((Te=t.loadingIndicator)!=null&&Te.render)&&(xe=t.loadingIndicator.render(I)),xe===null&&(xe=Sn()),xe){let Ve=document.createElement("div"),He=((Ce=t.loadingIndicator)==null?void 0:Ce.showBubble)!==!1;Ve.className=He?["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(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(xe);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Ve),L.appendChild(mt)}}if(!ln&&u.length>0){let I=u[u.length-1],we={config:t,lastMessage:I,messageCount:u.length},xe=o.find(He=>He.renderIdleIndicator),Ve=null;if(xe!=null&&xe.renderIdleIndicator&&(Ve=xe.renderIdleIndicator(we)),Ve===null&&((Pe=t.loadingIndicator)!=null&&Pe.renderIdle)&&(Ve=t.loadingIndicator.renderIdle(we)),Ve){let He=document.createElement("div"),mt=((G=t.loadingIndicator)==null?void 0:G.showBubble)!==!1;He.className=mt?["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(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(Ve);let It=document.createElement("div");It.className="tvw-flex",It.id="wrapper-idle-indicator",It.setAttribute("data-wrapper-id","idle-indicator"),It.appendChild(He),L.appendChild(It)}}zi(l,L),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=ws();vs(I)})})},mn=()=>{C&&(y?(Fe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-95","tvw-opacity-0"),Ae.classList.add("tvw-scale-100","tvw-opacity-100"),ne?ne.element.style.display="none":ae&&(ae.style.display="none")):(Fe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-100","tvw-opacity-100"),Ae.classList.add("tvw-scale-95","tvw-opacity-0"),ne?ne.element.style.display="":ae&&(ae.style.display="")))},tt=(l,u="user")=>{if(!C||y===l)return;let b=y;y=l,mn(),y&&(Xe(),pn(!0));let L={open:y,source:u,timestamp:Date.now()};y&&!b?s.emit("widget:opened",L):!y&&b&&s.emit("widget:closed",L),s.emit("widget:state",{open:y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()})},Wn=l=>{J.disabled=l,j&&(j.disabled=l),an.buttons.forEach(u=>{u.disabled=l})},Vn=()=>{var A,$,ye,ce,be,Te,Ce,Pe,G,I,we,xe,Ve,He;Ot.textContent=($=(A=t.copy)==null?void 0:A.welcomeTitle)!=null?$:"Hello \u{1F44B}",wt.textContent=(ce=(ye=t.copy)==null?void 0:ye.welcomeSubtitle)!=null?ce:"Ask anything about your account or products.",me.placeholder=(Te=(be=t.copy)==null?void 0:be.inputPlaceholder)!=null?Te:"How can I help...",((Pe=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?Pe:!1)||(J.textContent=(I=(G=t.copy)==null?void 0:G.sendButtonLabel)!=null?I:"Send");let u=(xe=(we=t.theme)==null?void 0:we.inputFontFamily)!=null?xe:"sans-serif",b=(He=(Ve=t.theme)==null?void 0:Ve.inputFontWeight)!=null?He:"400",L=mt=>{switch(mt){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'}};me.style.fontFamily=L(u),me.style.fontWeight=b};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{c(u=>({...u,sessionId:l}))}}),F=new Hn(t,{onMessagesChanged(l){gn(Qe,l,oe),F&&(l.some(A=>A.role==="user")?an.render([],F,me,l):an.render(t.suggestionChips,F,me,l,t.suggestionChipsConfig)),pn(!ln),ys(l);let u=[...l].reverse().find(L=>L.role==="user"),b=Ke.lastUserMessageId;u&&u.id!==b&&(Ke.lastUserMessageId=u.id,s.emit("user:message",u)),Ke.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Yn(l)},onStatusChanged(l){var L;let u=(L=t.statusIndicator)!=null?L:{},b=A=>{var $,ye,ce,be;return A==="idle"?($=u.idleText)!=null?$:Pt.idle:A==="connecting"?(ye=u.connectingText)!=null?ye:Pt.connecting:A==="connected"?(ce=u.connectedText)!=null?ce:Pt.connected:A==="error"?(be=u.errorText)!=null?be:Pt.error:Pt[A]};ft.textContent=b(l)},onStreamingChanged(l){ln=l,Wn(l),F&&gn(Qe,F.getMessages(),oe),l||pn(!0)}}),t.clientToken&&F.initClientSession().catch(l=>{t.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&F.setSSEEventCallback((l,u)=>{D==null||D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(a=br(l.metadata),x.syncFromMetadata()),(u=l.messages)!=null&&u.length&&F.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Xn=l=>{var A;l.preventDefault();let u=me.value.trim(),b=(A=ue==null?void 0:ue.hasAttachments())!=null?A:!1;if(!u&&!b)return;let L;b&&(L=[],L.push(...ue.getContentParts()),u&&L.push(Bs(u))),me.value="",me.style.height="auto",F.sendMessage(u,{contentParts:L}),b&&ue.clearAttachments()},Gn=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},Ht=null,Nt=!1,nn=null,Yt=null,Qn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,hn=(l="user")=>{var $,ye,ce,be;if(Nt||F.isStreaming())return;let u=Qn();if(!u)return;Ht=new u;let L=(ye=(($=t.voiceRecognition)!=null?$:{}).pauseDuration)!=null?ye:2e3;Ht.continuous=!0,Ht.interimResults=!0,Ht.lang="en-US";let A=me.value;Ht.onresult=Te=>{let Ce="",Pe="";for(let I=0;I<Te.results.length;I++){let we=Te.results[I],xe=we[0].transcript;we.isFinal?Ce+=xe+" ":Pe=xe}let G=A+Ce+Pe;me.value=G,nn&&clearTimeout(nn),(Ce||Pe)&&(nn=window.setTimeout(()=>{let I=me.value.trim();I&&Ht&&Nt&&(qt(),me.value="",me.style.height="auto",F.sendMessage(I,{viaVoice:!0}))},L))},Ht.onerror=Te=>{Te.error!=="no-speech"&&qt()},Ht.onend=()=>{if(Nt){let Te=me.value.trim();Te&&Te!==A.trim()&&(me.value="",me.style.height="auto",F.sendMessage(Te,{viaVoice:!0})),qt()}};try{if(Ht.start(),Nt=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),Kn(l),en(),j){Yt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let Te=(ce=t.voiceRecognition)!=null?ce:{},Ce=(be=Te.recordingBackgroundColor)!=null?be:"#ef4444",Pe=Te.recordingIconColor,G=Te.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=Ce,Pe){j.style.color=Pe;let I=j.querySelector("svg");I&&I.setAttribute("stroke",Pe)}G&&(j.style.borderColor=G),j.setAttribute("aria-label","Stop voice recognition")}}catch{qt("system")}},qt=(l="user")=>{if(Nt){if(Nt=!1,nn&&(clearTimeout(nn),nn=null),Ht){try{Ht.stop()}catch{}Ht=null}if(Ke.active=!1,Kn(l),en(),j){if(j.classList.remove("tvw-voice-recording"),Yt){j.style.backgroundColor=Yt.backgroundColor,j.style.color=Yt.color,j.style.borderColor=Yt.borderColor;let u=j.querySelector("svg");u&&u.setAttribute("stroke",Yt.color||"currentColor"),Yt=null}j.setAttribute("aria-label","Start voice recognition")}}},bs=(l,u)=>{var xe,Ve,He,mt,It,K,je;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let L=p("div","tvw-send-button-wrapper"),A=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let $=(xe=l==null?void 0:l.iconName)!=null?xe:"mic",ye=(Ve=u==null?void 0:u.size)!=null?Ve:"40px",ce=(He=l==null?void 0:l.iconSize)!=null?He:ye,be=parseFloat(ce)||24,Te=(mt=l==null?void 0:l.backgroundColor)!=null?mt:u==null?void 0:u.backgroundColor,Ce=(It=l==null?void 0:l.iconColor)!=null?It:u==null?void 0:u.textColor;A.style.width=ce,A.style.height=ce,A.style.minWidth=ce,A.style.minHeight=ce,A.style.fontSize="18px",A.style.lineHeight="1";let Pe=Ce||"currentColor",G=ie($,be,Pe,1.5);G?(A.appendChild(G),A.style.color=Pe):(A.textContent="\u{1F3A4}",A.style.color=Pe),Te?A.style.backgroundColor=Te:A.classList.add("tvw-bg-cw-primary"),Ce?A.style.color=Ce:!Ce&&!(u!=null&&u.textColor)&&A.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(A.style.borderWidth=l.borderWidth,A.style.borderStyle="solid"),l!=null&&l.borderColor&&(A.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(A.style.paddingLeft=l.paddingX,A.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(A.style.paddingTop=l.paddingY,A.style.paddingBottom=l.paddingY),L.appendChild(A);let I=(K=l==null?void 0:l.tooltipText)!=null?K:"Start voice recognition";if(((je=l==null?void 0:l.showTooltip)!=null?je:!1)&&I){let Vt=p("div","tvw-send-button-tooltip");Vt.textContent=I,L.appendChild(Vt)}return{micButton:A,micButtonWrapper:L}},In=()=>{if(Nt){let l=me.value.trim();Ke.manuallyDeactivated=!0,en(),qt("user"),l&&(me.value="",me.style.height="auto",F.sendMessage(l))}else Ke.manuallyDeactivated=!1,en(),hn("user")};j&&(j.addEventListener("click",In),rt.push(()=>{qt("system"),j&&j.removeEventListener("click",In)}));let Cs=s.on("assistant:complete",()=>{Jn&&(Ke.active||Ke.manuallyDeactivated||Jn==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&hn("auto")},600))});rt.push(Cs);let xs=s.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});rt.push(xs);let B=()=>{tt(!y,"user")},ne=null,ae=null;if(C){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:t,defaultRenderer:()=>is(t,B).element,onToggle:B});u&&(ae=u)}ae||(ne=is(t,B))}ne?e.appendChild(ne.element):ae&&e.appendChild(ae),mn(),an.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),Vn(),Wn(F.isStreaming()),pn(!0),hs();let Xe=()=>{var b,L,A,$,ye,ce,be,Te;let l=(L=(b=t.launcher)==null?void 0:b.sidebarMode)!=null?L:!1,u=l||(($=(A=t.launcher)==null?void 0:A.fullHeight)!=null?$:!1);if(!C){Ae.style.height="",Ae.style.width="";return}if(!l){let Ce=(ce=(ye=t==null?void 0:t.launcher)==null?void 0:ye.width)!=null?ce:t==null?void 0:t.launcherWidth,Pe=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";Ae.style.width=Pe,Ae.style.maxWidth=Pe}if(!u){let Ce=window.innerHeight,Pe=64,G=(Te=(be=t.launcher)==null?void 0:be.heightOffset)!=null?Te:0,I=Math.max(200,Ce-Pe),we=Math.min(640,I),xe=Math.max(200,we-G);Ae.style.height=`${xe}px`}};Xe(),window.addEventListener("resize",Xe),rt.push(()=>window.removeEventListener("resize",Xe)),un=$e.scrollTop;let pt=()=>{let l=$e.scrollTop,u=$e.scrollHeight,b=$e.clientHeight,L=u-l-b,A=Math.abs(l-un);if(un=l,!Ln&&!(A<=ms)){if(!Gt&&L<Un){Zt=!1,Gt=!0;return}Gt&&L>Un&&(Zt=!0,Mn=Date.now()+gs,Gt=!1)}};$e.addEventListener("scroll",pt,{passive:!0}),rt.push(()=>$e.removeEventListener("scroll",pt)),rt.push(()=>{Qt&&cancelAnimationFrame(Qt)});let Et=()=>{Y&&(Kt&&(Y.removeEventListener("click",Kt),Kt=null),C?(Y.style.display="",Kt=()=>{y=!1,mn()},Y.addEventListener("click",Kt)):Y.style.display="none")};Et(),(()=>{let{clearChatButton:l}=ee;l&&l.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(_n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_n}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==_n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",L)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()})})(),ut.addEventListener("submit",Xn),me.addEventListener("keydown",Gn),rt.push(()=>{ut.removeEventListener("submit",Xn),me.removeEventListener("keydown",Gn)}),rt.push(()=>{F.cancel()}),ne?rt.push(()=>{ne==null||ne.destroy()}):ae&&rt.push(()=>{ae==null||ae.remove()});let m={update(l){var Dr,jr,_r,qr,zr,Ur,Jr,Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,Lo,ko,Wo,Io,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,jo,_o,qo,zo,Uo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,hi,fi,wi,vi;let u=t.toolCall,b=t.colorScheme;t={...t,...l},Tn(),$s(e,t),t.colorScheme!==b&&qn();let L=ds.getForInstance(t.plugins);o.length=0,o.push(...L),C=(jr=(Dr=t.launcher)==null?void 0:Dr.enabled)!=null?jr:!0,E=(qr=(_r=t.launcher)==null?void 0:_r.autoExpand)!=null?qr:!1,_=(Ur=(zr=t.features)==null?void 0:zr.showReasoning)!=null?Ur:!0,le=(Kr=(Jr=t.features)==null?void 0:Jr.showToolCalls)!=null?Kr:!0;let A=X;if(X=(Vr=(Yr=t.features)==null?void 0:Yr.showEventStreamToggle)!=null?Vr:!1,X&&!A){if(D||(N=new ls(Se),D=new as(re,N),N.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),F.setSSEEventCallback((M,Me)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:M,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!q&&Q){let M=(Gr=(Xr=t.features)==null?void 0:Xr.eventStream)==null?void 0:Gr.classNames,Me="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 tvw-bg-transparent tvw-p-1"+(M!=null&&M.toggleButton?" "+M.toggleButton:"");q=p("button",Me),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let Ge=ie("activity","18px","currentColor",1.5);Ge&&q.appendChild(Ge);let fe=ee.clearChatButtonWrapper,Re=ee.closeButtonWrapper,ht=fe||Re;ht&&ht.parentNode===Q?Q.insertBefore(q,ht):Q.appendChild(q),q.addEventListener("click",()=>{ve?Ne():Le()})}}else!X&&A&&(Ne(),q&&(q.remove(),q=null),D==null||D.clear(),N==null||N.destroy(),D=null,N=null);if(((Qr=t.launcher)==null?void 0:Qr.enabled)===!1&&ne&&(ne.destroy(),ne=null),((Zr=t.launcher)==null?void 0:Zr.enabled)===!1&&ae&&(ae.remove(),ae=null),((eo=t.launcher)==null?void 0:eo.enabled)!==!1&&!ne&&!ae){let M=o.find(Me=>Me.renderLauncher);if(M!=null&&M.renderLauncher){let Me=M.renderLauncher({config:t,defaultRenderer:()=>is(t,B).element,onToggle:B});Me&&(ae=Me,e.appendChild(ae))}ae||(ne=is(t,B),e.appendChild(ne.element))}ne&&ne.update(t),vt&&((to=t.launcher)==null?void 0:to.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((no=t.launcher)==null?void 0:no.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let $=(so=t.layout)==null?void 0:so.header;if(($==null?void 0:$.layout)!==V&&Q){let M=$?Bn(t,$,{showClose:C,onClose:()=>tt(!1,"user")}):rn({config:t,showClose:C,onClose:()=>tt(!1,"user")});Q.replaceWith(M.header),Q=M.header,Ie=M.iconHolder,vt=M.headerTitle,yt=M.headerSubtitle,Y=M.closeButton,V=$==null?void 0:$.layout}else if($&&(Ie&&(Ie.style.display=$.showIcon===!1?"none":""),vt&&(vt.style.display=$.showTitle===!1?"none":""),yt&&(yt.style.display=$.showSubtitle===!1?"none":""),Y&&(Y.style.display=$.showCloseButton===!1?"none":""),ee.clearChatButtonWrapper)){let M=$.showClearChat;if(M!==void 0){ee.clearChatButtonWrapper.style.display=M?"":"none";let{closeButtonWrapper:Me}=ee;Me&&!Me.classList.contains("tvw-absolute")&&(M?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let ce=((ro=t.layout)==null?void 0:ro.showHeader)!==!1;Q&&(Q.style.display=ce?"":"none");let be=((oo=t.layout)==null?void 0:oo.showFooter)!==!1;Oe&&(Oe.style.display=be?"":"none"),C!==k?C?tt(E,"auto"):(y=!0,mn()):E!==S&&tt(E,"auto"),S=E,k=C,Xe(),Et(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&F&&gn(Qe,F.getMessages(),oe);let G=(io=t.launcher)!=null?io:{},I=(ao=G.headerIconHidden)!=null?ao:!1,we=(co=(lo=t.layout)==null?void 0:lo.header)==null?void 0:co.showIcon,xe=I||we===!1,Ve=G.headerIconName,He=(uo=G.headerIconSize)!=null?uo:"48px";if(Ie){let M=ge.querySelector(".tvw-border-b-cw-divider"),Me=M==null?void 0:M.querySelector(".tvw-flex-col");if(xe)Ie.style.display="none",M&&Me&&!M.contains(Me)&&M.insertBefore(Me,M.firstChild);else{if(Ie.style.display="",Ie.style.height=He,Ie.style.width=He,M&&Me&&(M.contains(Ie)?Ie.nextSibling!==Me&&(Ie.remove(),M.insertBefore(Ie,Me)):M.insertBefore(Ie,Me)),Ve){let fe=parseFloat(He)||24,Re=ie(Ve,fe*.6,"#ffffff",2);Re?Ie.replaceChildren(Re):Ie.textContent=(po=G.agentIconText)!=null?po:"\u{1F4AC}"}else if(G.iconUrl){let fe=Ie.querySelector("img");if(fe)fe.src=G.iconUrl,fe.style.height=He,fe.style.width=He;else{let Re=document.createElement("img");Re.src=G.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=He,Re.style.width=He,Ie.replaceChildren(Re)}}else{let fe=Ie.querySelector("svg"),Re=Ie.querySelector("img");(fe||Re)&&Ie.replaceChildren(),Ie.textContent=(go=G.agentIconText)!=null?go:"\u{1F4AC}"}let Ge=Ie.querySelector("img");Ge&&(Ge.style.height=He,Ge.style.width=He)}}let mt=(ho=(mo=t.layout)==null?void 0:mo.header)==null?void 0:ho.showTitle,It=(wo=(fo=t.layout)==null?void 0:fo.header)==null?void 0:wo.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=It===!1?"none":""),Y){((yo=(vo=t.layout)==null?void 0:vo.header)==null?void 0:yo.showCloseButton)===!1?Y.style.display="none":Y.style.display="";let Me=(bo=G.closeButtonSize)!=null?bo:"32px",Ge=(Co=G.closeButtonPlacement)!=null?Co:"inline";Y.style.height=Me,Y.style.width=Me;let{closeButtonWrapper:fe}=ee,Re=Ge==="top-right",ht=fe==null?void 0:fe.classList.contains("tvw-absolute");if(fe&&Re!==ht)if(fe.remove(),Re)fe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",ge.style.position="relative",ge.appendChild(fe);else{let ke=(So=(xo=G.clearChat)==null?void 0:xo.placement)!=null?So:"inline",St=(Eo=(Ao=G.clearChat)==null?void 0:Ao.enabled)!=null?Eo:!0;fe.className=St&&ke==="inline"?"":"tvw-ml-auto";let Ft=ge.querySelector(".tvw-border-b-cw-divider");Ft&&Ft.appendChild(fe)}if(G.closeButtonColor?(Y.style.color=G.closeButtonColor,Y.classList.remove("tvw-text-cw-muted")):(Y.style.color="",Y.classList.add("tvw-text-cw-muted")),G.closeButtonBackgroundColor?(Y.style.backgroundColor=G.closeButtonBackgroundColor,Y.classList.remove("hover:tvw-bg-gray-100")):(Y.style.backgroundColor="",Y.classList.add("hover:tvw-bg-gray-100")),G.closeButtonBorderWidth||G.closeButtonBorderColor){let ke=G.closeButtonBorderWidth||"0px",St=G.closeButtonBorderColor||"transparent";Y.style.border=`${ke} solid ${St}`,Y.classList.remove("tvw-border-none")}else Y.style.border="",Y.classList.add("tvw-border-none");G.closeButtonBorderRadius?(Y.style.borderRadius=G.closeButtonBorderRadius,Y.classList.remove("tvw-rounded-full")):(Y.style.borderRadius="",Y.classList.add("tvw-rounded-full")),G.closeButtonPaddingX?(Y.style.paddingLeft=G.closeButtonPaddingX,Y.style.paddingRight=G.closeButtonPaddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),G.closeButtonPaddingY?(Y.style.paddingTop=G.closeButtonPaddingY,Y.style.paddingBottom=G.closeButtonPaddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let kt=(To=G.closeButtonIconName)!=null?To:"x",Dt=(Mo=G.closeButtonIconText)!=null?Mo:"\xD7";Y.innerHTML="";let Bt=ie(kt,"20px",G.closeButtonColor||"",2);Bt?Y.appendChild(Bt):Y.textContent=Dt;let ot=(Lo=G.closeButtonTooltipText)!=null?Lo:"Close chat",jt=(ko=G.closeButtonShowTooltip)!=null?ko:!0;if(Y.setAttribute("aria-label",ot),fe&&(fe._cleanupTooltip&&(fe._cleanupTooltip(),delete fe._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!Y)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let ss=p("div");ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(ss);let vn=Y.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${vn.left+vn.width/2}px`,ke.style.top=`${vn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};fe.addEventListener("mouseenter",St),fe.addEventListener("mouseleave",Ft),Y.addEventListener("focus",St),Y.addEventListener("blur",Ft),fe._cleanupTooltip=()=>{Ft(),fe&&(fe.removeEventListener("mouseenter",St),fe.removeEventListener("mouseleave",Ft)),Y&&(Y.removeEventListener("focus",St),Y.removeEventListener("blur",Ft))}}}let{clearChatButton:K,clearChatButtonWrapper:je}=ee;if(K){let M=(Wo=G.clearChat)!=null?Wo:{},Me=(Io=M.enabled)!=null?Io:!0,Ge=(Ho=(Po=t.layout)==null?void 0:Po.header)==null?void 0:Ho.showClearChat,fe=Ge!==void 0?Ge:Me,Re=(Bo=M.placement)!=null?Bo:"inline";if(je){je.style.display=fe?"":"none";let{closeButtonWrapper:ht}=ee;ht&&!ht.classList.contains("tvw-absolute")&&(fe?ht.classList.remove("tvw-ml-auto"):ht.classList.add("tvw-ml-auto"));let kt=Re==="top-right",Dt=je.classList.contains("tvw-absolute");if(kt!==Dt&&fe){if(je.remove(),kt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",ge.style.position="relative",ge.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ot=ge.querySelector(".tvw-border-b-cw-divider"),jt=ee.closeButtonWrapper;ot&&jt&&jt.parentElement===ot?ot.insertBefore(je,jt):ot&&ot.appendChild(je)}let Bt=ee.closeButtonWrapper;Bt&&!Bt.classList.contains("tvw-absolute")&&(kt?Bt.classList.add("tvw-ml-auto"):Bt.classList.remove("tvw-ml-auto"))}}if(fe){let ht=(Ro=M.size)!=null?Ro:"32px";K.style.height=ht,K.style.width=ht;let kt=(Fo=M.iconName)!=null?Fo:"refresh-cw",Dt=($o=M.iconColor)!=null?$o:"";K.innerHTML="";let Bt=ie(kt,"20px",Dt||"",2);if(Bt&&K.appendChild(Bt),Dt?(K.style.color=Dt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),M.backgroundColor?(K.style.backgroundColor=M.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let ke=M.borderWidth||"0px",St=M.borderColor||"transparent";K.style.border=`${ke} solid ${St}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");M.borderRadius?(K.style.borderRadius=M.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),M.paddingX?(K.style.paddingLeft=M.paddingX,K.style.paddingRight=M.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),M.paddingY?(K.style.paddingTop=M.paddingY,K.style.paddingBottom=M.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let ot=(Oo=M.tooltipText)!=null?Oo:"Clear chat",jt=(No=M.showTooltip)!=null?No:!0;if(K.setAttribute("aria-label",ot),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!K)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let ss=p("div");ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(ss);let vn=K.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${vn.left+vn.width/2}px`,ke.style.top=`${vn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};je.addEventListener("mouseenter",St),je.addEventListener("mouseleave",Ft),K.addEventListener("focus",St),K.addEventListener("blur",Ft),je._cleanupTooltip=()=>{Ft(),je&&(je.removeEventListener("mouseenter",St),je.removeEventListener("mouseleave",Ft)),K&&(K.removeEventListener("focus",St),K.removeEventListener("blur",Ft))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[cs],zt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[An.message,An.messageAndClick];x=us({parsers:Vt,handlers:zt,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),oe=oa(t,x,H),F.updateConfig(t),gn(Qe,F.getMessages(),oe),an.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),Vn(),Wn(F.isStreaming());let dn=((Do=t.voiceRecognition)==null?void 0:Do.enabled)===!0,Ss=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(dn&&Ss)if(!j||!Ze){let M=bs(t.voiceRecognition,t.sendButton);M&&(j=M.micButton,Ze=M.micButtonWrapper,Mt.insertBefore(Ze,ct),j.addEventListener("click",In),j.disabled=F.isStreaming())}else{let M=(jo=t.voiceRecognition)!=null?jo:{},Me=(_o=t.sendButton)!=null?_o:{},Ge=(qo=M.iconName)!=null?qo:"mic",fe=(zo=Me.size)!=null?zo:"40px",Re=(Uo=M.iconSize)!=null?Uo:fe,ht=parseFloat(Re)||24;j.style.width=Re,j.style.height=Re,j.style.minWidth=Re,j.style.minHeight=Re;let kt=(Ko=(Jo=M.iconColor)!=null?Jo:Me.textColor)!=null?Ko:"currentColor";j.innerHTML="";let Dt=ie(Ge,ht,kt,2);Dt?j.appendChild(Dt):j.textContent="\u{1F3A4}";let Bt=(Yo=M.backgroundColor)!=null?Yo:Me.backgroundColor;Bt?(j.style.backgroundColor=Bt,j.classList.remove("tvw-bg-cw-primary")):(j.style.backgroundColor="",j.classList.add("tvw-bg-cw-primary")),kt?(j.style.color=kt,j.classList.remove("tvw-text-white")):!kt&&!Me.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),M.borderWidth?(j.style.borderWidth=M.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),M.borderColor?j.style.borderColor=M.borderColor:j.style.borderColor="",M.paddingX?(j.style.paddingLeft=M.paddingX,j.style.paddingRight=M.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),M.paddingY?(j.style.paddingTop=M.paddingY,j.style.paddingBottom=M.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let ot=Ze==null?void 0:Ze.querySelector(".tvw-send-button-tooltip"),jt=(Vo=M.tooltipText)!=null?Vo:"Start voice recognition";if(((Xo=M.showTooltip)!=null?Xo:!1)&&jt)if(ot)ot.textContent=jt,ot.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=jt,Ze==null||Ze.insertBefore(St,j)}else ot&&(ot.style.display="none");Ze.style.display="",j.disabled=F.isStreaming()}else j&&Ze&&(Ze.style.display="none",Nt&&qt());if(((Go=t.attachments)==null?void 0:Go.enabled)===!0)if(!z||!We){let M=(Qo=t.attachments)!=null?Qo:{},Ge=(ei=((Zo=t.sendButton)!=null?Zo:{}).size)!=null?ei:"40px";he||(he=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),he.style.display="none",ut.insertBefore(he,me)),R||(R=document.createElement("input"),R.type="file",R.accept=((ti=M.allowedTypes)!=null?ti:cn).join(","),R.multiple=((ni=M.maxFiles)!=null?ni:4)>1,R.style.display="none",R.setAttribute("aria-label","Attach files"),ut.insertBefore(R,me)),z=p("div","tvw-send-button-wrapper"),We=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),We.type="button",We.setAttribute("aria-label",(si=M.buttonTooltipText)!=null?si:"Attach file");let fe=(ri=M.buttonIconName)!=null?ri:"paperclip",Re=Ge,ht=parseFloat(Re)||40,kt=Math.round(ht*.6);We.style.width=Re,We.style.height=Re,We.style.minWidth=Re,We.style.minHeight=Re,We.style.fontSize="18px",We.style.lineHeight="1",We.style.backgroundColor="transparent",We.style.color="var(--cw-primary, #111827)",We.style.border="none",We.style.borderRadius="6px",We.style.transition="background-color 0.15s ease",We.addEventListener("mouseenter",()=>{We.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),We.addEventListener("mouseleave",()=>{We.style.backgroundColor="transparent"});let Dt=ie(fe,kt,"currentColor",1.5);Dt?We.appendChild(Dt):We.textContent="\u{1F4CE}",We.addEventListener("click",jt=>{jt.preventDefault(),R==null||R.click()}),z.appendChild(We);let Bt=(oi=M.buttonTooltipText)!=null?oi:"Attach file",ot=p("div","tvw-send-button-tooltip");ot.textContent=Bt,z.appendChild(ot),Wt.append(z),!ue&&R&&he&&(ue=Cn.fromConfig(M),ue.setPreviewsContainer(he),R.addEventListener("change",async()=>{ue&&(R!=null&&R.files)&&(await ue.handleFileSelect(R.files),R.value="")}))}else{z.style.display="";let M=(ii=t.attachments)!=null?ii:{};R&&(R.accept=((ai=M.allowedTypes)!=null?ai:cn).join(","),R.multiple=((li=M.maxFiles)!=null?li:4)>1),ue&&ue.updateConfig({allowedTypes:M.allowedTypes,maxFileSize:M.maxFileSize,maxFiles:M.maxFiles})}else z&&(z.style.display="none"),ue&&ue.clearAttachments();let dt=(di=t.sendButton)!=null?di:{},As=(ci=dt.useIcon)!=null?ci:!1,Zn=(ui=dt.iconText)!=null?ui:"\u2191",fn=dt.iconName,wn=(pi=dt.tooltipText)!=null?pi:"Send message",ma=(gi=dt.showTooltip)!=null?gi:!1,es=(mi=dt.size)!=null?mi:"40px",Es=dt.backgroundColor,Xt=dt.textColor;if(As){if(J.style.width=es,J.style.height=es,J.style.minWidth=es,J.style.minHeight=es,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",fn){let M=parseFloat(es)||24,Me=Xt&&typeof Xt=="string"&&Xt.trim()?Xt.trim():"currentColor",Ge=ie(fn,M,Me,2);Ge?(J.appendChild(Ge),J.style.color=Me):(J.textContent=Zn,Xt?J.style.color=Xt:J.classList.add("tvw-text-white"))}else J.textContent=Zn,Xt?J.style.color=Xt:J.classList.add("tvw-text-white");J.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Es?(J.style.backgroundColor=Es,J.classList.remove("tvw-bg-cw-primary")):J.classList.add("tvw-bg-cw-primary")}else J.textContent=(fi=(hi=t.copy)==null?void 0:hi.sendButtonLabel)!=null?fi:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.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",Es?(J.style.backgroundColor=Es,J.classList.remove("tvw-bg-cw-accent")):J.classList.add("tvw-bg-cw-accent"),Xt?J.style.color=Xt:J.classList.add("tvw-text-white");dt.borderWidth?(J.style.borderWidth=dt.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),dt.borderColor?J.style.borderColor=dt.borderColor:J.style.borderColor="",dt.paddingX?(J.style.paddingLeft=dt.paddingX,J.style.paddingRight=dt.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),dt.paddingY?(J.style.paddingTop=dt.paddingY,J.style.paddingBottom=dt.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let ts=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(ma&&wn)if(ts)ts.textContent=wn,ts.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=wn,ct==null||ct.insertBefore(M,J)}else ts&&(ts.style.display="none");let ns=(wi=t.statusIndicator)!=null?wi:{},ha=(vi=ns.visible)!=null?vi:!0;if(ft.style.display=ha?"":"none",F){let M=F.getStatus(),Me=Ge=>{var fe,Re,ht,kt;return Ge==="idle"?(fe=ns.idleText)!=null?fe:Pt.idle:Ge==="connecting"?(Re=ns.connectingText)!=null?Re:Pt.connecting:Ge==="connected"?(ht=ns.connectedText)!=null?ht:Pt.connected:Ge==="error"?(kt=ns.errorText)!=null?kt:Pt.error:Pt[Ge]};ft.textContent=Me(M)}},open(){C&&tt(!0,"api")},close(){C&&tt(!1,"api")},toggle(){C&&tt(!y,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(_n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_n}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==_n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()},setMessage(l){return!me||F.isStreaming()?!1:(!y&&C&&tt(!0,"system"),me.value=l,me.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let u=(l==null?void 0:l.trim())||me.value.trim();return u?(!y&&C&&tt(!0,"system"),me.value="",me.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){return Nt||F.isStreaming()||!Qn()?!1:(!y&&C&&tt(!0,"system"),Ke.manuallyDeactivated=!1,en(),hn("user"),!0)},stopVoiceRecognition(){return Nt?(Ke.manuallyDeactivated=!0,en(),qt("user"),!0):!1},injectMessage(l){return!y&&C&&tt(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!y&&C&&tt(!0,"system");let u=F.injectAssistantMessage(l);return O&&(O=!1,W&&(clearTimeout(W),W=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),u},injectUserMessage(l){return!y&&C&&tt(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!y&&C&&tt(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!y&&C&&tt(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!y&&C&&tt(!0,"system"),F.injectTestEvent(l)},__pushEventStreamEvent(l){D&&D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!X||!D||Le()},hideEventStream(){ve&&Ne()},isEventStreamVisible(){return ve},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){c(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return C&&y},isVoiceActive(){return Ke.active},getState(){return{open:C&&y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()}},showCSATFeedback(l){!y&&C&&tt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Us({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitCSATFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!y&&C&&tt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Js({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitNPSFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return F.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return F.submitNPSFeedback(l,u)},destroy(){rt.forEach(l=>l()),Fe.remove(),ne==null||ne.destroy(),ae==null||ae.remove(),Kt&&Y.removeEventListener("click",Kt)}};if((((Br=r==null?void 0:r.debugTools)!=null?Br:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:m,getMessages:m.getMessages,getStatus:m.getStatus,getMetadata:m.getPersistentMetadata,updateMetadata:m.updatePersistentMetadata,clearHistory:()=>m.clearChat(),setVoiceActive:b=>b?m.startVoiceRecognition():m.stopVoiceRecognition()};window.AgentWidgetBrowser=u,rt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(X&&typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.showEventStream()},b=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.hideEventStream()};window.addEventListener("persona:showEventStream",u),window.addEventListener("persona:hideEventStream",b),rt.push(()=>{window.removeEventListener("persona:showEventStream",u),window.removeEventListener("persona:hideEventStream",b)})}let P=al(t.persistState);if(P&&C){let l=ll(P.storage),u=`${P.keyPrefix}widget-open`,b=`${P.keyPrefix}widget-voice`,L=`${P.keyPrefix}widget-voice-mode`;if(l){let A=((Rr=P.persist)==null?void 0:Rr.openState)&&l.getItem(u)==="true",$=((Fr=P.persist)==null?void 0:Fr.voiceState)&&l.getItem(b)==="true",ye=(($r=P.persist)==null?void 0:$r.voiceState)&&l.getItem(L)==="true";if(A&&setTimeout(()=>{m.open(),setTimeout(()=>{var ce;if($||ye)m.startVoiceRecognition();else if((ce=P.persist)!=null&&ce.focusInput){let be=e.querySelector("textarea");be&&be.focus()}},100)},0),(Or=P.persist)!=null&&Or.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Nr=P.persist)!=null&&Nr.voiceState&&(s.on("voice:state",ce=>{l.setItem(b,ce.active?"true":"false")}),s.on("user:message",ce=>{l.setItem(L,ce.viaVoice?"true":"false")})),P.clearOnChatClear){let ce=()=>{l.removeItem(u),l.removeItem(b),l.removeItem(L)},be=()=>ce();window.addEventListener("persona:clear-chat",be),rt.push(()=>{window.removeEventListener("persona:clear-chat",be)})}}}return m};var Cr={},dl=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},cl=()=>{try{if(typeof Cr!="undefined"&&Cr.url)return new URL("../widget.css",Cr.url).href}catch{}return null},ia=e=>{let n=cl(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,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 r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},xr=e=>{var g,w,c,h;let n=dl(e.target),r=document.createElement("div");r.className="persona-host";let t=(c=(w=(g=e.config)==null?void 0:g.launcher)==null?void 0:w.enabled)!=null?c:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let f=r.attachShadow({mode:"open"});i=f,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"),f.appendChild(s),ia(f)}else i=r,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"),r.appendChild(s),ia(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=Ks(s,e.config,{debugTools:e.debugTools});(h=e.onReady)==null||h.call(e);let d={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var aa={name:"@runtypelabs/persona",version:"1.44.0",description:"Themeable, pluggable 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","fake-indexeddb":"^6.2.5",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:["ai","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 En=aa.version;function on(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function pl(e){if(e)return{getHeaders:on(e.getHeaders),onFeedback:on(e.onFeedback),onCopy:on(e.onCopy),requestMiddleware:on(e.requestMiddleware),actionHandlers:on(e.actionHandlers),actionParsers:on(e.actionParsers),postprocessMessage:on(e.postprocessMessage),contextProviders:on(e.contextProviders),streamParser:on(e.streamParser)}}var la=`({ 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
@@ -129,12 +129,12 @@
129
129
  if (parsed.action === 'message') return parsed.text || '';
130
130
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
131
131
  return parsed.text || null;
132
- }`;function hl(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 Ns(e){var n,r;return(r=(n=e.parserType)!=null?n:hl(e.streamParser))!=null?r:"plain"}function Ds(e,n){let r=[];return e.toolCall&&(r.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([t,o])=>{typeof o=="string"&&r.push(`${n} ${t}: "${o}",`)}),r.push(`${n}},`)),r}function js(e,n,r){let t=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||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},`))}),r!=null&&r.onFeedback&&t.push(`${n} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&t.push(`${n} onCopy: ${r.onCopy},`),t.push(`${n}},`)),t}function _s(e,n){let r=[];if(e.markdown){let t=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(t||o)&&(r.push(`${n}markdown: {`),t&&(r.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`)}),r.push(`${n} },`)),o&&r.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${n}},`))}return r}function qs(e,n){let r=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(t||o)&&(r.push(`${n}layout: {`),t&&(r.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),o&&(r.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${n} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?r.push(`${n} ${a}: "${d}",`):typeof d=="boolean"&&r.push(`${n} ${a}: ${d},`)}),r.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(r.push(`${n} timestamp: {`),Object.entries(i).forEach(([d,g])=>{d!=="format"&&(typeof g=="string"?r.push(`${n} ${d}: "${g}",`):typeof g=="boolean"&&r.push(`${n} ${d}: ${g},`))}),r.push(`${n} },`)):typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),r.push(`${n}},`))}return r}function mr(e,n){let r=[];return e&&(e.getHeaders&&r.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${n}streamParser: ${e.streamParser},`)),r}function pa(e,n="esm",r){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let o=r?{...r,hooks:pl(r.hooks)}:void 0;return n==="esm"?fl(t,o):n==="script-installer"?yl(t):n==="script-advanced"?Cl(t,o):n==="react-component"?wl(t,o):n==="react-advanced"?vl(t,o):bl(t,o)}function fl(e,n){let r=n==null?void 0:n.hooks,t=Ns(e),o=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}",`),o&&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(...Ds(e," ")),s.push(...js(e," ",r)),s.push(..._s(e," ")),s.push(...qs(e," ")),s.push(...mr(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
- `)}function wl(e,n){let r=n==null?void 0:n.hooks,t=Ns(e),o=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}",`),o&&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(...Ds(e," ")),s.push(...js(e," ",r)),s.push(..._s(e," ")),s.push(...qs(e," ")),s.push(...mr(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
134
- `)}function vl(e,n){let r=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(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),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(...Ds(e," ")),t.push(...js(e," ",r)),t.push(..._s(e," ")),t.push(...qs(e," ")),r!=null&&r.getHeaders&&t.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&t.push(` contextProviders: ${r.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?t.push(` streamParser: ${r.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${gl}),`)),r!=null&&r.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${la}`),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(` ${la}`),t.push(" ],")),r!=null&&r.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${r.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${ca}`),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(` ${ca}`),t.push(" ],")),r!=null&&r.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${r.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 ga(e){var o;let n=Ns(e),r=n!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.clientToken&&(t.clientToken=e.clientToken),e.flowId&&(t.flowId=e.flowId),r&&(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),((o=e.suggestionChips)==null?void 0:o.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 g={};Object.entries(d).forEach(([w,c])=>{w!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(g[w]=c)}),Object.keys(g).length>0&&(i.timestamp=g)}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 yl(e){let n=ga(e),r=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist/install.global.js" data-config='${r}'></script>`}function bl(e,n){let r=n==null?void 0:n.hooks,t=Ns(e),o=t!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/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}",`),o&&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(...Ds(e," ")),s.push(...js(e," ",r)),s.push(..._s(e," ")),s.push(...qs(e," ")),s.push(...mr(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
132
+ }`;function hl(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 Ys(e){var n,r;return(r=(n=e.parserType)!=null?n:hl(e.streamParser))!=null?r:"plain"}function Vs(e,n){let r=[];return e.toolCall&&(r.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([t,o])=>{typeof o=="string"&&r.push(`${n} ${t}: "${o}",`)}),r.push(`${n}},`)),r}function Xs(e,n,r){let t=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||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},`))}),r!=null&&r.onFeedback&&t.push(`${n} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&t.push(`${n} onCopy: ${r.onCopy},`),t.push(`${n}},`)),t}function Gs(e,n){let r=[];if(e.markdown){let t=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(t||o)&&(r.push(`${n}markdown: {`),t&&(r.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`)}),r.push(`${n} },`)),o&&r.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${n}},`))}return r}function Qs(e,n){let r=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(t||o)&&(r.push(`${n}layout: {`),t&&(r.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),o&&(r.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${n} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?r.push(`${n} ${a}: "${d}",`):typeof d=="boolean"&&r.push(`${n} ${a}: ${d},`)}),r.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(r.push(`${n} timestamp: {`),Object.entries(i).forEach(([d,g])=>{d!=="format"&&(typeof g=="string"?r.push(`${n} ${d}: "${g}",`):typeof g=="boolean"&&r.push(`${n} ${d}: ${g},`))}),r.push(`${n} },`)):typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),r.push(`${n}},`))}return r}function Sr(e,n){let r=[];return e&&(e.getHeaders&&r.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${n}streamParser: ${e.streamParser},`)),r}function pa(e,n="esm",r){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let o=r?{...r,hooks:pl(r.hooks)}:void 0;return n==="esm"?fl(t,o):n==="script-installer"?yl(t):n==="script-advanced"?Cl(t,o):n==="react-component"?wl(t,o):n==="react-advanced"?vl(t,o):bl(t,o)}function fl(e,n){let r=n==null?void 0:n.hooks,t=Ys(e),o=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}",`),o&&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(...Vs(e," ")),s.push(...Xs(e," ",r)),s.push(...Gs(e," ")),s.push(...Qs(e," ")),s.push(...Sr(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
+ `)}function wl(e,n){let r=n==null?void 0:n.hooks,t=Ys(e),o=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}",`),o&&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(...Vs(e," ")),s.push(...Xs(e," ",r)),s.push(...Gs(e," ")),s.push(...Qs(e," ")),s.push(...Sr(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
134
+ `)}function vl(e,n){let r=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(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),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(...Vs(e," ")),t.push(...Xs(e," ",r)),t.push(...Gs(e," ")),t.push(...Qs(e," ")),r!=null&&r.getHeaders&&t.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&t.push(` contextProviders: ${r.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?t.push(` streamParser: ${r.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${gl}),`)),r!=null&&r.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${la}`),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(` ${la}`),t.push(" ],")),r!=null&&r.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${r.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${ca}`),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(` ${ca}`),t.push(" ],")),r!=null&&r.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${r.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 ga(e){var o;let n=Ys(e),r=n!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.clientToken&&(t.clientToken=e.clientToken),e.flowId&&(t.flowId=e.flowId),r&&(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),((o=e.suggestionChips)==null?void 0:o.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 g={};Object.entries(d).forEach(([w,c])=>{w!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(g[w]=c)}),Object.keys(g).length>0&&(i.timestamp=g)}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 yl(e){let n=ga(e),r=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${En}/dist/install.global.js" data-config='${r}'></script>`}function bl(e,n){let r=n==null?void 0:n.hooks,t=Ys(e),o=t!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${En}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${En}/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}",`),o&&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(...Vs(e," ")),s.push(...Xs(e," ",r)),s.push(...Gs(e," ")),s.push(...Qs(e," ")),s.push(...Sr(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
136
136
  `)}function Cl(e,n){let r=n==null?void 0:n.hooks,t=ga(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
137
137
  `).map((i,a)=>a===0?i:" "+i).join(`
138
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/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 r!=null&&r.getHeaders&&(s.push(` widgetConfig.getHeaders = ${r.getHeaders};`),s.push("")),r!=null&&r.contextProviders&&(s.push(` widgetConfig.contextProviders = ${r.contextProviders};`),s.push("")),r!=null&&r.streamParser?s.push(` widgetConfig.streamParser = ${r.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${ml});`),s.push(" };")),s.push(""),r!=null&&r.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${r.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${da}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${da}`),s.push(" ];")),s.push(""),r!=null&&r.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${r.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${ua}`),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(` ${ua}`),s.push(" ];")),s.push(""),r!=null&&r.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${r.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(""),r!=null&&r.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(r!=null&&r.onFeedback||r!=null&&r.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r!=null&&r.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r!=null&&r.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
139
- `)}var xl=gr;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,renderLoadingIndicatorWithFallback,validateImageFile});
138
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${En}/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 r!=null&&r.getHeaders&&(s.push(` widgetConfig.getHeaders = ${r.getHeaders};`),s.push("")),r!=null&&r.contextProviders&&(s.push(` widgetConfig.contextProviders = ${r.contextProviders};`),s.push("")),r!=null&&r.streamParser?s.push(` widgetConfig.streamParser = ${r.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${ml});`),s.push(" };")),s.push(""),r!=null&&r.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${r.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${da}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${da}`),s.push(" ];")),s.push(""),r!=null&&r.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${r.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${ua}`),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(` ${ua}`),s.push(" ];")),s.push(""),r!=null&&r.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${r.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(""),r!=null&&r.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(r!=null&&r.onFeedback||r!=null&&r.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r!=null&&r.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r!=null&&r.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
139
+ `)}var xl=xr;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,renderLoadingIndicatorWithFallback,validateImageFile});
140
140
  //# sourceMappingURL=index.cjs.map