@runtypelabs/persona 1.43.5 → 1.43.6

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.js CHANGED
@@ -1,10 +1,10 @@
1
- import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=e==null?void 0:e.markedOptions,r=new Gi({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=Qi(e==null?void 0:e.renderer);return t&&r.use({renderer:t}),i=>r.parse(i)},us=e=>e?cs({markedOptions:e.options,renderer:e.renderer}):cs(),Zi=cs(),ii=e=>Zi(e),Ms=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ai=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),oi=e=>`%%FORM_PLACEHOLDER_${e}%%`,li=(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=oi(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=oi(n.length);return n.push({token:s,type:o}),s}),r},ea=e=>{let n=us(e);return r=>{let t=[],o=li(r,t),s=n(o);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${ai(a)}"></div>`;s=s.replace(d,v)}),s}},ta=e=>{let n=[],r=li(e,n),t=ii(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="${ai(s)}"></div>`;t=t.replace(i,d)}),t};import{parse as di,STR as ci,OBJ as ui}from"partial-json";var ps=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ls=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)}},na=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`},pi=e=>e.status==="complete"?na(e):e.status==="pending"?"Waiting":"",sa=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 gi=e=>e.status==="complete"?sa(e):"Using tool...",ra=()=>{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
+ import{Marked as Qi}from"marked";var Zi=e=>{if(e)return e},cs=e=>{var o,s;let n=e==null?void 0:e.markedOptions,r=new Qi({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=Zi(e==null?void 0:e.renderer);return t&&r.use({renderer:t}),i=>r.parse(i)},us=e=>e?cs({markedOptions:e.options,renderer:e.renderer}):cs(),ea=cs(),ai=e=>ea(e),Ms=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),li=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ii=e=>`%%FORM_PLACEHOLDER_${e}%%`,di=(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=ii(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=ii(n.length);return n.push({token:s,type:o}),s}),r},ta=e=>{let n=us(e);return r=>{let t=[],o=di(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="${li(a)}"></div>`;s=s.replace(d,w)}),s}},na=e=>{let n=[],r=di(e,n),t=ai(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="${li(s)}"></div>`;t=t.replace(i,d)}),t};import{parse as ci,STR as ui,OBJ as pi}from"partial-json";var ps=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)}},sa=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`},gi=e=>e.status==="complete"?sa(e):e.status==="pending"?"Waiting":"",ra=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"?ra(e):"Using tool...",oa=()=>{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()=>{}}},gs=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},ks=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ws=()=>{var n;let e=ra();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)}},Is=()=>{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=di(r,ci|ui);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?ps(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=ps(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},oa=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?ps(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?ps(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=di(s,ci|ui),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Ps=()=>{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 ia="https://api.runtype.com/v1/dispatch",mi="https://api.runtype.com",Hs=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 aa(e){switch(e){case"json":return Is;case"regex-json":return Ws;case"xml":return Ps;case"plain":default:return ks}}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:ia,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:aa(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$/,""))||mi;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$/,""))||mi}/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 w=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:w}),w}let g=await this.buildPayload(n.messages),v=g.metadata?Object.fromEntries(Object.entries(g.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,c={sessionId:d.sessionId,messages:n.messages.filter(Hs).map(w=>{var C,b,A;return{id:w.id,role:w.role,content:(A=(b=(C=w.contentParts)!=null?C:w.llmContent)!=null?b:w.rawContent)!=null?A:w.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...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 w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}if(m.status===429){let b=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let C=new Error(w.error||"Failed to send message");throw r({type:"error",error:C}),C}if(!m.body){let w=new Error("No response body received");throw r({type:"error",error:w}),w}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(Hs).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(Hs).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,Tt,Mt,$t,Ie,ye,ee,ue,Pe,et,Et,pe,J,ct,ut,ft,Ot,wt,V,Me,vt,yt,Q,Fe,bt,Wt,Lt,j,Qe,Ae,z,F,ge,de,te,xe,$e,_,ie,ke,Ke,it,pt,Nt,Wn,nn,Jt,$,sn,Vt,ln,In,Xt,Gt,hn,fn,Zn,es,ts,Pn,wn,Ye,Hn,Bn,Qt,ns,ss,Rn,dn,Zt,rs,os,is,Es,cn,un,tt,vn,Fn,$n,On,Ht,Dt,en;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,g=()=>a+d++,v=B=>{let Ee=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,He=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Je=B.tools?B.tools.map(Ct=>({...Ct,chunks:Ct.chunks?[...Ct.chunks]:void 0})):void 0;return{...B,reasoning:Ee,toolCall:He,tools:Je}},c=B=>{r({type:"message",message:v(B)})},m=null,w={current:null},C=new Map,b=new Map,A={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},W=B=>{if(B==null)return null;try{return String(B)}catch{return null}},Y=B=>{var Ee,He,Je,Ct,xt;return W((xt=(Ct=(Je=(He=(Ee=B.stepId)!=null?Ee:B.step_id)!=null?He:B.step)!=null?Je:B.parentId)!=null?Ct:B.flowStepId)!=null?xt:B.flow_step_id)},f=B=>{var Ee,He,Je,Ct,xt,st,y;return W((y=(st=(xt=(Ct=(Je=(He=(Ee=B.callId)!=null?Ee:B.call_id)!=null?He:B.requestId)!=null?Je:B.request_id)!=null?Ct:B.toolCallId)!=null?xt:B.tool_call_id)!=null?st:B.stepId)!=null?y:B.step_id)},R=()=>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),T=(B,Ee)=>{A.lastId=Ee,B&&A.byStep.set(B,Ee)},P=(B,Ee)=>{var xt;let He=(xt=B.reasoningId)!=null?xt:B.id,Je=Y(B);if(He){let st=String(He);return T(Je,st),st}if(Je){let st=A.byStep.get(Je);if(st)return A.lastId=st,st}if(A.lastId&&!Ee)return A.lastId;if(!Ee)return null;let Ct=`reason-${g()}`;return T(Je,Ct),Ct},X=B=>{let Ee=C.get(B);if(Ee)return Ee;let He={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:B,status:"streaming",chunks:[]}};return C.set(B,He),c(He),He},O=(B,Ee)=>{x.lastId=Ee,B&&x.byCall.set(B,Ee)},se=(B,Ee)=>{var xt;let He=(xt=B.toolId)!=null?xt:B.id,Je=f(B);if(He){let st=String(He);return O(Je,st),st}if(Je){let st=x.byCall.get(Je);if(st)return x.lastId=st,st}if(x.lastId&&!Ee)return x.lastId;if(!Ee)return null;let Ct=`tool-${g()}`;return O(Je,Ct),Ct},G=B=>{let Ee=b.get(B);if(Ee)return Ee;let He={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:B,status:"pending"}};return b.set(B,He),c(He),He},U=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let Ee=Number(B);if(!Number.isNaN(Ee)&&Number.isFinite(Ee))return Ee;let He=Date.parse(B);if(!Number.isNaN(He))return He}return Date.now()},ve=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,fe=(ce=this.config.iterationDisplay)!=null?ce:"separate";for(;;){let{done:B,value:Ee}=await o.read();if(B)break;i+=s.decode(Ee,{stream:!0});let He=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()=>{}}},gs=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ls=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ws=()=>{var n;let e=oa();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)}},Is=()=>{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=ci(r,ui|pi);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?ps(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=ps(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},ia=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?ps(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?ps(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=ci(s,ui|pi),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Ps=()=>{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 aa="https://api.runtype.com/v1/dispatch",hi="https://api.runtype.com",Hs=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 la(e){switch(e){case"json":return Is;case"regex-json":return Ws;case"xml":return Ps;case"plain":default:return Ls}}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:aa,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:la(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$/,""))||hi;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$/,""))||hi}/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(Hs).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(Hs).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(Hs).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,mn,at,Ut,Wn,tn,Jt,F,nn,Vt,an,In,Xt,Gt,hn,fn,Zn,es,ts,Pn,wn,Ke,Hn,Bn,Qt,ns,ss,Rn,ln,Zt,rs,os,is,Es,dn,cn,rt,vn,Fn,$n,On,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(`
5
5
 
6
- `);i=(Ue=He.pop())!=null?Ue:"";for(let Je of He){let Ct=Je.split(`
7
- `),xt="message",st="";for(let k of Ct)k.startsWith("event:")?xt=k.replace("event:","").trim():k.startsWith("data:")&&(st+=k.replace("data:","").trim());if(!st)continue;let y;try{y=JSON.parse(st)}catch(k){r({type:"error",error:k instanceof Error?k:new Error("Failed to parse chat stream payload")});continue}let Oe=xt!=="message"?xt:(Tt=y.type)!=null?Tt:"message";if((Mt=this.onSSEEvent)==null||Mt.call(this,Oe,y),this.parseSSEEvent){w.current=m;let k=await this.handleCustomSSEEvent(y,r,w,c,g);if(w.current&&!m&&(m=w.current),k)continue}if(Oe==="reason_start"){let k=($t=P(y,!0))!=null?$t:`reason-${g()}`,h=X(k);h.reasoning=(Ie=h.reasoning)!=null?Ie:{id:k,status:"streaming",chunks:[]},h.reasoning.startedAt=(ee=h.reasoning.startedAt)!=null?ee:U((ye=y.startedAt)!=null?ye:y.timestamp),h.reasoning.completedAt=void 0,h.reasoning.durationMs=void 0,h.streaming=!0,h.reasoning.status="streaming",c(h)}else if(Oe==="reason_chunk"){let k=(Pe=(ue=P(y,!1))!=null?ue:P(y,!0))!=null?Pe:`reason-${g()}`,h=X(k);h.reasoning=(et=h.reasoning)!=null?et:{id:k,status:"streaming",chunks:[]},h.reasoning.startedAt=(pe=h.reasoning.startedAt)!=null?pe:U((Et=y.startedAt)!=null?Et:y.timestamp);let M=(ut=(ct=(J=y.reasoningText)!=null?J:y.text)!=null?ct:y.delta)!=null?ut:"";if(M&&y.hidden!==!0&&h.reasoning.chunks.push(String(M)),h.reasoning.status=y.done?"complete":"streaming",y.done){h.reasoning.completedAt=U((ft=y.completedAt)!=null?ft:y.timestamp);let ae=(Ot=h.reasoning.startedAt)!=null?Ot:Date.now();h.reasoning.durationMs=Math.max(0,((wt=h.reasoning.completedAt)!=null?wt:Date.now())-ae)}h.streaming=h.reasoning.status!=="complete",c(h)}else if(Oe==="reason_complete"){let k=(Me=(V=P(y,!1))!=null?V:P(y,!0))!=null?Me:`reason-${g()}`,h=C.get(k);if(h!=null&&h.reasoning){h.reasoning.status="complete",h.reasoning.completedAt=U((vt=y.completedAt)!=null?vt:y.timestamp);let ae=(yt=h.reasoning.startedAt)!=null?yt:Date.now();h.reasoning.durationMs=Math.max(0,((Q=h.reasoning.completedAt)!=null?Q:Date.now())-ae),h.streaming=!1,c(h)}let M=Y(y);M&&A.byStep.delete(M)}else if(Oe==="tool_start"){let k=(Fe=se(y,!0))!=null?Fe:`tool-${g()}`,h=G(k),M=(bt=h.toolCall)!=null?bt:{id:k,status:"pending"};M.name=(Wt=y.toolName)!=null?Wt:M.name,M.status="running",y.args!==void 0&&(M.args=y.args),M.startedAt=(j=M.startedAt)!=null?j:U((Lt=y.startedAt)!=null?Lt:y.timestamp),M.completedAt=void 0,M.durationMs=void 0,h.toolCall=M,h.streaming=!0,c(h)}else if(Oe==="tool_chunk"){let k=(Ae=(Qe=se(y,!1))!=null?Qe:se(y,!0))!=null?Ae:`tool-${g()}`,h=G(k),M=(z=h.toolCall)!=null?z:{id:k,status:"running"};M.startedAt=(ge=M.startedAt)!=null?ge:U((F=y.startedAt)!=null?F:y.timestamp);let ae=(xe=(te=(de=y.text)!=null?de:y.delta)!=null?te:y.message)!=null?xe:"";ae&&(M.chunks=($e=M.chunks)!=null?$e:[],M.chunks.push(String(ae))),M.status="running",h.toolCall=M,h.streaming=!0,c(h)}else if(Oe==="tool_complete"){let k=(ie=(_=se(y,!1))!=null?_:se(y,!0))!=null?ie:`tool-${g()}`,h=G(k),M=(ke=h.toolCall)!=null?ke:{id:k,status:"running"};if(M.status="complete",y.result!==void 0&&(M.result=y.result),typeof y.duration=="number"&&(M.duration=y.duration),M.completedAt=U((Ke=y.completedAt)!=null?Ke:y.timestamp),typeof y.duration=="number")M.durationMs=y.duration;else{let Ze=(it=M.startedAt)!=null?it:Date.now();M.durationMs=Math.max(0,((pt=M.completedAt)!=null?pt:Date.now())-Ze)}h.toolCall=M,h.streaming=!1,c(h);let ae=f(y);ae&&x.byCall.delete(ae)}else if(Oe==="step_chunk"){let k=y.stepType,h=y.executionType;if(k==="tool"||h==="context")continue;let M=R(),ae=(Jt=(nn=(Wn=(Nt=y.text)!=null?Nt:y.delta)!=null?Wn:y.content)!=null?nn:y.chunk)!=null?Jt:"";if(ae){let rt=(($=re.get(M.id))!=null?$:"")+ae;M.rawContent=rt,N.has(M.id)||N.set(M.id,this.createStreamParser());let Ve=N.get(M.id),at=rt.trim().startsWith("{")||rt.trim().startsWith("[");if(at&&re.set(M.id,rt),Ve.__isPlainTextParser===!0){M.content+=ae,re.delete(M.id),N.delete(M.id),M.rawContent=void 0,c(M);continue}let gt=Ve.processChunk(rt);if(gt instanceof Promise)gt.then(Ne=>{var lt;let qe=typeof Ne=="string"?Ne:(lt=Ne==null?void 0:Ne.text)!=null?lt:null;if(qe!==null&&qe.trim()!==""){let ze=m;ze&&ze.id===M.id&&(ze.content=qe,c(ze))}else if(!at&&!rt.trim().startsWith("<")){let ze=m;ze&&ze.id===M.id&&(ze.content+=ae,re.delete(ze.id),N.delete(ze.id),ze.rawContent=void 0,c(ze))}}).catch(()=>{M.content+=ae,re.delete(M.id),N.delete(M.id),M.rawContent=void 0,c(M)});else{let Ne=typeof gt=="string"?gt:(sn=gt==null?void 0:gt.text)!=null?sn:null;Ne!==null&&Ne.trim()!==""?(M.content=Ne,c(M)):!at&&!rt.trim().startsWith("<")&&(M.content+=ae,re.delete(M.id),N.delete(M.id),M.rawContent=void 0,c(M))}}if(y.isComplete){let Ze=(ln=(Vt=y.result)==null?void 0:Vt.response)!=null?ln:M.content;if(Ze){let rt=re.get(M.id),Ve=rt!=null?rt:ve(Ze);M.rawContent=Ve;let at=N.get(M.id),_e=null,gt=!1;if(at&&(_e=at.getExtractedText(),_e===null&&(_e=gs(Ve)),_e===null)){let Ne=at.processChunk(Ve);Ne instanceof Promise?(gt=!0,Ne.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let St=m;St&&St.id===M.id&&(St.content=lt,St.streaming=!1,N.delete(St.id),re.delete(St.id),c(St))}})):_e=typeof Ne=="string"?Ne:(In=Ne==null?void 0:Ne.text)!=null?In:null}if(!gt){_e!==null&&_e.trim()!==""?M.content=_e:re.has(M.id)||(M.content=ve(Ze));let Ne=N.get(M.id);if(Ne){let qe=(Xt=Ne.close)==null?void 0:Xt.call(Ne);qe instanceof Promise&&qe.catch(()=>{}),N.delete(M.id)}re.delete(M.id),M.streaming=!1,c(M)}}}}else if(Oe==="step_complete"){let k=y.stepType,h=y.executionType;if(k==="tool"||h==="context")continue;let M=(Gt=y.result)==null?void 0:Gt.response,ae=R();if(M!=null){let Ze=N.get(ae.id),rt=!1,Ve=!1;if(Ze){let at=Ze.getExtractedText(),_e=re.get(ae.id),gt=_e!=null?_e:ve(M);if(ae.rawContent=gt,at!==null&&at.trim()!=="")ae.content=at,rt=!0;else{let Ne=gs(gt);if(Ne!==null)ae.content=Ne,rt=!0;else{let qe=Ze.processChunk(gt);if(qe instanceof Promise)Ve=!0,qe.then(lt=>{var St;let ze=typeof lt=="string"?lt:(St=lt==null?void 0:lt.text)!=null?St:null;if(ze!==null&&ze.trim()!==""){let Rt=m;Rt&&Rt.id===ae.id&&(Rt.content=ze,Rt.streaming=!1,N.delete(Rt.id),re.delete(Rt.id),c(Rt))}else{let Rt=Ze.getExtractedText(),qt=m;qt&&qt.id===ae.id&&(Rt!==null&&Rt.trim()!==""?qt.content=Rt:re.has(qt.id)||(qt.content=ve(M)),qt.streaming=!1,N.delete(qt.id),re.delete(qt.id),c(qt))}});else{let lt=typeof qe=="string"?qe:(hn=qe==null?void 0:qe.text)!=null?hn:null;if(lt!==null&&lt.trim()!=="")ae.content=lt,rt=!0;else{let ze=Ze.getExtractedText();ze!==null&&ze.trim()!==""&&(ae.content=ze,rt=!0)}}}}}if(!Ve){if(!ae.rawContent){let at=re.get(ae.id);ae.rawContent=at!=null?at:ve(M)}if(!rt&&!re.has(ae.id)&&(ae.content=ve(M)),Ze){let at=(fn=Ze.close)==null?void 0:fn.call(Ze);at instanceof Promise&&at.catch(()=>{})}N.delete(ae.id),re.delete(ae.id),ae.streaming=!1,c(ae)}}else N.delete(ae.id),re.delete(ae.id),ae.streaming=!1,c(ae)}else if(Oe==="flow_complete"){let k=(Zn=y.result)==null?void 0:Zn.response;if(k!=null){let h=R(),M=re.get(h.id),ae=M!=null?M:ve(k);h.rawContent=ae;let Ze=ve(k),rt=N.get(h.id);if(rt){let _e=gs(ae);if(_e!==null)Ze=_e;else{let gt=rt.processChunk(ae);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 St=m;St&&St.id===h.id&&(St.content=lt,St.streaming=!1,c(St))}});let Ne=rt.getExtractedText();Ne!==null&&(Ze=Ne)}}N.delete(h.id),re.delete(h.id);let Ve=Ze!==h.content,at=h.streaming!==!1;Ve&&(h.content=Ze),h.streaming=!1,(Ve||at)&&c(h)}else if(m!==null){let h=m;N.delete(h.id),re.delete(h.id),h.streaming!==!1&&(h.streaming=!1,c(h))}r({type:"status",status:"idle"})}else if(Oe==="agent_start")D={executionId:y.executionId,agentId:(es=y.agentId)!=null?es:"virtual",agentName:(ts=y.agentName)!=null?ts:"",status:"running",currentIteration:0,maxIterations:(Pn=y.maxIterations)!=null?Pn:1,startedAt:U(y.startedAt)};else if(Oe==="agent_iteration_start"){if(D&&(D.currentIteration=y.iteration),fe==="separate"&&y.iteration>1){let k=m;k&&(k.streaming=!1,c(k),Z.set(y.iteration-1,k),m=null)}}else if(Oe!=="agent_turn_start"){if(Oe==="agent_turn_delta"){if(y.contentType==="text"){let k=R();k.content+=(wn=y.delta)!=null?wn:"",k.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId,agentName:D==null?void 0:D.agentName},c(k)}else if(y.contentType==="thinking"){let k=(Ye=y.turnId)!=null?Ye:`agent-think-${y.iteration}`,h=X(k);h.reasoning=(Hn=h.reasoning)!=null?Hn:{id:k,status:"streaming",chunks:[]},h.reasoning.chunks.push((Bn=y.delta)!=null?Bn:""),h.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId},c(h)}else if(y.contentType==="tool_input"){let k=(Qt=y.toolCallId)!=null?Qt:x.lastId;if(k){let h=b.get(k);h!=null&&h.toolCall&&(h.toolCall.chunks=(ns=h.toolCall.chunks)!=null?ns:[],h.toolCall.chunks.push((ss=y.delta)!=null?ss:""),c(h))}}}else if(Oe==="agent_turn_complete"){let k=y.turnId;if(k){let h=C.get(k);if(h!=null&&h.reasoning){h.reasoning.status="complete",h.reasoning.completedAt=U(y.completedAt);let M=(Rn=h.reasoning.startedAt)!=null?Rn:Date.now();h.reasoning.durationMs=Math.max(0,((dn=h.reasoning.completedAt)!=null?dn:Date.now())-M),h.streaming=!1,c(h)}}}else if(Oe==="agent_tool_start"){let k=(Zt=y.toolCallId)!=null?Zt:`agent-tool-${g()}`;O(f(y),k);let h=G(k),M=(rs=h.toolCall)!=null?rs:{id:k,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};M.name=(os=y.toolName)!=null?os:M.name,M.status="running",y.parameters!==void 0&&(M.args=y.parameters),M.startedAt=U((is=y.startedAt)!=null?is:y.timestamp),h.toolCall=M,h.streaming=!0,h.agentMetadata={executionId:y.executionId,iteration:y.iteration},c(h)}else if(Oe==="agent_tool_delta"){let k=(Es=y.toolCallId)!=null?Es:x.lastId;if(k){let h=(cn=b.get(k))!=null?cn:G(k);h.toolCall&&(h.toolCall.chunks=(un=h.toolCall.chunks)!=null?un:[],h.toolCall.chunks.push((tt=y.delta)!=null?tt:""),h.toolCall.status="running",h.streaming=!0,c(h))}}else if(Oe==="agent_tool_complete"){let k=(vn=y.toolCallId)!=null?vn:x.lastId;if(k){let h=(Fn=b.get(k))!=null?Fn:G(k);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(($n=y.completedAt)!=null?$n:y.timestamp),h.streaming=!1,c(h);let M=f(y);M&&x.byCall.delete(M)}}}else if(Oe!=="agent_iteration_complete")if(Oe==="agent_reflection"){let k=`agent-reflection-${y.executionId}-${y.iteration}`,h={id:k,role:"assistant",content:(On=y.reflection)!=null?On:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:g(),reasoning:{id:k,status:"complete",chunks:[(Ht=y.reflection)!=null?Ht:""]},agentMetadata:{executionId:y.executionId,iteration:y.iteration}};c(h)}else if(Oe==="agent_complete"){D&&(D.status=y.success?"complete":"error",D.completedAt=U(y.completedAt),D.stopReason=y.stopReason);let k=m;k&&(k.streaming=!1,c(k)),r({type:"status",status:"idle"})}else if(Oe==="agent_error"){let k=typeof y.error=="string"?y.error:(en=(Dt=y.error)==null?void 0:Dt.message)!=null?en:"Agent execution error";y.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",k):r({type:"error",error:new Error(k)})}else Oe==="agent_ping"||Oe==="error"&&y.error&&r({type:"error",error:y.error instanceof Error?y.error:new Error(String(y.error))})}}}}};function la(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function zn(){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 Un=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"?zn():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:v,streaming:c=!1}=t,w={id:d!=null?d:o==="user"?zn():o==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:g!=null?g:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:c,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(w)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var g,v,c,m,w;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(g=this.abortController)==null||g.abort();let o=zn(),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(C){let b=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!b){let A={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(A)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(C instanceof Error?(c=(v=this.callbacks).onError)==null||c.call(v,C):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(C))))}}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 v={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(v),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};import*as da from"lucide";var oe=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=da[o];return s?ca(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 ca(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,v])=>{g!=="stroke"&&d.setAttribute(g,String(v))}),o.appendChild(d)}}}),o}function ua(e){return typeof e=="string"?[{type:"text",text:e}]:e}function pa(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function ga(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function ma(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Bs(e){return{type:"text",text:e}}function ha(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 fa(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 wa(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 hi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],va=["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"],on=[...hi,...va];function ya(e){return hi.includes(e)||e.startsWith("image/")}function ms(e){return ya(e.type)}async function fi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;ms(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 wi(e,n=on,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 ba(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function vi(e,n){let r=ba(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 hs={allowedTypes:on,maxFileSize:10*1024*1024,maxFiles:4};function Ca(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xa(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:hs.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:hs.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:hs.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:hs.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 v of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,v,"count");continue}let c=wi(v,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,v,m);continue}try{let m=await fi(v),w=ms(v)?URL.createObjectURL(v):null,C={id:Ca(),file:v,previewUrl:w,contentPart:m};this.attachments.push(C),this.renderPreview(C)}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=ms(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=xa(n.file.type),d=oe(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let g=p("span");g.textContent=vi(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=oe("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 Rs=()=>{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"},Sa=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"||Rs()==="dark"?t:r},yi=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Rs())});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(Rs());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())}},fs=(e,n)=>{let r=Sa(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))})};import{Idiomorph as Aa}from"idiomorph";var bi=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;Aa.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 Jn=(e,n)=>{let r=p("button");r.type="button",r.innerHTML=`
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,((mn=S.completedAt)!=null?mn: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=(tn=(Wn=(Ut=(at=y.text)!=null?at:y.delta)!=null?Ut:y.content)!=null?Wn:y.chunk)!=null?tn:"";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=(nn=y.result)==null?void 0:nn.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=gs(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:(an=Ne==null?void 0:Ne.text)!=null?an: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=(In=Ne.close)==null?void 0:In.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=gs(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=(hn=nt.close)==null?void 0:hn.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=(fn=y.result)==null?void 0:fn.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=gs(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:(Zn=y.agentId)!=null?Zn:"virtual",agentName:(es=y.agentName)!=null?es:"",status:"running",currentIteration:0,maxIterations:(ts=y.maxIterations)!=null?ts: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+=(Pn=y.delta)!=null?Pn:"",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=(wn=y.turnId)!=null?wn:`agent-think-${y.iteration}`,h=se(H);h.reasoning=(Ke=h.reasoning)!=null?Ke:{id:H,status:"streaming",chunks:[]},h.reasoning.chunks.push((Hn=y.delta)!=null?Hn:""),h.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId},c(h)}else if(y.contentType==="tool_input"){let H=(Bn=y.toolCallId)!=null?Bn: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((ns=y.delta)!=null?ns:""),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=(ss=h.reasoning.startedAt)!=null?ss:Date.now();h.reasoning.durationMs=Math.max(0,((Rn=h.reasoning.completedAt)!=null?Rn:Date.now())-S),h.streaming=!1,c(h)}}}else if(Ve==="agent_tool_start"){let H=(ln=y.toolCallId)!=null?ln:`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=(rs=y.toolName)!=null?rs:S.name,S.status="running",y.parameters!==void 0&&(S.args=y.parameters),S.startedAt=U((os=y.startedAt)!=null?os: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=(is=y.toolCallId)!=null?is:A.lastId;if(H){let h=(Es=C.get(H))!=null?Es:X(H);h.toolCall&&(h.toolCall.chunks=(dn=h.toolCall.chunks)!=null?dn:[],h.toolCall.chunks.push((cn=y.delta)!=null?cn:""),h.toolCall.status="running",h.streaming=!0,c(h))}}else if(Ve==="agent_tool_complete"){let H=(rt=y.toolCallId)!=null?rt:A.lastId;if(H){let h=(vn=C.get(H))!=null?vn: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((Fn=y.completedAt)!=null?Fn: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:($n=y.reflection)!=null?$n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:g(),reasoning:{id:H,status:"complete",chunks:[(On=y.reflection)!=null?On:""]},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 da(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function zn(){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 Un=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"?zn():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"?zn():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,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=zn(),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 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=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};import*as ca from"lucide";var re=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=ca[o];return s?ua(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 ua(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 pa(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ga(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function ma(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function ha(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Bs(e){return{type:"text",text:e}}function fa(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 wa(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 va(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 fi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ya=["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"],rn=[...fi,...ya];function ba(e){return fi.includes(e)||e.startsWith("image/")}function ms(e){return ba(e.type)}async function wi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;ms(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 vi(e,n=rn,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 Ca(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function yi(e,n){let r=Ca(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 hs={allowedTypes:rn,maxFileSize:10*1024*1024,maxFiles:4};function xa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Sa(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:hs.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:hs.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:hs.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:hs.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=vi(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 wi(w),f=ms(w)?URL.createObjectURL(w):null,x={id:xa(),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=ms(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=Sa(n.file.type),d=re(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let g=p("span");g.textContent=yi(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 Rs=()=>{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"},Aa=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"||Rs()==="dark"?t:r},bi=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Rs())});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(Rs());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())}},fs=(e,n)=>{let r=Aa(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))})};import{Idiomorph as Ea}from"idiomorph";var Ci=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;Ea.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 Jn=(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,16 +12,16 @@ import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=
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 x,W,Y,f,R,T,P,X,O,se,G,U;let i=(x=s.launcher)!=null?x:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(W=i.title)!=null?W:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(Y=i.subtitle)!=null?Y:"Get answers fast");let g=r.querySelector(".tvw-flex-col");g&&(i.textHidden?g.style.display="none":g.style.display="");let v=r.querySelector("[data-role='launcher-icon']");if(v)if(i.agentIconHidden)v.style.display="none";else{let ve=(f=i.agentIconSize)!=null?f:"40px";if(v.style.height=ve,v.style.width=ve,v.innerHTML="",i.agentIconName){let N=parseFloat(ve)||24,re=oe(i.agentIconName,N*.6,"#ffffff",2);re?(v.appendChild(re),v.style.display=""):(v.textContent=(R=i.agentIconText)!=null?R:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(T=i.agentIconText)!=null?T:"\u{1F4AC}",v.style.display="")}let c=r.querySelector("[data-role='launcher-image']");if(c){let ve=(P=i.agentIconSize)!=null?P:"40px";c.style.height=ve,c.style.width=ve,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 ve=(X=i.callToActionIconSize)!=null?X:"32px";m.style.height=ve,m.style.width=ve,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 re=parseFloat(ve)||24,D=Math.max(re-N,8),Z=oe(i.callToActionIconName,D,"currentColor",2);Z?m.appendChild(Z):m.textContent=(O=i.callToActionIconText)!=null?O:"\u2197"}else m.textContent=(se=i.callToActionIconText)!=null?se:"\u2197"}let w=i.position&&Ut[i.position]?Ut[i.position]:Ut["bottom-right"],C="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=`${C} ${w}`;let b="1px solid #e5e7eb",A="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(G=i.border)!=null?G:b,r.style.boxShadow=(U=i.shadow)!=null?U:A},o=()=>{r.removeEventListener("click",n),r.remove()};return e&&t(e),{element:r,update:t,destroy:o}};var an=e=>{var se,G,U,ve,N,re,D,Z,fe,ce,Ue,Tt,Mt,$t,Ie,ye,ee,ue,Pe,et,Et,pe,J,ct,ut,ft,Ot,wt,V,Me,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=(se=n==null?void 0:n.launcher)!=null?se:{},s=(G=o.headerIconSize)!=null?G:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",a=(ve=o.closeButtonPlacement)!=null?ve:"inline",d=(N=o.headerIconHidden)!=null?N:!1,g=o.headerIconName,v=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(v.style.height=s,v.style.width=s,!d)if(g){let Q=parseFloat(s)||24,Fe=oe(g,Q*.6,"#ffffff",1);Fe?v.replaceChildren(Fe):v.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,v.replaceChildren(Q)}else v.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=(Tt=(Ue=n==null?void 0:n.launcher)==null?void 0:Ue.title)!=null?Tt:"Chat Assistant";let w=p("span","tvw-text-xs tvw-text-cw-muted");w.textContent=($t=(Mt=n==null?void 0:n.launcher)==null?void 0:Mt.subtitle)!=null?$t:"Here to help you get answers fast",c.append(m,w),d?t.append(c):t.append(v,c);let C=(Ie=o.clearChat)!=null?Ie:{},b=(ye=C.enabled)!=null?ye:!0,A=(ee=C.placement)!=null?ee:"inline",x=null,W=null;if(b){let Q=(ue=C.size)!=null?ue:"32px",Fe=(Pe=C.iconName)!=null?Pe:"refresh-cw",bt=(et=C.iconColor)!=null?et:"",Wt=(Et=C.backgroundColor)!=null?Et:"",Lt=(pe=C.borderWidth)!=null?pe:"",j=(J=C.borderColor)!=null?J:"",Qe=(ct=C.borderRadius)!=null?ct:"",Ae=(ut=C.paddingX)!=null?ut:"",z=(ft=C.paddingY)!=null?ft:"",F=(Ot=C.tooltipText)!=null?Ot:"Clear chat",ge=(wt=C.showTooltip)!=null?wt:!0;W=p("div",A==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),A==="top-right"&&(W.style.right="48px"),x=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"),x.style.height=Q,x.style.width=Q,x.type="button",x.setAttribute("aria-label",F);let de=oe(Fe,"20px",bt||"",1);if(de&&x.appendChild(de),bt&&(x.style.color=bt,x.classList.remove("tvw-text-cw-muted")),Wt&&(x.style.backgroundColor=Wt,x.classList.remove("hover:tvw-bg-gray-100")),Lt||j){let te=Lt||"0px",xe=j||"transparent";x.style.border=`${te} solid ${xe}`,x.classList.remove("tvw-border-none")}if(Qe&&(x.style.borderRadius=Qe,x.classList.remove("tvw-rounded-full")),Ae?(x.style.paddingLeft=Ae,x.style.paddingRight=Ae):(x.style.paddingLeft="",x.style.paddingRight=""),z?(x.style.paddingTop=z,x.style.paddingBottom=z):(x.style.paddingTop="",x.style.paddingBottom=""),W.appendChild(x),ge&&F&&x&&W){let te=null,xe=()=>{if(te||!x)return;te=p("div","tvw-clear-chat-tooltip"),te.textContent=F;let _=p("div");_.className="tvw-clear-chat-tooltip-arrow",te.appendChild(_);let ie=x.getBoundingClientRect();te.style.position="fixed",te.style.left=`${ie.left+ie.width/2}px`,te.style.top=`${ie.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},$e=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};W.addEventListener("mouseenter",xe),W.addEventListener("mouseleave",$e),x.addEventListener("focus",xe),x.addEventListener("blur",$e),W._cleanupTooltip=()=>{$e(),W&&(W.removeEventListener("mouseenter",xe),W.removeEventListener("mouseleave",$e)),x&&(x.removeEventListener("focus",xe),x.removeEventListener("blur",$e))}}A==="inline"&&t.appendChild(W)}let Y=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":b&&A==="inline"?"":"tvw-ml-auto"),f=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");f.style.height=i,f.style.width=i,f.type="button";let R=(V=o.closeButtonTooltipText)!=null?V:"Close chat",T=(Me=o.closeButtonShowTooltip)!=null?Me:!0;f.setAttribute("aria-label",R),f.style.display=r?"":"none";let P=(vt=o.closeButtonIconName)!=null?vt:"x",X=(yt=o.closeButtonIconText)!=null?yt:"\xD7",O=oe(P,"20px",o.closeButtonColor||"",1);if(O?f.appendChild(O):f.textContent=X,o.closeButtonColor?(f.style.color=o.closeButtonColor,f.classList.remove("tvw-text-cw-muted")):(f.style.color="",f.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(f.style.backgroundColor=o.closeButtonBackgroundColor,f.classList.remove("hover:tvw-bg-gray-100")):(f.style.backgroundColor="",f.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Q=o.closeButtonBorderWidth||"0px",Fe=o.closeButtonBorderColor||"transparent";f.style.border=`${Q} solid ${Fe}`,f.classList.remove("tvw-border-none")}else f.style.border="",f.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(f.style.borderRadius=o.closeButtonBorderRadius,f.classList.remove("tvw-rounded-full")):(f.style.borderRadius="",f.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(f.style.paddingLeft=o.closeButtonPaddingX,f.style.paddingRight=o.closeButtonPaddingX):(f.style.paddingLeft="",f.style.paddingRight=""),o.closeButtonPaddingY?(f.style.paddingTop=o.closeButtonPaddingY,f.style.paddingBottom=o.closeButtonPaddingY):(f.style.paddingTop="",f.style.paddingBottom=""),Y.appendChild(f),T&&R){let Q=null,Fe=()=>{if(Q)return;Q=p("div","tvw-clear-chat-tooltip"),Q.textContent=R;let Wt=p("div");Wt.className="tvw-clear-chat-tooltip-arrow",Q.appendChild(Wt);let Lt=f.getBoundingClientRect();Q.style.position="fixed",Q.style.left=`${Lt.left+Lt.width/2}px`,Q.style.top=`${Lt.top-8}px`,Q.style.transform="translate(-50%, -100%)",document.body.appendChild(Q)},bt=()=>{Q&&Q.parentNode&&(Q.parentNode.removeChild(Q),Q=null)};Y.addEventListener("mouseenter",Fe),Y.addEventListener("mouseleave",bt),f.addEventListener("focus",Fe),f.addEventListener("blur",bt),Y._cleanupTooltip=()=>{bt(),Y.removeEventListener("mouseenter",Fe),Y.removeEventListener("mouseleave",bt),f.removeEventListener("focus",Fe),f.removeEventListener("blur",bt)}}return a!=="top-right"&&t.appendChild(Y),{header:t,iconHolder:v,headerTitle:m,headerSubtitle:w,closeButton:f,closeButtonWrapper:Y,clearChatButton:x,clearChatButtonWrapper:W}},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 Ci=e=>an({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),xi=e=>{var C,b,A,x;let{config:n,showClose:r=!0,onClose:t}=e,o=(C=n==null?void 0:n.launcher)!=null?C:{},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=(b=o.title)!=null?b:"Chat Assistant",s.appendChild(i);let a=(A=o.closeButtonSize)!=null?A:"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 v=(x=o.closeButtonIconName)!=null?x:"x",c=oe(v,"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 w=p("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:g,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Si=e=>{var f,R,T,P,X,O,se,G;let{config:n,showClose:r=!0,onClose:t,onClearChat:o}=e,s=(f=n==null?void 0:n.launcher)!=null?f:{},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=(R=s.headerIconSize)!=null?R:"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 v=s.headerIconName;if(v){let U=parseFloat(d)||24,ve=oe(v,U*.5,"#ffffff",2);ve?g.replaceChildren(ve):g.textContent=(T=s.agentIconText)!=null?T:"\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=(X=s.title)!=null?X:"Chat Assistant";let w=p("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(O=s.subtitle)!=null?O:"Here to help you get answers fast",c.append(m,w),a.append(g,c);let C=(se=s.closeButtonSize)!=null?se:"32px",b=p("div",""),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=C,A.style.width=C,A.type="button",A.setAttribute("aria-label","Close chat"),A.style.display=r?"":"none";let x=(G=s.closeButtonIconName)!=null?G:"x",W=oe(x,"20px",s.closeButtonColor||"",2);W?A.appendChild(W):A.textContent="\xD7",t&&A.addEventListener("click",t),b.appendChild(A),a.appendChild(b),i.appendChild(a);let Y=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return Y.textContent="Online and ready to help",i.appendChild(Y),{header:i,iconHolder:g,headerTitle:m,headerSubtitle:w,closeButton:A,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},Fs={default:Ci,minimal:xi,expanded:Si},Ai=e=>{var n;return(n=Fs[e])!=null?n:Fs.default},Kn=(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}),v=p("div");v.style.display="none";let c=p("span"),m=p("span"),w=p("button");w.style.display="none";let C=p("div");return C.style.display="none",{header:g,iconHolder:v,headerTitle:c,headerSubtitle:m,closeButton:w,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=Ai(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 Ea=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'}},Yn=e=>{var Ie,ye,ee,ue,Pe,et,Et,pe,J,ct,ut,ft,Ot,wt,V,Me,vt,yt,Q,Fe,bt,Wt,Lt,j,Qe,Ae,z,F,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=(ye=(Ie=n==null?void 0:n.copy)==null?void 0:Ie.inputPlaceholder)!=null?ye:"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=(et=(Pe=n==null?void 0:n.theme)==null?void 0:Pe.inputFontWeight)!=null?et:"400";s.style.fontFamily=Ea(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let c=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,v);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=(Et=n==null?void 0:n.sendButton)!=null?Et:{},w=(pe=m.useIcon)!=null?pe:!1,C=(J=m.iconText)!=null?J:"\u2191",b=m.iconName,A=(ct=m.tooltipText)!=null?ct:"Send message",x=(ut=m.showTooltip)!=null?ut:!1,W=(ft=m.size)!=null?ft:"40px",Y=m.backgroundColor,f=m.textColor,R=p("div","tvw-send-button-wrapper"),T=p("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(T.type="submit",w){if(T.style.width=W,T.style.height=W,T.style.minWidth=W,T.style.minHeight=W,T.style.fontSize="18px",T.style.lineHeight="1",T.innerHTML="",b){let te=parseFloat(W)||24,xe=f&&typeof f=="string"&&f.trim()?f.trim():"currentColor",$e=oe(b,te,xe,2);$e?(T.appendChild($e),T.style.color=xe):(T.textContent=C,f?T.style.color=f:T.classList.add("tvw-text-white"))}else T.textContent=C,f?T.style.color=f:T.classList.add("tvw-text-white");Y?T.style.backgroundColor=Y:T.classList.add("tvw-bg-cw-primary")}else T.textContent=(wt=(Ot=n==null?void 0:n.copy)==null?void 0:Ot.sendButtonLabel)!=null?wt:"Send",f?T.style.color=f:T.classList.add("tvw-text-white");if(m.borderWidth&&(T.style.borderWidth=m.borderWidth,T.style.borderStyle="solid"),m.borderColor&&(T.style.borderColor=m.borderColor),m.paddingX?(T.style.paddingLeft=m.paddingX,T.style.paddingRight=m.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),m.paddingY?(T.style.paddingTop=m.paddingY,T.style.paddingBottom=m.paddingY):(T.style.paddingTop="",T.style.paddingBottom=""),x&&A){let te=p("div","tvw-send-button-tooltip");te.textContent=A,R.appendChild(te)}R.appendChild(T);let P=(V=n==null?void 0:n.voiceRecognition)!=null?V:{},X=P.enabled===!0,O=null,se=null,G=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(X&&G){se=p("div","tvw-send-button-wrapper"),O=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),O.type="button",O.setAttribute("aria-label","Start voice recognition");let te=(Me=P.iconName)!=null?Me:"mic",xe=(vt=P.iconSize)!=null?vt:W,$e=parseFloat(xe)||24,_=(yt=P.backgroundColor)!=null?yt:Y,ie=(Q=P.iconColor)!=null?Q:f;O.style.width=xe,O.style.height=xe,O.style.minWidth=xe,O.style.minHeight=xe,O.style.fontSize="18px",O.style.lineHeight="1";let ke=ie||"currentColor",Ke=oe(te,$e,ke,1.5);Ke?(O.appendChild(Ke),O.style.color=ke):(O.textContent="\u{1F3A4}",O.style.color=ke),_?O.style.backgroundColor=_:O.classList.add("tvw-bg-cw-primary"),ie?O.style.color=ie:!ie&&!f&&O.classList.add("tvw-text-white"),P.borderWidth&&(O.style.borderWidth=P.borderWidth,O.style.borderStyle="solid"),P.borderColor&&(O.style.borderColor=P.borderColor),P.paddingX&&(O.style.paddingLeft=P.paddingX,O.style.paddingRight=P.paddingX),P.paddingY&&(O.style.paddingTop=P.paddingY,O.style.paddingBottom=P.paddingY),se.appendChild(O);let it=(Fe=P.tooltipText)!=null?Fe:"Start voice recognition";if(((bt=P.showTooltip)!=null?bt:!1)&&it){let Nt=p("div","tvw-send-button-tooltip");Nt.textContent=it,se.appendChild(Nt)}}let U=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},ve=U.enabled===!0,N=null,re=null,D=null,Z=null;if(ve){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=((Lt=U.allowedTypes)!=null?Lt:on).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",(Qe=U.buttonTooltipText)!=null?Qe:"Attach file");let te=(Ae=U.buttonIconName)!=null?Ae:"paperclip",xe=W,$e=parseFloat(xe)||40,_=Math.round($e*.6);N.style.width=xe,N.style.height=xe,N.style.minWidth=xe,N.style.minHeight=xe,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 ie=oe(te,_,"currentColor",1.5);ie?N.appendChild(ie):N.textContent="\u{1F4CE}",N.addEventListener("click",it=>{it.preventDefault(),D==null||D.click()}),re.appendChild(N);let ke=(z=U.buttonTooltipText)!=null?z:"Attach file",Ke=p("div","tvw-send-button-tooltip");Ke.textContent=ke,re.appendChild(Ke)}o.addEventListener("click",te=>{te.target!==T&&te.target!==R&&te.target!==O&&te.target!==se&&te.target!==N&&te.target!==re&&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");re&&ce.append(re);let Ue=p("div","tvw-flex tvw-items-center tvw-gap-1");se&&Ue.append(se),Ue.append(R),fe.append(ce,Ue),o.append(fe);let Tt=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Mt=(F=n==null?void 0:n.statusIndicator)!=null?F:{},$t=(ge=Mt.visible)!=null?ge:!0;return Tt.style.display=$t?"":"none",Tt.textContent=(de=Mt.idleText)!=null?de:"Online",r.append(t,o,Tt),{footer:r,suggestions:t,composerForm:o,textarea:s,sendButton:T,sendButtonWrapper:R,micButton:O,micButtonWrapper:se,statusText:Tt,attachmentButton:N,attachmentButtonWrapper:re,attachmentInput:D,attachmentPreviewsContainer:Z,actionsRow:fe,leftActions:ce,rightActions:Ue}};var Ei=e=>{var d,g,v,c,m,w,C;if(!((g=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?g:!0)){let b=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),A=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(c=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?c:"100%";return b.style.width=x,A.style.width="100%",b.appendChild(A),{wrapper:b,panel:A}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},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=(C=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?C: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}},Ti=(e,n=!0)=>{var w,C,b,A,x,W,Y;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=(w=e==null?void 0:e.layout)==null?void 0:w.header,o=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,s=t?Kn(e,t,{showClose:n}):an({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=(A=(b=e==null?void 0:e.copy)==null?void 0:b.welcomeTitle)!=null?A:"Hello \u{1F44B}";let g=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");g.textContent=(W=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",a.append(d,g);let v=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let c=Yn({config:e}),m=((Y=e==null?void 0:e.layout)==null?void 0:Y.showFooter)!==!1;return o?xn(r,s,e):(s.header.style.display="none",xn(r,s,e)),r.append(i),m||(c.footer.style.display="none"),r.append(c.footer),{container:r,body:i,messagesWrapper:v,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},Li=(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()},Ta=(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},Mi=(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},Ma=(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},ki=(e,n,r)=>{var C,b,A,x,W,Y;let t=(C=n.showCopy)!=null?C:!0,o=(b=n.showUpvote)!=null?b:!0,s=(A=n.showDownvote)!=null?A:!0,i=(x=n.visibility)!=null?x:"hover",a=(W=n.align)!=null?W:"right",d=(Y=n.layout)!=null?Y:"pill-inside",g={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],v={"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} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);c.id=`actions-${e.id}`,c.setAttribute("data-actions-for",e.id);let m=null,w=(f,R,T,P)=>{let X=document.createElement("button");X.className="tvw-message-action-btn",X.setAttribute("aria-label",R),X.setAttribute("title",R),P&&X.setAttribute("data-action",P);let O=oe(f,14,"currentColor",2);return O&&X.appendChild(O),X.addEventListener("click",se=>{se.preventDefault(),se.stopPropagation(),T()}),X};if(t){let f=w("copy","Copy message",()=>{let R=e.content||"";navigator.clipboard.writeText(R).then(()=>{f.classList.add("tvw-message-action-success");let T=oe("check",14,"currentColor",2);T&&(f.innerHTML="",f.appendChild(T)),setTimeout(()=>{f.classList.remove("tvw-message-action-success");let P=oe("copy",14,"currentColor",2);P&&(f.innerHTML="",f.appendChild(P))},2e3)}).catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",T)}),r!=null&&r.onCopy&&r.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");c.appendChild(f)}if(o){let f=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,f.classList.remove("tvw-message-action-active");else{let T=c.querySelector('[data-action="downvote"]');T&&T.classList.remove("tvw-message-action-active"),m="upvote",f.classList.add("tvw-message-action-active");let P={type:"upvote",messageId:e.id,message:e};r!=null&&r.onFeedback&&r.onFeedback(P),n.onFeedback&&n.onFeedback(P)}},"upvote");c.appendChild(f)}if(s){let f=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,f.classList.remove("tvw-message-action-active");else{let T=c.querySelector('[data-action="upvote"]');T&&T.classList.remove("tvw-message-action-active"),m="downvote",f.classList.add("tvw-message-action-active");let P={type:"downvote",messageId:e.id,message:e};r!=null&&r.onFeedback&&r.onFeedback(P),n.onFeedback&&n.onFeedback(P)}},"downvote");c.appendChild(f)}return c},Vn=(e,n,r,t,o,s)=>{var f,R,T,P,X;let i=r!=null?r:{},a=(f=i.layout)!=null?f:"bubble",d=i.avatar,g=i.timestamp,v=(R=d==null?void 0:d.show)!=null?R:!1,c=(T=g==null?void 0:g.show)!=null?T:!1,m=(P=d==null?void 0:d.position)!=null?P:"left",w=(X=g==null?void 0:g.position)!=null?X:"below",C=Ma(e.role,a),b=p("div",C.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id);let A=document.createElement("div");if(A.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),c&&w==="inline"&&e.createdAt){let O=Mi(e,g);O.classList.add("tvw-ml-2","tvw-inline"),A.appendChild(O)}if(b.appendChild(A),c&&w==="below"&&e.createdAt){let O=Mi(e,g);O.classList.add("tvw-mt-1"),b.appendChild(O)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let O=Li("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);O&&b.appendChild(O)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let O=ki(e,t,o);b.appendChild(O)}if(!v||e.role==="system")return b;let W=p("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),Y=Ta(d,e.role);return m==="right"||m==="left"&&e.role==="user"?W.append(b,Y):W.append(Y,b),b.classList.remove("tvw-max-w-[85%]"),b.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),W},La=(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}):Vn(e,n,r,t,o,s)};var An=new Set,Wi=(e,n)=>{let r=An.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=oe(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},$s=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=An.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=pi(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),v=oe(t?"chevron-up":"chevron-down",16,"currentColor",2);v?d.appendChild(v):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 w=n.chunks.join(""),C=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return C.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(C),(()=>{o.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let x=oe(t?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),r.append(o,m),r};var En=new Set,Ii=(e,n,r)=>{var g;let t=En.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 v=o.toggleTextColor||o.headerTextColor||"currentColor",c=oe(t?"chevron-up":"chevron-down",16,v,2);c?d.appendChild(c):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Os=(e,n)=>{var b;let r=e.toolCall,t=(b=n==null?void 0:n.toolCall)!=null?b:{},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=En.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=gi(r),a.appendChild(d);let g=p("div","tvw-flex tvw-items-center"),v=t.toggleTextColor||t.headerTextColor||"currentColor",c=oe(s?"chevron-up":"chevron-down",16,v,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 w=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",t.contentBackgroundColor&&(w.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(w.style.color=t.contentTextColor),t.contentPaddingX&&(w.style.paddingLeft=t.contentPaddingX,w.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(w.style.paddingTop=t.contentPaddingY,w.style.paddingBottom=t.contentPaddingY),r.name){let A=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?A.style.color=t.contentTextColor:t.headerTextColor&&(A.style.color=t.headerTextColor),A.textContent=r.name,w.appendChild(A)}if(r.args!==void 0){let A=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Arguments";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Ls(r.args),A.append(x,W),w.appendChild(A)}if(r.chunks&&r.chunks.length){let A=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Activity";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=r.chunks.join(`
16
- `),A.append(x,W),w.appendChild(A)}if(r.status==="complete"&&r.result!==void 0){let A=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.labelTextColor),x.textContent="Result";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=Ls(r.result),A.append(x,W),w.appendChild(A)}if(r.status==="complete"&&typeof r.duration=="number"){let A=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(A.style.color=t.contentTextColor),A.textContent=`Duration: ${r.duration}ms`,w.appendChild(A)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),g.innerHTML="";let A=t.toggleTextColor||t.headerTextColor||"currentColor",x=oe(s?"chevron-up":"chevron-down",16,A,2);x?g.appendChild(x):g.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var Pi=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(w=>w.role==="user"))return;let v=document.createDocumentFragment(),c=o?o.isStreaming():!1,m=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(w=>{let C=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");C.type="button",C.textContent=w,C.disabled=c,a!=null&&a.fontFamily&&(C.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(C.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(C.style.paddingLeft=a.paddingX,C.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(C.style.paddingTop=a.paddingY,C.style.paddingBottom=a.paddingY),C.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),v.appendChild(C),n.push(C)}),e.appendChild(v)}}};var Xn=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 Gn=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 Tn(e,n){n&&n.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var ka={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"}},Wa={bg:"#f3f4f6",text:"#4b5563"},Ia=["flowName","stepName","reasoningText","text","name","tool","toolName"],Pa=100;function Ha(e,n){let r={...ka,...n};if(r[e])return r[e];for(let t of Object.keys(r))if(t.endsWith("_")&&e.startsWith(t))return r[t];return Wa}function Ba(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Ra(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 Fa(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 $a(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 Oa(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 Na(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 Ns(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");Tn(g,(m=t.classNames)==null?void 0:m.eventRow);let v=i.find(w=>w.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let w=v.renderEventStreamRow({event:e,index:n,config:a,defaultRenderer:()=>c(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(w)return g.appendChild(w),g}return g.appendChild(c()),g;function c(){var U,ve;let w=p("div",""),C=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");C.setAttribute("data-event-id",e.id);let b=p("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),A=oe(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&b.appendChild(A);let x=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),W=(U=t.timestampFormat)!=null?U:"relative";x.textContent=W==="relative"?Ba(e.timestamp,r):Ra(e.timestamp);let Y=null;t.showSequenceNumbers!==!1&&(Y=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),Y.textContent=String(n+1));let f=Ha(e.type,t.badgeColors),R=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");R.style.backgroundColor=f.bg,R.style.color=f.text,R.style.borderColor=f.text+"50",R.textContent=e.type;let T=(ve=t.descriptionFields)!=null?ve:Ia,P=Fa(e.payload,T),X=null;P&&(X=p("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),X.textContent=P);let O=p("div","tvw-flex-1 tvw-min-w-0"),se=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"),G=oe("clipboard","12px","currentColor",1.5);return G&&se.appendChild(G),se.addEventListener("click",async N=>{N.stopPropagation(),await $a(Oa(e)),se.innerHTML="";let re=oe("check","12px","currentColor",1.5);re&&se.appendChild(re),setTimeout(()=>{se.innerHTML="";let D=oe("clipboard","12px","currentColor",1.5);D&&se.appendChild(D)},1500)}),C.appendChild(b),C.appendChild(x),Y&&C.appendChild(Y),C.appendChild(R),X&&C.appendChild(X),C.appendChild(O),C.appendChild(se),w.appendChild(C),d&&w.appendChild(Na(e,i,a)),w}}function Hi(e){var g,v;let{buffer:n,getFullHistory:r,onClose:t,config:o,plugins:s=[]}=e,i=(v=(g=o==null?void 0:o.features)==null?void 0:g.eventStream)!=null?v:{},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");Tn(m,c==null?void 0:c.panel);let w=[],C="",b="",A=null,x=[],W={},Y=0,f=!1,R=0,T=0,P=!1,X=null,O=!1,se=0,G=new Set,U=new Map,ve="",N="",re=null,D,Z,fe,ce,Ue;function Tt(){let z=p("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),F=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");Tn(F,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 $e=oe("clipboard-copy","12px","currentColor",1.5);$e&&fe.appendChild($e);let _=p("span","tvw-text-xs");_.textContent="Copy All",fe.appendChild(_),F.appendChild(ge),F.appendChild(D),F.appendChild(de),F.appendChild(Z),F.appendChild(fe);let ie=p("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");Tn(ie,c==null?void 0:c.searchBar);let ke=oe("search","14px","var(--cw-muted, #9ca3af)",1.5),Ke=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");ke&&Ke.appendChild(ke),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"),Tn(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=oe("x","12px","currentColor",2);return it&&Ue.appendChild(it),ie.appendChild(Ke),ie.appendChild(ce),ie.appendChild(Ue),z.appendChild(F),z.appendChild(ie),z}let Mt,$t=s.find(z=>z.renderEventStreamToolbar);if($t!=null&&$t.renderEventStreamToolbar&&o){let z=$t.renderEventStreamToolbar({config:o,defaultRenderer:()=>Tt(),eventCount:n.getSize(),filteredCount:0,onFilterChange:F=>{C=F,ut(),wt()},onSearchChange:F=>{b=F,ut(),wt()}});Mt=z!=null?z:Tt()}else Mt=Tt();let Ie=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");Ie.style.display="none";let ye=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");Tn(ue,c==null?void 0:c.scrollIndicator),ue.style.display="none";let Pe=oe("arrow-down","12px","currentColor",2);Pe&&ue.appendChild(Pe);let et=p("span","");ue.appendChild(et);let Et=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");Et.style.display="none",ye.appendChild(ee),ye.appendChild(Et),ye.appendChild(ue),m.setAttribute("tabindex","0"),m.appendChild(Mt),m.appendChild(Ie),m.appendChild(ye);function pe(){let z=n.getAll(),F={};for(let _ of z)F[_.type]=(F[_.type]||0)+1;let ge=Object.keys(F).sort(),de=ge.length!==x.length||!ge.every((_,ie)=>_===x[ie]),te=!de&&ge.some(_=>F[_]!==W[_]),xe=z.length!==Object.values(W).reduce((_,ie)=>_+ie,0);if(!de&&!te&&!xe||(x=ge,W=F,!Z))return;let $e=Z.value;if(Z.options[0].textContent="All events",de){for(;Z.options.length>1;)Z.remove(1);for(let _ of ge){let ie=p("option","");ie.value=_,ie.textContent=`${_} (${F[_]||0})`,Z.appendChild(ie)}$e&&ge.includes($e)?Z.value=$e:$e&&(Z.value="",C="")}else for(let _=1;_<Z.options.length;_++){let ie=Z.options[_];ie.textContent=`${ie.value} (${F[ie.value]||0})`}}function J(){let z=n.getAll();if(C&&(z=z.filter(F=>F.type===C)),b){let F=b.toLowerCase();z=z.filter(ge=>ge.type.toLowerCase().includes(F)||ge.payload.toLowerCase().includes(F))}return z}function ct(){return C!==""||b!==""}function ut(){Y=0,R=0,f=!1,ue.style.display="none"}function ft(z){G.has(z)?G.delete(z):G.add(z),re=z;let F=ee.scrollTop,ge=f;O=!0,f=!0,wt(),ee.scrollTop=F,f=ge,O=!1}function Ot(){return ee.scrollHeight-ee.scrollTop-ee.clientHeight<=50}function wt(){T=Date.now(),P=!1,pe();let z=n.getEvictedCount();z>0?(Ie.textContent=`${z.toLocaleString()} older events truncated`,Ie.style.display=""):Ie.style.display="none",w=J();let F=w.length,ge=n.getSize()>0;D&&(D.textContent=String(n.getSize())),F===0&&ge&&ct()?(Et.textContent=b?`No events matching '${b}'`:"No events matching filter",Et.style.display="",ee.style.display="none"):(Et.style.display="none",ee.style.display=""),fe&&(fe.title=ct()?`Copy Filtered (${F})`:"Copy All"),f&&F>Y&&(R+=F-Y,et.textContent=`${R} new event${R===1?"":"s"}`,ue.style.display=""),Y=F;let de=n.getAll(),te=de.length>0?de[0].timestamp:0,xe=new Set(w.map(ie=>ie.id));for(let ie of G)xe.has(ie)||G.delete(ie);let $e=C!==ve||b!==N,_=U.size===0&&w.length>0;if($e||_||w.length===0){ee.innerHTML="",U.clear();let ie=document.createDocumentFragment();for(let ke=0;ke<w.length;ke++){let Ke=Ns(w[ke],ke,te,i,G,ft,s,o);U.set(w[ke].id,Ke),ie.appendChild(Ke)}ee.appendChild(ie),ve=C,N=b,re=null}else{if(re!==null){let ke=U.get(re);if(ke&&ke.parentNode===ee){let Ke=w.findIndex(it=>it.id===re);if(Ke>=0){let it=Ns(w[Ke],Ke,te,i,G,ft,s,o);ee.insertBefore(it,ke),ke.remove(),U.set(re,it)}}re=null}let ie=new Set(w.map(ke=>ke.id));for(let[ke,Ke]of U)ie.has(ke)||(Ke.remove(),U.delete(ke));for(let ke=0;ke<w.length;ke++){let Ke=w[ke];if(!U.has(Ke.id)){let it=Ns(Ke,ke,te,i,G,ft,s,o);U.set(Ke.id,it),ee.appendChild(it)}}}f||(ee.scrollTop=ee.scrollHeight)}function V(){if(Date.now()-T>=Pa){X!==null&&(cancelAnimationFrame(X),X=null),wt();return}P||(P=!0,X=requestAnimationFrame(()=>{X=null,wt()}))}let Me=(z,F)=>{if(!fe)return;fe.innerHTML="";let ge=oe(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=oe("clipboard-copy","12px","currentColor",1.5);te&&fe.appendChild(te);let xe=p("span","tvw-text-xs");xe.textContent="Copy All",fe.appendChild(xe),fe.disabled=!1},F)},vt=async()=>{if(fe){fe.disabled=!0;try{let z;ct()?z=w:z=r?await r():n.getAll();let F=z.map(ge=>{try{return JSON.parse(ge.payload)}catch{return ge.payload}});await navigator.clipboard.writeText(JSON.stringify(F,null,2)),Me("check",1500)}catch{Me("x",1500)}}},yt=()=>{Z&&(C=Z.value,ut(),wt())},Q=()=>{!ce||!Ue||(Ue.style.display=ce.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{b=ce.value,ut(),wt()},150))},Fe=()=>{!ce||!Ue||(ce.value="",b="",Ue.style.display="none",A&&clearTimeout(A),ut(),wt())},bt=()=>{if(O)return;let z=ee.scrollTop,F=z>se;se=z,Ot()&&F?(f=!1,R=0,ue.style.display="none"):Ot()||(f=!0)},Wt=z=>{z.deltaY<0&&(f=!0)},Lt=()=>{ee.scrollTop=ee.scrollHeight,f=!1,R=0,ue.style.display="none"},j=z=>{let F=z.target;if(!F||F.closest("button"))return;let ge=F.closest("[data-event-id]");if(!ge)return;let de=ge.getAttribute("data-event-id");de&&ft(de)},Qe=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?(Fe(),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",Fe),ee.addEventListener("scroll",bt),ee.addEventListener("wheel",Wt,{passive:!0}),ee.addEventListener("click",j),ue.addEventListener("click",Lt),m.addEventListener("keydown",Qe);function Ae(){A&&clearTimeout(A),X!==null&&(cancelAnimationFrame(X),X=null),P=!1,U.clear(),fe&&fe.removeEventListener("click",vt),Z&&Z.removeEventListener("change",yt),ce&&ce.removeEventListener("input",Q),Ue&&Ue.removeEventListener("click",Fe),ee.removeEventListener("scroll",bt),ee.removeEventListener("wheel",Wt),ee.removeEventListener("click",j),ue.removeEventListener("click",Lt),m.removeEventListener("keydown",Qe)}return{element:m,update:V,destroy:Ae}}}var Bi={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"}},Ds=(e,n,r,t)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,b,A;if(s.dataset.enhanced==="true")return;let i=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let a=(b=Bi[i])!=null?b:Bi.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 x=p("p","tvw-text-sm tvw-text-cw-muted");x.textContent=a.description,d.appendChild(x)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(x=>{var T,P;let W=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");W.htmlFor=`${n.id}-${i}-${x.name}`;let Y=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");Y.textContent=x.label,W.appendChild(Y);let f=(T=x.type)!=null?T:"text",R;f==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=f),R.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",R.id=`${n.id}-${i}-${x.name}`,R.name=x.name,R.placeholder=(P=x.placeholder)!=null?P:"",x.required&&(R.required=!0),W.appendChild(R),v.appendChild(W)});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]"),w=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(A=a.submitLabel)!=null?A:"Submit",c.appendChild(m),c.appendChild(w),v.appendChild(c),s.replaceChildren(d,v),v.addEventListener("submit",async x=>{var R,T;x.preventDefault();let W=(R=r.formEndpoint)!=null?R:"/form",Y=new FormData(v),f={};Y.forEach((P,X)=>{f[X]=P}),f.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let P=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let X=await P.json();m.textContent=(T=X.message)!=null?T:"Thanks! We'll be in touch soon.",X.success&&X.nextPrompt&&await t.sendMessage(String(X.nextPrompt))}catch(P){m.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var js=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()}},ws=new js;var Ri={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"},Fi={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"},nt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ri,darkTheme:Fi,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 _s(e){var n,r,t,o,s,i,a,d,g,v,c,m,w,C,b,A,x,W,Y;return e?{...nt,...e,theme:{...nt.theme,...e.theme},darkTheme:{...nt.darkTheme,...e.darkTheme},launcher:{...nt.launcher,...e.launcher,clearChat:{...(n=nt.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...nt.copy,...e.copy},sendButton:{...nt.sendButton,...e.sendButton},statusIndicator:{...nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...nt.voiceRecognition,...e.voiceRecognition},features:{...nt.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:nt.suggestionChips,suggestionChipsConfig:{...nt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...nt.layout,...e.layout,header:{...(o=nt.layout)==null?void 0:o.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=nt.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(g=(d=nt.layout)==null?void 0:d.messages)==null?void 0:g.avatar,...(c=(v=e.layout)==null?void 0:v.messages)==null?void 0:c.avatar},timestamp:{...(w=(m=nt.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(b=(C=e.layout)==null?void 0:C.messages)==null?void 0:b.timestamp}},slots:{...(A=nt.layout)==null?void 0:A.slots,...(x=e.layout)==null?void 0:x.slots}},markdown:{...nt.markdown,...e.markdown,options:{...(W=nt.markdown)==null?void 0:W.options,...(Y=e.markdown)==null?void 0:Y.options}},messageActions:{...nt.messageActions,...e.messageActions}}:nt}var $i=()=>{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 Da=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},ja=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},vs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Da(e),r=ja(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}},qs=e=>typeof e=="string"?e:e==null?"":String(e),Mn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:qs(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=qs(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:qs(r.text)}}},Oi=e=>Array.isArray(e)?e.map(n=>String(n)):[],ys=e=>{let n=new Set(Oi(e.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(Oi(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,v)=>g||(v==null?void 0:v({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 v=()=>{e.emit("action:resubmit",d)},c=g(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:v});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(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var _a=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}},qa=e=>e.map(n=>({...n,streaming:!1})),zs=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?_a(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?qa(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 Us=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)})}},Qn=new Us;import{parse as za,STR as Ua,OBJ as Ja}from"partial-json";function Ka(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Ya(e,n){if(!Ka(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=za(r,Ua|Ja),s=Ya(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function Va(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ks(e,n){let{config:r,message:t,onPropsUpdate:o}=n,s=Qn.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 Xa(){let e=Js();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ys(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 Vs(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 Ga=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xs(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=Ga}=e,v=document.createElement("div");v.className="tvw-feedback-container tvw-feedback-csat",v.setAttribute("role","dialog"),v.setAttribute("aria-label","Customer satisfaction feedback");let c=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=t,w.appendChild(C);let b=document.createElement("p");b.className="tvw-feedback-subtitle",b.textContent=o,w.appendChild(b),m.appendChild(w);let A=document.createElement("div");A.className="tvw-feedback-rating tvw-feedback-rating-csat",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let T=1;T<=5;T++){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",`${T} star${T>1?"s":""}: ${g[T-1]}`),P.title=g[T-1],P.dataset.rating=String(T),P.innerHTML=`
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 on=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}},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 xi=e=>on({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),Si=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}},Ai=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}},Fs={default:xi,minimal:Si,expanded:Ai},Ei=e=>{var n;return(n=Fs[e])!=null?n:Fs.default},Kn=(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=Ei(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 Ta=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'}},Yn=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=Ta(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:rn).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 Ti=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}},Mi=(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?Kn(e,t,{showClose:n}):on({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=Yn({config:e}),m=((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),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 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},Li=(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()},Ma=(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},ka=(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},Wi=(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},Vn=(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=ka(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 _=Li("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 _=Wi(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=Ma(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},La=(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}):Vn(e,n,r,t,o,s)};var An=new Set,Ii=(e,n)=>{let r=An.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"},$s=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=An.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=gi(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 En=new Set,Pi=(e,n,r)=>{var g;let t=En.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"},Os=(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=En.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 Hi=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 Xn=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 Gn=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 Tn(e,n){n&&n.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var Wa={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"}},Ia={bg:"#f3f4f6",text:"#4b5563"},Pa=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ha=100;function Ba(e,n){let r={...Wa,...n};if(r[e])return r[e];for(let t of Object.keys(r))if(t.endsWith("_")&&e.startsWith(t))return r[t];return Ia}function Ra(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Fa(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 $a(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 Oa(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 Na(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 Da(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 Ns(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");Tn(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"?Ra(e.timestamp,r):Fa(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=Ba(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:Pa,P=$a(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 Oa(Na(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(Da(e,i,a)),f}}function Bi(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");Tn(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");Tn(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");Tn(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"),Tn(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");Tn(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=Ns(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=Ns(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=Ns(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>=Ha){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 Ri={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Ds=(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=Ri[i])!=null?C:Ri.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 js=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()}},ws=new js;var Fi={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"},$i={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"},ot={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Fi,darkTheme:$i,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 _s(e){var n,r,t,o,s,i,a,d,g,w,c,m,f,x,C,T,A,L,V;return e?{...ot,...e,theme:{...ot.theme,...e.theme},darkTheme:{...ot.darkTheme,...e.darkTheme},launcher:{...ot.launcher,...e.launcher,clearChat:{...(n=ot.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...ot.copy,...e.copy},sendButton:{...ot.sendButton,...e.sendButton},statusIndicator:{...ot.statusIndicator,...e.statusIndicator},voiceRecognition:{...ot.voiceRecognition,...e.voiceRecognition},features:{...ot.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:ot.suggestionChips,suggestionChipsConfig:{...ot.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ot.layout,...e.layout,header:{...(o=ot.layout)==null?void 0:o.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=ot.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(g=(d=ot.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=ot.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=ot.layout)==null?void 0:T.slots,...(A=e.layout)==null?void 0:A.slots}},markdown:{...ot.markdown,...e.markdown,options:{...(L=ot.markdown)==null?void 0:L.options,...(V=e.markdown)==null?void 0:V.options}},messageActions:{...ot.messageActions,...e.messageActions}}:ot}var Oi=()=>{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 ja=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},_a=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},vs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=ja(e),r=_a(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}},qs=e=>typeof e=="string"?e:e==null?"":String(e),Mn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:qs(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=qs(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:qs(r.text)}}},Ni=e=>Array.isArray(e)?e.map(n=>String(n)):[],ys=e=>{let n=new Set(Ni(e.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(Ni(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 qa=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}},za=e=>e.map(n=>({...n,streaming:!1})),zs=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?qa(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?za(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 Us=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)})}},Qn=new Us;import{parse as Ua,STR as Ja,OBJ as Ka}from"partial-json";function Ya(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Va(e,n){if(!Ya(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=Ua(r,Ja|Ka),s=Va(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function Xa(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ks(e,n){let{config:r,message:t,onPropsUpdate:o}=n,s=Qn.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 Ga(){let e=Js();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ys(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 Vs(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 Qa=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xs(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=Qa}=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=`
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=T,x.forEach((X,O)=>{let se=O<T;X.classList.toggle("selected",se),X.setAttribute("aria-checked",O===T-1?"true":"false")})}),x.push(P),A.appendChild(P)}m.appendChild(A);let W=null;if(d){let T=document.createElement("div");T.className="tvw-feedback-comment-container",W=document.createElement("textarea"),W.className="tvw-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),T.appendChild(W),m.appendChild(T)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let f=document.createElement("button");f.type="button",f.className="tvw-feedback-btn tvw-feedback-btn-skip",f.textContent=a,f.addEventListener("click",()=>{r==null||r(),v.remove()});let R=document.createElement("button");return R.type="button",R.className="tvw-feedback-btn tvw-feedback-btn-submit",R.textContent=i,R.addEventListener("click",async()=>{if(c===null){A.classList.add("tvw-feedback-shake"),setTimeout(()=>A.classList.remove("tvw-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let T=(W==null?void 0:W.value.trim())||void 0;await n(c,T),v.remove()}catch(T){R.disabled=!1,R.textContent=i,console.error("[CSAT Feedback] Failed to submit:",T)}}),Y.appendChild(f),Y.appendChild(R),m.appendChild(Y),v.appendChild(m),v}function Gs(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:v="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,w=document.createElement("div");w.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let b=document.createElement("h3");b.className="tvw-feedback-title",b.textContent=t,C.appendChild(b);let A=document.createElement("p");A.className="tvw-feedback-subtitle",A.textContent=o,C.appendChild(A),w.appendChild(C);let x=document.createElement("div");x.className="tvw-feedback-rating tvw-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="tvw-feedback-labels";let Y=document.createElement("span");Y.className="tvw-feedback-label-low",Y.textContent=g;let f=document.createElement("span");f.className="tvw-feedback-label-high",f.textContent=v,W.appendChild(Y),W.appendChild(f);let R=document.createElement("div");R.className="tvw-feedback-numbers";let T=[];for(let G=0;G<=10;G++){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 ${G} out of 10`),U.textContent=String(G),U.dataset.rating=String(G),G<=6?U.classList.add("tvw-feedback-detractor"):G<=8?U.classList.add("tvw-feedback-passive"):U.classList.add("tvw-feedback-promoter"),U.addEventListener("click",()=>{m=G,T.forEach((ve,N)=>{ve.classList.toggle("selected",N===G),ve.setAttribute("aria-checked",N===G?"true":"false")})}),T.push(U),R.appendChild(U)}x.appendChild(W),x.appendChild(R),w.appendChild(x);let P=null;if(d){let G=document.createElement("div");G.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"),G.appendChild(P),w.appendChild(G)}let X=document.createElement("div");X.className="tvw-feedback-actions";let O=document.createElement("button");O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-skip",O.textContent=a,O.addEventListener("click",()=>{r==null||r(),c.remove()});let se=document.createElement("button");return se.type="button",se.className="tvw-feedback-btn tvw-feedback-btn-submit",se.textContent=i,se.addEventListener("click",async()=>{if(m===null){R.classList.add("tvw-feedback-shake"),setTimeout(()=>R.classList.remove("tvw-feedback-shake"),500);return}se.disabled=!0,se.textContent="Submitting...";try{let G=(P==null?void 0:P.value.trim())||void 0;await n(m,G),c.remove()}catch(G){se.disabled=!1,se.textContent=i,console.error("[NPS Feedback] Failed to submit:",G)}}),X.appendChild(O),X.appendChild(se),w.appendChild(X),c.appendChild(w),c}var Ln="persona-chat-history",Qa=30*1e3;function Za(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 el(e){try{let n=e==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var Qs=e=>!e||typeof e!="object"?{}:{...e},Ni=e=>e.map(n=>({...n,streaming:!1})),Di=(e,n,r)=>{let t=e!=null&&e.markdown?us(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 v=n.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});v!==null&&(s=v.text,v.persist||(o.message.__skipPersist=!0),v.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)}},Zs=(e,n,r)=>{var gt,Ne,qe,lt,ze,St,Rt,qt,nr,sr,rr,or,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,vr,yr,br,Cr,xr,Sr,Ar,Er;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let t=_s(n),o=ws.getForInstance(t.plugins);t.components&&Qn.registerAll(t.components);let s=$i(),i=(gt=t.storageAdapter)!=null?gt:zs(),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 S=u!=null?u:{messages:[],metadata:{}};return g(S)});else{let u=l!=null?l:{messages:[],metadata:{}},S=g(u);S.metadata&&(a=Qs(S.metadata)),(Ne=S.messages)!=null&&Ne.length&&(t={...t,initialMessages:S.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:{}});(qe=l.messages)!=null&&qe.length&&(t={...t,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,c=l=>{var S;a=(S=l({...a}))!=null?S:{},Rn()},m=t.actionParsers&&t.actionParsers.length?t.actionParsers:[vs],w=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Mn.message,Mn.messageAndClick],C=ys({parsers:m,handlers:w,getSessionMetadata:v,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let b=(ze=(lt=t.launcher)==null?void 0:lt.enabled)!=null?ze:!0,A=(Rt=(St=t.launcher)==null?void 0:St.autoExpand)!=null?Rt:!1,x=A,W=b,Y=(nr=(qt=t.layout)==null?void 0:qt.header)==null?void 0:nr.layout,f=b?A:!0,R=!1,T=null,P=()=>{R=!0,T&&clearTimeout(T),T=setTimeout(()=>{R&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),R=!1)},1e4)},X=Di(t,C,P),O=(rr=(sr=t.features)==null?void 0:sr.showReasoning)!=null?rr:!0,se=(ir=(or=t.features)==null?void 0:or.showToolCalls)!=null?ir:!0,G=(lr=(ar=t.features)==null?void 0:ar.showEventStreamToggle)!=null?lr:!1,ve=`${(cr=typeof t.persistState=="object"?(dr=t.persistState)==null?void 0:dr.keyPrefix:void 0)!=null?cr:"persona-"}event-stream`,N=G?new Gn(ve):null,re=(gr=(pr=(ur=t.features)==null?void 0:ur.eventStream)==null?void 0:pr.maxEvents)!=null?gr:2e3,D=G?new Xn(re,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 Tt={onCopy:l=>{var u,S;s.emit("message:copy",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(I=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",I)}),(S=(u=t.messageActions)==null?void 0:u.onCopy)==null||S.call(u,l)},onFeedback:l=>{var u,S;s.emit("message:feedback",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(I=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",I)}),(S=(u=t.messageActions)==null?void 0:u.onFeedback)==null||S.call(u,l)}},Mt=(mr=t.statusIndicator)!=null?mr:{},$t=l=>{var u,S,I,E;return l==="idle"?(u=Mt.idleText)!=null?u:Pt.idle:l==="connecting"?(S=Mt.connectingText)!=null?S:Pt.connecting:l==="connected"?(I=Mt.connectedText)!=null?I:Pt.connected:l==="error"?(E=Mt.errorText)!=null?E:Pt.error:Pt[l]},{wrapper:Ie,panel:ye}=Ei(t),ee=Ti(t,b),{container:ue,body:Pe,messagesWrapper:et,suggestions:Et,textarea:pe,sendButton:J,sendButtonWrapper:ct,composerForm:ut,statusText:ft,introTitle:Ot,introSubtitle:wt,closeButton:V,iconHolder:Me,headerTitle:vt,headerSubtitle:yt,header:Q,footer:Fe,actionsRow:bt,leftActions:Wt,rightActions:Lt}=ee,j=ee.micButton,Qe=ee.micButtonWrapper,Ae=ee.attachmentButton,z=ee.attachmentButtonWrapper,F=ee.attachmentInput,ge=ee.attachmentPreviewsContainer,de=null;(hr=t.attachments)!=null&&hr.enabled&&F&&ge&&(de=Cn.fromConfig(t.attachments),de.setPreviewsContainer(ge),F.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=an({config:t,showClose:b});return xn(ue,u,t),u.header},onClose:()=>tt(!1,"user")});if(l){let u=ue.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),Q=l)}}let xe=()=>{var u,S,I,E;if(!D)return;if(fe=!0,!Z&&D&&(Z=Hi({buffer:D,getFullHistory:()=>D.getAllFromStore(),onClose:()=>$e(),config:t,plugins:o})),Z&&(Pe.style.display="none",(u=Fe.parentNode)==null||u.insertBefore(Z.element,Fe),Z.update()),_){_.classList.remove("tvw-text-cw-muted"),_.classList.add("tvw-text-cw-accent"),_.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let q=(E=(I=(S=t.features)==null?void 0:S.eventStream)==null?void 0:I.classNames)==null?void 0:E.toggleButtonActive;q&&q.split(/\s+/).forEach(be=>be&&_.classList.add(be))}let l=()=>{if(!fe)return;let q=Date.now();q-Ue>=200&&(Z==null||Z.update(),Ue=q),ce=requestAnimationFrame(l)};Ue=0,ce=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},$e=()=>{var l,u,S;if(fe){if(fe=!1,Z&&Z.element.remove(),Pe.style.display="",_){_.classList.remove("tvw-text-cw-accent"),_.classList.add("tvw-text-cw-muted"),_.style.boxShadow="";let I=(S=(u=(l=t.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:S.toggleButtonActive;I&&I.split(/\s+/).forEach(E=>E&&_.classList.remove(E))}ce!==null&&(cancelAnimationFrame(ce),ce=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},_=null;if(G){let l=(wr=(fr=t.features)==null?void 0:fr.eventStream)==null?void 0:wr.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:"");_=p("button",u),_.style.width="28px",_.style.height="28px",_.type="button",_.setAttribute("aria-label","Event Stream"),_.title="Event Stream";let S=oe("activity","18px","currentColor",1.5);S&&_.appendChild(S);let I=ee.clearChatButtonWrapper,E=ee.closeButtonWrapper,q=I||E;q&&q.parentNode===Q?Q.insertBefore(_,q):Q.appendChild(_),_.addEventListener("click",()=>{fe?$e():xe()})}let ie=o.find(l=>l.renderComposer);if(ie!=null&&ie.renderComposer){let l=ie.renderComposer({config:t,defaultRenderer:()=>Yn({config:t}).footer,onSubmit:u=>{$&&!$.isStreaming()&&$.sendMessage(u)},disabled:!1});l&&(Fe.replaceWith(l),Fe=l)}(()=>{var I,E;let l=(E=(I=t.layout)==null?void 0:I.slots)!=null?E:{},u=q=>{switch(q){case"body-top":return ue.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return et;case"footer-top":return Et;case"composer":return ut;case"footer-bottom":return ft;default:return null}},S=(q,be)=>{var le;switch(q){case"header-left":case"header-center":case"header-right":if(q==="header-left")Q.insertBefore(be,Q.firstChild);else if(q==="header-right")Q.appendChild(be);else{let Te=Q.querySelector(".tvw-flex-col");Te?(le=Te.parentNode)==null||le.insertBefore(be,Te.nextSibling):Q.appendChild(be)}break;case"body-top":{let Te=Pe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");Te?Te.replaceWith(be):Pe.insertBefore(be,Pe.firstChild);break}case"body-bottom":Pe.appendChild(be);break;case"footer-top":Et.replaceWith(be);break;case"footer-bottom":ft.replaceWith(be);break;default:break}};for(let[q,be]of Object.entries(l))if(be)try{let le=be({config:t,defaultContent:()=>u(q)});le&&S(q,le)}catch(le){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${q}":`,le)}})();let Ke=l=>{let S=l.target.closest('button[data-expand-header="true"]');if(!S)return;let I=S.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!I)return;let E=I.getAttribute("data-message-id");if(!E)return;let q=S.getAttribute("data-bubble-type");q==="reasoning"?(An.has(E)?An.delete(E):An.add(E),Wi(E,I)):q==="tool"&&(En.has(E)?En.delete(E):En.add(E),Ii(E,I,t))};et.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ke(l))}),et.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ke(l))}),ye.appendChild(ue),e.appendChild(Ie);let it=()=>{var he,we,Xe,Le,mt,It,K,je,Kt,zt,rn,as,Ts,dt,ls,Nn;let l=(we=(he=t.launcher)==null?void 0:he.sidebarMode)!=null?we:!1,u=l||((Le=(Xe=t.launcher)==null?void 0:Xe.fullHeight)!=null?Le:!1),S=(mt=t.theme)!=null?mt:{},I=(K=(It=t.launcher)==null?void 0:It.position)!=null?K:"bottom-left",E=I==="bottom-left"||I==="top-left",q=l?"none":"1px solid var(--tvw-cw-border)",be=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",Te=(je=S.panelBorder)!=null?je:q,Be=(Kt=S.panelShadow)!=null?Kt:be,Re=(zt=S.panelBorderRadius)!=null?zt:le;e.style.cssText="",Ie.style.cssText="",ye.style.cssText="",ue.style.cssText="",Pe.style.cssText="",Fe.style.cssText="";let De=(as=(rn=t==null?void 0:t.launcher)==null?void 0:rn.width)!=null?as:t==null?void 0:t.launcherWidth,ne=De!=null?De:"min(400px, calc(100vw - 24px))";l||(ye.style.width=ne,ye.style.maxWidth=ne),ye.style.boxShadow=Be,ye.style.borderRadius=Re,ue.style.border=Te,ue.style.borderRadius=Re;let H=((Ts=t.launcher)==null?void 0:Ts.enabled)===!1;if(u&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",Ie.style.display="flex",Ie.style.flexDirection="column",Ie.style.flex="1 1 0%",Ie.style.minHeight="0",Ie.style.maxHeight="100%",Ie.style.height="100%",H&&(Ie.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",ye.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",Pe.style.flex="1 1 0%",Pe.style.minHeight="0",Pe.style.overflowY="auto",Fe.style.flexShrink="0"),Ie.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&&!H&&((dt=Ut[I])!=null?dt:Ut["bottom-right"]).split(" ").forEach(gn=>Ie.classList.add(gn)),l){let pn=(Nn=(ls=t.launcher)==null?void 0:ls.sidebarWidth)!=null?Nn:"420px";Ie.style.cssText=`
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 Gs(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 kn="persona-chat-history",Za=30*1e3;function el(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 tl(e){try{let n=e==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var Qs=e=>!e||typeof e!="object"?{}:{...e},Di=e=>e.map(n=>({...n,streaming:!1})),ji=(e,n,r)=>{let t=e!=null&&e.markdown?us(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)}},Zs=(e,n,r)=>{var Ne,qe,ct,ze,Ct,Bt,_t,nr,sr,rr,or,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,vr,yr,br,Cr,xr,Sr,Ar,Er,Tr;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let t=_s(n),o=ws.getForInstance(t.plugins);t.components&&Qn.registerAll(t.components);let s=Oi(),i=(Ne=t.storageAdapter)!=null?Ne:zs(),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=Qs(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:{},Rn()},m=t.actionParsers&&t.actionParsers.length?t.actionParsers:[vs],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Mn.message,Mn.messageAndClick],x=ys({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=(sr=(nr=t.layout)==null?void 0:nr.header)==null?void 0:sr.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=ji(t,x,P),_=(or=(rr=t.features)==null?void 0:rr.showReasoning)!=null?or:!0,oe=(ar=(ir=t.features)==null?void 0:ir.showToolCalls)!=null?ar:!0,X=(dr=(lr=t.features)==null?void 0:lr.showEventStreamToggle)!=null?dr:!1,xe=`${(ur=typeof t.persistState=="object"?(cr=t.persistState)==null?void 0:cr.keyPrefix:void 0)!=null?ur:"persona-"}event-stream`,N=X?new Gn(xe):null,ne=(mr=(gr=(pr=t.features)==null?void 0:pr.eventStream)==null?void 0:gr.maxEvents)!=null?mr:2e3,D=X?new Xn(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=(hr=t.statusIndicator)!=null?hr:{},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}=Ti(t),ee=Mi(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;(fr=t.attachments)!=null&&fr.enabled&&R&&ge&&(de=Cn.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=on({config:t,showClose:C});return xn(ue,u,t),u.header},onClose:()=>rt(!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=Bi({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=(vr=(wr=t.features)==null?void 0:wr.eventStream)==null?void 0:vr.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:()=>Yn({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"?(An.has(E)?An.delete(E):An.add(E),Ii(E,k)):$==="tool"&&(En.has(E)?En.delete(E):En.add(E),Pi(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 mn=()=>{var he,Ce,Xe,Pe,mt,Wt,K,_e,Kt,qt,sn,as,Ts,ut,ls,Nn;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=(as=(sn=t==null?void 0:t.launcher)==null?void 0:sn.width)!=null?as: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=((Ts=t.launcher)==null?void 0:Ts.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(pn=>Re.classList.add(pn)),l){let un=(Nn=(ls=t.launcher)==null?void 0:ls.sidebarWidth)!=null?Nn:"420px";Re.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
24
- width: ${pn} !important;
24
+ width: ${un} !important;
25
25
  height: 100vh !important;
26
26
  max-height: 100vh !important;
27
27
  margin: 0 !important;
@@ -29,7 +29,7 @@ import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=
29
29
  display: flex !important;
30
30
  flex-direction: column !important;
31
31
  ${E?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
- `,ye.style.cssText=`
32
+ `,Se.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
35
35
  flex-direction: column !important;
@@ -40,9 +40,9 @@ import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=
40
40
  min-height: 0 !important;
41
41
  margin: 0 !important;
42
42
  padding: 0 !important;
43
- box-shadow: ${Be} !important;
44
- border-radius: ${Re} !important;
45
- `,ye.style.setProperty("width","100%","important"),ye.style.setProperty("max-width","100%","important"),ue.style.cssText=`
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=`
46
46
  display: flex !important;
47
47
  flex-direction: column !important;
48
48
  flex: 1 1 0% !important;
@@ -51,13 +51,13 @@ import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=
51
51
  min-height: 0 !important;
52
52
  max-height: 100% !important;
53
53
  overflow: hidden !important;
54
- border-radius: ${Re} !important;
55
- border: ${Te} !important;
56
- `,Fe.style.cssText=`
54
+ border-radius: ${be} !important;
55
+ border: ${ye} !important;
56
+ `,$e.style.cssText=`
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!H){let pn="max-height: -moz-available !important; max-height: stretch !important;",gn=l?"":"padding-top: 1.25em !important;";Ie.style.cssText+=pn+gn}};it(),fs(e,t);let pt=[];G&&pt.push(()=>{ce!==null&&(cancelAnimationFrame(ce),ce=null),Z==null||Z.destroy(),Z=null,D==null||D.destroy(),D=null,N=null});let Nt=null,Wn=()=>{Nt&&(Nt(),Nt=null),t.colorScheme==="auto"&&(Nt=yi(()=>{fs(e,t)}))};Wn(),pt.push(()=>{Nt&&(Nt(),Nt=null)});let nn=Pi(Et),Jt=null,$,sn=!1,Vt=!0,ln=0,In=0,Xt=null,Gt=!1,hn=0,fn=!1,Zn=125,es=2e3,ts=5,Pn=50,wn=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Hn=(yr=(vr=t.voiceRecognition)==null?void 0:vr.autoResume)!=null?yr:!1,Bn=l=>{s.emit("voice:state",{active:Ye.active,source:l,timestamp:Date.now()})},Qt=()=>{c(l=>({...l,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},ns=()=>{var I,E;if(((I=t.voiceRecognition)==null?void 0:I.enabled)===!1)return;let l=Qs(a.voiceState),u=!!l.active,S=Number((E=l.timestamp)!=null?E:0);Ye.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-S<Qa&&setTimeout(()=>{Ye.active||(Ye.manuallyDeactivated=!1,He("restore"))},1e3)},ss=()=>$?Ni($.getMessages()).filter(l=>!l.__skipPersist):[];function Rn(l){if(!(i!=null&&i.save))return;let S={messages:l?Ni(l):$?ss():[],metadata:a};try{let I=i.save(S);I instanceof Promise&&I.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)})}catch(I){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)}}let dn=(l=!1)=>{if(!Vt)return;let u=Date.now();Gt&&u<hn&&!l||(Gt&&u>=hn&&(Gt=!1),!(!l&&!sn)&&(u-In<Zn||(In=u,Xt&&cancelAnimationFrame(Xt),Xt=requestAnimationFrame(()=>{Gt||!Vt||(fn=!0,Pe.scrollTop=Pe.scrollHeight,ln=Pe.scrollTop,requestAnimationFrame(()=>{fn=!1}),Xt=null)}))))},Zt=null,rs=()=>Ie.querySelector("#persona-scroll-container")||Pe,os=(l,u=500)=>{let S=l.scrollTop,I=l.clientHeight,E=l.scrollHeight,q=E-S;if(S+I>=E-2||Math.abs(q)<5)return;Zt!==null&&(cancelAnimationFrame(Zt),Zt=null);let le=performance.now(),Te=Re=>1-Math.pow(1-Re,3),Be=Re=>{let De=l.scrollHeight;De!==E&&(E=De,q=E-S);let ne=Re-le,H=Math.min(ne/u,1),he=Te(H),we=S+q*he;l.scrollTop=we,H<1?Zt=requestAnimationFrame(Be):(l.scrollTop=l.scrollHeight,Zt=null)};Zt=requestAnimationFrame(Be)},is=l=>{let u=new Map;l.forEach(S=>{let I=wn.get(S.id);u.set(S.id,{streaming:S.streaming,role:S.role}),!I&&S.role==="assistant"&&s.emit("assistant:message",S),S.role==="assistant"&&(I!=null&&I.streaming)&&S.streaming===!1&&s.emit("assistant:complete",S)}),wn.clear(),u.forEach((S,I)=>{wn.set(I,S)})},cn=(l,u,S)=>{var Be,Re,De,ne;let I=document.createElement("div"),q=(()=>{var he;let H=o.find(we=>we.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((he=t.loadingIndicator)!=null&&he.render)return t.loadingIndicator.render})();u.forEach(H=>{var mt,It;let he=null,we=o.find(K=>!!(H.variant==="reasoning"&&K.renderReasoning||H.variant==="tool"&&K.renderToolCall||!H.variant&&K.renderMessage)),Xe=(mt=t.layout)==null?void 0:mt.messages;if(we)if(H.variant==="reasoning"&&H.reasoning&&we.renderReasoning){if(!O)return;he=we.renderReasoning({message:H,defaultRenderer:()=>$s(H),config:t})}else if(H.variant==="tool"&&H.toolCall&&we.renderToolCall){if(!se)return;he=we.renderToolCall({message:H,defaultRenderer:()=>Os(H,t),config:t})}else we.renderMessage&&(he=we.renderMessage({message:H,defaultRenderer:()=>{let K=Vn(H,S,Xe,t.messageActions,Tt,{loadingIndicatorRenderer:q,widgetConfig:t});return H.role!=="user"&&Ds(K,H,t,$),K},config:t}));if(!he&&H.role==="assistant"&&!H.variant&&t.enableComponentStreaming!==!1&&Ys(H)){let je=Vs(H);if(je){let Kt=Ks(je,{config:t,message:H,transform:S});if(Kt){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-${H.id}`,zt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let rn=document.createElement("div");rn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",rn.innerHTML=S({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),zt.appendChild(rn)}zt.appendChild(Kt),he=zt}}}if(!he)if(H.variant==="reasoning"&&H.reasoning){if(!O)return;he=$s(H)}else if(H.variant==="tool"&&H.toolCall){if(!se)return;he=Os(H,t)}else{let K=(It=t.layout)==null?void 0:It.messages;K!=null&&K.renderUserMessage&&H.role==="user"?he=K.renderUserMessage({message:H,config:t,streaming:!!H.streaming}):K!=null&&K.renderAssistantMessage&&H.role==="assistant"?he=K.renderAssistantMessage({message:H,config:t,streaming:!!H.streaming}):he=Vn(H,S,K,t.messageActions,Tt,{loadingIndicatorRenderer:q,widgetConfig:t}),H.role!=="user"&&he&&Ds(he,H,t,$)}let Le=document.createElement("div");Le.className="tvw-flex",Le.id=`wrapper-${H.id}`,Le.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Le.classList.add("tvw-justify-end"),Le.appendChild(he),I.appendChild(Le)});let be=u.some(H=>H.role==="assistant"&&H.streaming),le=u[u.length-1],Te=(le==null?void 0:le.role)==="assistant"&&!le.streaming;if(sn&&u.some(H=>H.role==="user")&&!be&&!Te){let H={config:t,streaming:!0,location:"standalone",defaultRenderer:Sn},he=o.find(Xe=>Xe.renderLoadingIndicator),we=null;if(he!=null&&he.renderLoadingIndicator&&(we=he.renderLoadingIndicator(H)),we===null&&((Be=t.loadingIndicator)!=null&&Be.render)&&(we=t.loadingIndicator.render(H)),we===null&&(we=Sn()),we){let Xe=document.createElement("div"),Le=((Re=t.loadingIndicator)==null?void 0:Re.showBubble)!==!1;Xe.className=Le?["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(we);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Xe),I.appendChild(mt)}}if(!sn&&u.length>0){let H=u[u.length-1],he={config:t,lastMessage:H,messageCount:u.length},we=o.find(Le=>Le.renderIdleIndicator),Xe=null;if(we!=null&&we.renderIdleIndicator&&(Xe=we.renderIdleIndicator(he)),Xe===null&&((De=t.loadingIndicator)!=null&&De.renderIdle)&&(Xe=t.loadingIndicator.renderIdle(he)),Xe){let Le=document.createElement("div"),mt=((ne=t.loadingIndicator)==null?void 0:ne.showBubble)!==!1;Le.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(" "),Le.setAttribute("data-idle-indicator","true"),Le.appendChild(Xe);let It=document.createElement("div");It.className="tvw-flex",It.id="wrapper-idle-indicator",It.setAttribute("data-wrapper-id","idle-indicator"),It.appendChild(Le),I.appendChild(It)}}bi(l,I),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let H=rs();os(H)})})},un=()=>{b&&(f?(Ie.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ye.classList.remove("tvw-scale-95","tvw-opacity-0"),ye.classList.add("tvw-scale-100","tvw-opacity-100"),k?k.element.style.display="none":h&&(h.style.display="none")):(Ie.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ye.classList.remove("tvw-scale-100","tvw-opacity-100"),ye.classList.add("tvw-scale-95","tvw-opacity-0"),k?k.element.style.display="":h&&(h.style.display="")))},tt=(l,u="user")=>{if(!b||f===l)return;let S=f;f=l,un(),f&&(M(),dn(!0));let I={open:f,source:u,timestamp:Date.now()};f&&!S?s.emit("widget:opened",I):!f&&S&&s.emit("widget:closed",I),s.emit("widget:state",{open:f,launcherEnabled:b,voiceActive:Ye.active,streaming:$.isStreaming()})},vn=l=>{J.disabled=l,j&&(j.disabled=l),nn.buttons.forEach(u=>{u.disabled=l})},Fn=()=>{var E,q,be,le,Te,Be,Re,De,ne,H,he,we,Xe,Le;Ot.textContent=(q=(E=t.copy)==null?void 0:E.welcomeTitle)!=null?q:"Hello \u{1F44B}",wt.textContent=(le=(be=t.copy)==null?void 0:be.welcomeSubtitle)!=null?le:"Ask anything about your account or products.",pe.placeholder=(Be=(Te=t.copy)==null?void 0:Te.inputPlaceholder)!=null?Be:"How can I help...",((De=(Re=t.sendButton)==null?void 0:Re.useIcon)!=null?De:!1)||(J.textContent=(H=(ne=t.copy)==null?void 0:ne.sendButtonLabel)!=null?H:"Send");let u=(we=(he=t.theme)==null?void 0:he.inputFontFamily)!=null?we:"sans-serif",S=(Le=(Xe=t.theme)==null?void 0:Xe.inputFontWeight)!=null?Le:"400",I=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=I(u),pe.style.fontWeight=S};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{c(u=>({...u,sessionId:l}))}}),$=new Un(t,{onMessagesChanged(l){cn(et,l,X),$&&(l.some(E=>E.role==="user")?nn.render([],$,pe,l):nn.render(t.suggestionChips,$,pe,l,t.suggestionChipsConfig)),dn(!sn),is(l);let u=[...l].reverse().find(I=>I.role==="user"),S=Ye.lastUserMessageId;u&&u.id!==S&&(Ye.lastUserMessageId=u.id,s.emit("user:message",u)),Ye.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Rn(l)},onStatusChanged(l){var I;let u=(I=t.statusIndicator)!=null?I:{},S=E=>{var q,be,le,Te;return E==="idle"?(q=u.idleText)!=null?q:Pt.idle:E==="connecting"?(be=u.connectingText)!=null?be:Pt.connecting:E==="connected"?(le=u.connectedText)!=null?le:Pt.connected:E==="error"?(Te=u.errorText)!=null?Te:Pt.error:Pt[E]};ft.textContent=S(l)},onStreamingChanged(l){sn=l,vn(l),$&&cn(et,$.getMessages(),X),l||dn(!0)}}),t.clientToken&&$.initClientSession().catch(l=>{t.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&$.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=Qs(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&$.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let $n=l=>{var E;l.preventDefault();let u=pe.value.trim(),S=(E=de==null?void 0:de.hasAttachments())!=null?E:!1;if(!u&&!S)return;let I;S&&(I=[],I.push(...de.getContentParts()),u&&I.push(Bs(u))),pe.value="",pe.style.height="auto",$.sendMessage(u,{contentParts:I}),S&&de.clearAttachments()},On=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},Ht=null,Dt=!1,en=null,B=null,Ee=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,He=(l="user")=>{var q,be,le,Te;if(Dt||$.isStreaming())return;let u=Ee();if(!u)return;Ht=new u;let I=(be=((q=t.voiceRecognition)!=null?q:{}).pauseDuration)!=null?be:2e3;Ht.continuous=!0,Ht.interimResults=!0,Ht.lang="en-US";let E=pe.value;Ht.onresult=Be=>{let Re="",De="";for(let H=0;H<Be.results.length;H++){let he=Be.results[H],we=he[0].transcript;he.isFinal?Re+=we+" ":De=we}let ne=E+Re+De;pe.value=ne,en&&clearTimeout(en),(Re||De)&&(en=window.setTimeout(()=>{let H=pe.value.trim();H&&Ht&&Dt&&(Je(),pe.value="",pe.style.height="auto",$.sendMessage(H,{viaVoice:!0}))},I))},Ht.onerror=Be=>{Be.error!=="no-speech"&&Je()},Ht.onend=()=>{if(Dt){let Be=pe.value.trim();Be&&Be!==E.trim()&&(pe.value="",pe.style.height="auto",$.sendMessage(Be,{viaVoice:!0})),Je()}};try{if(Ht.start(),Dt=!0,Ye.active=!0,l!=="system"&&(Ye.manuallyDeactivated=!1),Bn(l),Qt(),j){B={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let Be=(le=t.voiceRecognition)!=null?le:{},Re=(Te=Be.recordingBackgroundColor)!=null?Te:"#ef4444",De=Be.recordingIconColor,ne=Be.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=Re,De){j.style.color=De;let H=j.querySelector("svg");H&&H.setAttribute("stroke",De)}ne&&(j.style.borderColor=ne),j.setAttribute("aria-label","Stop voice recognition")}}catch{Je("system")}},Je=(l="user")=>{if(Dt){if(Dt=!1,en&&(clearTimeout(en),en=null),Ht){try{Ht.stop()}catch{}Ht=null}if(Ye.active=!1,Bn(l),Qt(),j){if(j.classList.remove("tvw-voice-recording"),B){j.style.backgroundColor=B.backgroundColor,j.style.color=B.color,j.style.borderColor=B.borderColor;let u=j.querySelector("svg");u&&u.setAttribute("stroke",B.color||"currentColor"),B=null}j.setAttribute("aria-label","Start voice recognition")}}},Ct=(l,u)=>{var we,Xe,Le,mt,It,K,je;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let I=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 q=(we=l==null?void 0:l.iconName)!=null?we:"mic",be=(Xe=u==null?void 0:u.size)!=null?Xe:"40px",le=(Le=l==null?void 0:l.iconSize)!=null?Le:be,Te=parseFloat(le)||24,Be=(mt=l==null?void 0:l.backgroundColor)!=null?mt:u==null?void 0:u.backgroundColor,Re=(It=l==null?void 0:l.iconColor)!=null?It: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 De=Re||"currentColor",ne=oe(q,Te,De,1.5);ne?(E.appendChild(ne),E.style.color=De):(E.textContent="\u{1F3A4}",E.style.color=De),Be?E.style.backgroundColor=Be:E.classList.add("tvw-bg-cw-primary"),Re?E.style.color=Re:!Re&&!(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),I.appendChild(E);let H=(K=l==null?void 0:l.tooltipText)!=null?K:"Start voice recognition";if(((je=l==null?void 0:l.showTooltip)!=null?je:!1)&&H){let Kt=p("div","tvw-send-button-tooltip");Kt.textContent=H,I.appendChild(Kt)}return{micButton:E,micButtonWrapper:I}},xt=()=>{if(Dt){let l=pe.value.trim();Ye.manuallyDeactivated=!0,Qt(),Je("user"),l&&(pe.value="",pe.style.height="auto",$.sendMessage(l))}else Ye.manuallyDeactivated=!1,Qt(),He("user")};j&&(j.addEventListener("click",xt),pt.push(()=>{Je("system"),j&&j.removeEventListener("click",xt)}));let st=s.on("assistant:complete",()=>{Hn&&(Ye.active||Ye.manuallyDeactivated||Hn==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{!Ye.active&&!Ye.manuallyDeactivated&&He("auto")},600))});pt.push(st);let y=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});pt.push(y);let Oe=()=>{tt(!f,"user")},k=null,h=null;if(b){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:t,defaultRenderer:()=>Jn(t,Oe).element,onToggle:Oe});u&&(h=u)}h||(k=Jn(t,Oe))}k?e.appendChild(k.element):h&&e.appendChild(h),un(),nn.render(t.suggestionChips,$,pe,void 0,t.suggestionChipsConfig),Fn(),vn($.isStreaming()),dn(!0),ns();let M=()=>{var S,I,E,q,be,le,Te,Be;let l=(I=(S=t.launcher)==null?void 0:S.sidebarMode)!=null?I:!1,u=l||((q=(E=t.launcher)==null?void 0:E.fullHeight)!=null?q:!1);if(!b){ye.style.height="",ye.style.width="";return}if(!l){let Re=(le=(be=t==null?void 0:t.launcher)==null?void 0:be.width)!=null?le:t==null?void 0:t.launcherWidth,De=Re!=null?Re:"min(400px, calc(100vw - 24px))";ye.style.width=De,ye.style.maxWidth=De}if(!u){let Re=window.innerHeight,De=64,ne=(Be=(Te=t.launcher)==null?void 0:Te.heightOffset)!=null?Be:0,H=Math.max(200,Re-De),he=Math.min(640,H),we=Math.max(200,he-ne);ye.style.height=`${we}px`}};M(),window.addEventListener("resize",M),pt.push(()=>window.removeEventListener("resize",M)),ln=Pe.scrollTop;let ae=()=>{let l=Pe.scrollTop,u=Pe.scrollHeight,S=Pe.clientHeight,I=u-l-S,E=Math.abs(l-ln);if(ln=l,!fn&&!(E<=ts)){if(!Vt&&I<Pn){Gt=!1,Vt=!0;return}Vt&&I>Pn&&(Gt=!0,hn=Date.now()+es,Vt=!1)}};Pe.addEventListener("scroll",ae,{passive:!0}),pt.push(()=>Pe.removeEventListener("scroll",ae)),pt.push(()=>{Xt&&cancelAnimationFrame(Xt)});let Ze=()=>{V&&(Jt&&(V.removeEventListener("click",Jt),Jt=null),b?(V.style.display="",Jt=()=>{f=!1,un()},V.addEventListener("click",Jt)):V.style.display="none")};Ze(),(()=>{let{clearChatButton:l}=ee;l&&l.addEventListener("click",()=>{$.clearMessages();try{localStorage.removeItem(Ln),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ln}`)}catch(S){console.error("[AgentWidget] Failed to clear default localStorage:",S)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Ln)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(S){console.error("[AgentWidget] Failed to clear custom localStorage:",S)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let S=i.clear();S instanceof Promise&&S.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",I)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)}a={},C.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()})})(),ut.addEventListener("submit",$n),pe.addEventListener("keydown",On),pt.push(()=>{ut.removeEventListener("submit",$n),pe.removeEventListener("keydown",On)}),pt.push(()=>{$.cancel()}),k?pt.push(()=>{k==null||k.destroy()}):h&&pt.push(()=>{h==null||h.remove()});let Ve={update(l){var Tr,Mr,Lr,kr,Wr,Ir,Pr,Hr,Br,Rr,Fr,$r,Or,Nr,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;let u=t.toolCall,S=t.colorScheme;t={...t,...l},it(),fs(e,t),t.colorScheme!==S&&Wn();let I=ws.getForInstance(t.plugins);o.length=0,o.push(...I),b=(Mr=(Tr=t.launcher)==null?void 0:Tr.enabled)!=null?Mr:!0,A=(kr=(Lr=t.launcher)==null?void 0:Lr.autoExpand)!=null?kr:!1,O=(Ir=(Wr=t.features)==null?void 0:Wr.showReasoning)!=null?Ir:!0,se=(Hr=(Pr=t.features)==null?void 0:Pr.showToolCalls)!=null?Hr:!0;let E=G;if(G=(Rr=(Br=t.features)==null?void 0:Br.showEventStreamToggle)!=null?Rr:!1,G&&!E){if(D||(N=new Gn(ve),D=new Xn(re,N),N.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),$.setSSEEventCallback((L,Ce)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:L,timestamp:Date.now(),payload:JSON.stringify(Ce)})})),!_&&Q){let L=($r=(Fr=t.features)==null?void 0:Fr.eventStream)==null?void 0:$r.classNames,Ce="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:"");_=p("button",Ce),_.style.width="28px",_.style.height="28px",_.type="button",_.setAttribute("aria-label","Event Stream"),_.title="Event Stream";let Ge=oe("activity","18px","currentColor",1.5);Ge&&_.appendChild(Ge);let me=ee.clearChatButtonWrapper,We=ee.closeButtonWrapper,ht=me||We;ht&&ht.parentNode===Q?Q.insertBefore(_,ht):Q.appendChild(_),_.addEventListener("click",()=>{fe?$e():xe()})}}else!G&&E&&($e(),_&&(_.remove(),_=null),D==null||D.clear(),N==null||N.destroy(),D=null,N=null);if(((Or=t.launcher)==null?void 0:Or.enabled)===!1&&k&&(k.destroy(),k=null),((Nr=t.launcher)==null?void 0:Nr.enabled)===!1&&h&&(h.remove(),h=null),((Dr=t.launcher)==null?void 0:Dr.enabled)!==!1&&!k&&!h){let L=o.find(Ce=>Ce.renderLauncher);if(L!=null&&L.renderLauncher){let Ce=L.renderLauncher({config:t,defaultRenderer:()=>Jn(t,Oe).element,onToggle:Oe});Ce&&(h=Ce,e.appendChild(h))}h||(k=Jn(t,Oe),e.appendChild(k.element))}k&&k.update(t),vt&&((jr=t.launcher)==null?void 0:jr.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((_r=t.launcher)==null?void 0:_r.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let q=(qr=t.layout)==null?void 0:qr.header;if((q==null?void 0:q.layout)!==Y&&Q){let L=q?Kn(t,q,{showClose:b,onClose:()=>tt(!1,"user")}):an({config:t,showClose:b,onClose:()=>tt(!1,"user")});Q.replaceWith(L.header),Q=L.header,Me=L.iconHolder,vt=L.headerTitle,yt=L.headerSubtitle,V=L.closeButton,Y=q==null?void 0:q.layout}else if(q&&(Me&&(Me.style.display=q.showIcon===!1?"none":""),vt&&(vt.style.display=q.showTitle===!1?"none":""),yt&&(yt.style.display=q.showSubtitle===!1?"none":""),V&&(V.style.display=q.showCloseButton===!1?"none":""),ee.clearChatButtonWrapper)){let L=q.showClearChat;if(L!==void 0){ee.clearChatButtonWrapper.style.display=L?"":"none";let{closeButtonWrapper:Ce}=ee;Ce&&!Ce.classList.contains("tvw-absolute")&&(L?Ce.classList.remove("tvw-ml-auto"):Ce.classList.add("tvw-ml-auto"))}}let le=((zr=t.layout)==null?void 0:zr.showHeader)!==!1;Q&&(Q.style.display=le?"":"none");let Te=((Ur=t.layout)==null?void 0:Ur.showFooter)!==!1;Fe&&(Fe.style.display=Te?"":"none"),b!==W?b?tt(A,"auto"):(f=!0,un()):A!==x&&tt(A,"auto"),x=A,W=b,M(),Ze(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&$&&cn(et,$.getMessages(),X);let ne=(Jr=t.launcher)!=null?Jr:{},H=(Kr=ne.headerIconHidden)!=null?Kr:!1,he=(Vr=(Yr=t.layout)==null?void 0:Yr.header)==null?void 0:Vr.showIcon,we=H||he===!1,Xe=ne.headerIconName,Le=(Xr=ne.headerIconSize)!=null?Xr:"48px";if(Me){let L=ue.querySelector(".tvw-border-b-cw-divider"),Ce=L==null?void 0:L.querySelector(".tvw-flex-col");if(we)Me.style.display="none",L&&Ce&&!L.contains(Ce)&&L.insertBefore(Ce,L.firstChild);else{if(Me.style.display="",Me.style.height=Le,Me.style.width=Le,L&&Ce&&(L.contains(Me)?Me.nextSibling!==Ce&&(Me.remove(),L.insertBefore(Me,Ce)):L.insertBefore(Me,Ce)),Xe){let me=parseFloat(Le)||24,We=oe(Xe,me*.6,"#ffffff",2);We?Me.replaceChildren(We):Me.textContent=(Gr=ne.agentIconText)!=null?Gr:"\u{1F4AC}"}else if(ne.iconUrl){let me=Me.querySelector("img");if(me)me.src=ne.iconUrl,me.style.height=Le,me.style.width=Le;else{let We=document.createElement("img");We.src=ne.iconUrl,We.alt="",We.className="tvw-rounded-xl tvw-object-cover",We.style.height=Le,We.style.width=Le,Me.replaceChildren(We)}}else{let me=Me.querySelector("svg"),We=Me.querySelector("img");(me||We)&&Me.replaceChildren(),Me.textContent=(Qr=ne.agentIconText)!=null?Qr:"\u{1F4AC}"}let Ge=Me.querySelector("img");Ge&&(Ge.style.height=Le,Ge.style.width=Le)}}let mt=(eo=(Zr=t.layout)==null?void 0:Zr.header)==null?void 0:eo.showTitle,It=(no=(to=t.layout)==null?void 0:to.header)==null?void 0:no.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=It===!1?"none":""),V){((ro=(so=t.layout)==null?void 0:so.header)==null?void 0:ro.showCloseButton)===!1?V.style.display="none":V.style.display="";let Ce=(oo=ne.closeButtonSize)!=null?oo:"32px",Ge=(io=ne.closeButtonPlacement)!=null?io:"inline";V.style.height=Ce,V.style.width=Ce;let{closeButtonWrapper:me}=ee,We=Ge==="top-right",ht=me==null?void 0:me.classList.contains("tvw-absolute");if(me&&We!==ht)if(me.remove(),We)me.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",ue.style.position="relative",ue.appendChild(me);else{let Se=(lo=(ao=ne.clearChat)==null?void 0:ao.placement)!=null?lo:"inline",At=(uo=(co=ne.clearChat)==null?void 0:co.enabled)!=null?uo:!0;me.className=At&&Se==="inline"?"":"tvw-ml-auto";let Ft=ue.querySelector(".tvw-border-b-cw-divider");Ft&&Ft.appendChild(me)}if(ne.closeButtonColor?(V.style.color=ne.closeButtonColor,V.classList.remove("tvw-text-cw-muted")):(V.style.color="",V.classList.add("tvw-text-cw-muted")),ne.closeButtonBackgroundColor?(V.style.backgroundColor=ne.closeButtonBackgroundColor,V.classList.remove("hover:tvw-bg-gray-100")):(V.style.backgroundColor="",V.classList.add("hover:tvw-bg-gray-100")),ne.closeButtonBorderWidth||ne.closeButtonBorderColor){let Se=ne.closeButtonBorderWidth||"0px",At=ne.closeButtonBorderColor||"transparent";V.style.border=`${Se} solid ${At}`,V.classList.remove("tvw-border-none")}else V.style.border="",V.classList.add("tvw-border-none");ne.closeButtonBorderRadius?(V.style.borderRadius=ne.closeButtonBorderRadius,V.classList.remove("tvw-rounded-full")):(V.style.borderRadius="",V.classList.add("tvw-rounded-full")),ne.closeButtonPaddingX?(V.style.paddingLeft=ne.closeButtonPaddingX,V.style.paddingRight=ne.closeButtonPaddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ne.closeButtonPaddingY?(V.style.paddingTop=ne.closeButtonPaddingY,V.style.paddingBottom=ne.closeButtonPaddingY):(V.style.paddingTop="",V.style.paddingBottom="");let kt=(po=ne.closeButtonIconName)!=null?po:"x",jt=(go=ne.closeButtonIconText)!=null?go:"\xD7";V.innerHTML="";let Bt=oe(kt,"20px",ne.closeButtonColor||"",2);Bt?V.appendChild(Bt):V.textContent=jt;let ot=(mo=ne.closeButtonTooltipText)!=null?mo:"Close chat",_t=(ho=ne.closeButtonShowTooltip)!=null?ho:!0;if(V.setAttribute("aria-label",ot),me&&(me._cleanupTooltip&&(me._cleanupTooltip(),delete me._cleanupTooltip),_t&&ot)){let Se=null,At=()=>{if(Se||!V)return;Se=p("div","tvw-clear-chat-tooltip"),Se.textContent=ot;let qn=p("div");qn.className="tvw-clear-chat-tooltip-arrow",Se.appendChild(qn);let mn=V.getBoundingClientRect();Se.style.position="fixed",Se.style.left=`${mn.left+mn.width/2}px`,Se.style.top=`${mn.top-8}px`,Se.style.transform="translate(-50%, -100%)",document.body.appendChild(Se)},Ft=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};me.addEventListener("mouseenter",At),me.addEventListener("mouseleave",Ft),V.addEventListener("focus",At),V.addEventListener("blur",Ft),me._cleanupTooltip=()=>{Ft(),me&&(me.removeEventListener("mouseenter",At),me.removeEventListener("mouseleave",Ft)),V&&(V.removeEventListener("focus",At),V.removeEventListener("blur",Ft))}}}let{clearChatButton:K,clearChatButtonWrapper:je}=ee;if(K){let L=(fo=ne.clearChat)!=null?fo:{},Ce=(wo=L.enabled)!=null?wo:!0,Ge=(yo=(vo=t.layout)==null?void 0:vo.header)==null?void 0:yo.showClearChat,me=Ge!==void 0?Ge:Ce,We=(bo=L.placement)!=null?bo:"inline";if(je){je.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=We==="top-right",jt=je.classList.contains("tvw-absolute");if(kt!==jt&&me){if(je.remove(),kt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",ue.style.position="relative",ue.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ot=ue.querySelector(".tvw-border-b-cw-divider"),_t=ee.closeButtonWrapper;ot&&_t&&_t.parentElement===ot?ot.insertBefore(je,_t):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(me){let ht=(Co=L.size)!=null?Co:"32px";K.style.height=ht,K.style.width=ht;let kt=(xo=L.iconName)!=null?xo:"refresh-cw",jt=(So=L.iconColor)!=null?So:"";K.innerHTML="";let Bt=oe(kt,"20px",jt||"",2);if(Bt&&K.appendChild(Bt),jt?(K.style.color=jt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),L.backgroundColor?(K.style.backgroundColor=L.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let Se=L.borderWidth||"0px",At=L.borderColor||"transparent";K.style.border=`${Se} solid ${At}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");L.borderRadius?(K.style.borderRadius=L.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),L.paddingX?(K.style.paddingLeft=L.paddingX,K.style.paddingRight=L.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),L.paddingY?(K.style.paddingTop=L.paddingY,K.style.paddingBottom=L.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let ot=(Ao=L.tooltipText)!=null?Ao:"Clear chat",_t=(Eo=L.showTooltip)!=null?Eo:!0;if(K.setAttribute("aria-label",ot),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),_t&&ot)){let Se=null,At=()=>{if(Se||!K)return;Se=p("div","tvw-clear-chat-tooltip"),Se.textContent=ot;let qn=p("div");qn.className="tvw-clear-chat-tooltip-arrow",Se.appendChild(qn);let mn=K.getBoundingClientRect();Se.style.position="fixed",Se.style.left=`${mn.left+mn.width/2}px`,Se.style.top=`${mn.top-8}px`,Se.style.transform="translate(-50%, -100%)",document.body.appendChild(Se)},Ft=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};je.addEventListener("mouseenter",At),je.addEventListener("mouseleave",Ft),K.addEventListener("focus",At),K.addEventListener("blur",Ft),je._cleanupTooltip=()=>{Ft(),je&&(je.removeEventListener("mouseenter",At),je.removeEventListener("mouseleave",Ft)),K&&(K.removeEventListener("focus",At),K.removeEventListener("blur",Ft))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[vs],zt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Mn.message,Mn.messageAndClick];C=ys({parsers:Kt,handlers:zt,getSessionMetadata:v,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),X=Di(t,C,P),$.updateConfig(t),cn(et,$.getMessages(),X),nn.render(t.suggestionChips,$,pe,void 0,t.suggestionChipsConfig),Fn(),vn($.isStreaming());let rn=((To=t.voiceRecognition)==null?void 0:To.enabled)===!0,as=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(rn&&as)if(!j||!Qe){let L=Ct(t.voiceRecognition,t.sendButton);L&&(j=L.micButton,Qe=L.micButtonWrapper,Lt.insertBefore(Qe,ct),j.addEventListener("click",xt),j.disabled=$.isStreaming())}else{let L=(Mo=t.voiceRecognition)!=null?Mo:{},Ce=(Lo=t.sendButton)!=null?Lo:{},Ge=(ko=L.iconName)!=null?ko:"mic",me=(Wo=Ce.size)!=null?Wo:"40px",We=(Io=L.iconSize)!=null?Io:me,ht=parseFloat(We)||24;j.style.width=We,j.style.height=We,j.style.minWidth=We,j.style.minHeight=We;let kt=(Ho=(Po=L.iconColor)!=null?Po:Ce.textColor)!=null?Ho:"currentColor";j.innerHTML="";let jt=oe(Ge,ht,kt,2);jt?j.appendChild(jt):j.textContent="\u{1F3A4}";let Bt=(Bo=L.backgroundColor)!=null?Bo:Ce.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&&!Ce.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),L.borderWidth?(j.style.borderWidth=L.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),L.borderColor?j.style.borderColor=L.borderColor:j.style.borderColor="",L.paddingX?(j.style.paddingLeft=L.paddingX,j.style.paddingRight=L.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),L.paddingY?(j.style.paddingTop=L.paddingY,j.style.paddingBottom=L.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let ot=Qe==null?void 0:Qe.querySelector(".tvw-send-button-tooltip"),_t=(Ro=L.tooltipText)!=null?Ro:"Start voice recognition";if(((Fo=L.showTooltip)!=null?Fo:!1)&&_t)if(ot)ot.textContent=_t,ot.style.display="";else{let At=document.createElement("div");At.className="tvw-send-button-tooltip",At.textContent=_t,Qe==null||Qe.insertBefore(At,j)}else ot&&(ot.style.display="none");Qe.style.display="",j.disabled=$.isStreaming()}else j&&Qe&&(Qe.style.display="none",Dt&&Je());if((($o=t.attachments)==null?void 0:$o.enabled)===!0)if(!z||!Ae){let L=(Oo=t.attachments)!=null?Oo:{},Ge=(Do=((No=t.sendButton)!=null?No:{}).size)!=null?Do:"40px";ge||(ge=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ge.style.display="none",ut.insertBefore(ge,pe)),F||(F=document.createElement("input"),F.type="file",F.accept=((jo=L.allowedTypes)!=null?jo:on).join(","),F.multiple=((_o=L.maxFiles)!=null?_o:4)>1,F.style.display="none",F.setAttribute("aria-label","Attach files"),ut.insertBefore(F,pe)),z=p("div","tvw-send-button-wrapper"),Ae=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),Ae.type="button",Ae.setAttribute("aria-label",(qo=L.buttonTooltipText)!=null?qo:"Attach file");let me=(zo=L.buttonIconName)!=null?zo:"paperclip",We=Ge,ht=parseFloat(We)||40,kt=Math.round(ht*.6);Ae.style.width=We,Ae.style.height=We,Ae.style.minWidth=We,Ae.style.minHeight=We,Ae.style.fontSize="18px",Ae.style.lineHeight="1",Ae.style.backgroundColor="transparent",Ae.style.color="var(--cw-primary, #111827)",Ae.style.border="none",Ae.style.borderRadius="6px",Ae.style.transition="background-color 0.15s ease",Ae.addEventListener("mouseenter",()=>{Ae.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),Ae.addEventListener("mouseleave",()=>{Ae.style.backgroundColor="transparent"});let jt=oe(me,kt,"currentColor",1.5);jt?Ae.appendChild(jt):Ae.textContent="\u{1F4CE}",Ae.addEventListener("click",_t=>{_t.preventDefault(),F==null||F.click()}),z.appendChild(Ae);let Bt=(Uo=L.buttonTooltipText)!=null?Uo:"Attach file",ot=p("div","tvw-send-button-tooltip");ot.textContent=Bt,z.appendChild(ot),Wt.append(z),!de&&F&&ge&&(de=Cn.fromConfig(L),de.setPreviewsContainer(ge),F.addEventListener("change",async()=>{de&&(F!=null&&F.files)&&(await de.handleFileSelect(F.files),F.value="")}))}else{z.style.display="";let L=(Jo=t.attachments)!=null?Jo:{};F&&(F.accept=((Ko=L.allowedTypes)!=null?Ko:on).join(","),F.multiple=((Yo=L.maxFiles)!=null?Yo:4)>1),de&&de.updateConfig({allowedTypes:L.allowedTypes,maxFileSize:L.maxFileSize,maxFiles:L.maxFiles})}else z&&(z.style.display="none"),de&&de.clearAttachments();let dt=(Vo=t.sendButton)!=null?Vo:{},ls=(Xo=dt.useIcon)!=null?Xo:!1,Nn=(Go=dt.iconText)!=null?Go:"\u2191",pn=dt.iconName,gn=(Qo=dt.tooltipText)!=null?Qo:"Send message",Vi=(Zo=dt.showTooltip)!=null?Zo:!1,Dn=(ei=dt.size)!=null?ei:"40px",ds=dt.backgroundColor,Yt=dt.textColor;if(ls){if(J.style.width=Dn,J.style.height=Dn,J.style.minWidth=Dn,J.style.minHeight=Dn,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",pn){let L=parseFloat(Dn)||24,Ce=Yt&&typeof Yt=="string"&&Yt.trim()?Yt.trim():"currentColor",Ge=oe(pn,L,Ce,2);Ge?(J.appendChild(Ge),J.style.color=Ce):(J.textContent=Nn,Yt?J.style.color=Yt:J.classList.add("tvw-text-white"))}else J.textContent=Nn,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",ds?(J.style.backgroundColor=ds,J.classList.remove("tvw-bg-cw-primary")):J.classList.add("tvw-bg-cw-primary")}else J.textContent=(ni=(ti=t.copy)==null?void 0:ti.sendButtonLabel)!=null?ni:"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",ds?(J.style.backgroundColor=ds,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");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 jn=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(Vi&&gn)if(jn)jn.textContent=gn,jn.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=gn,ct==null||ct.insertBefore(L,J)}else jn&&(jn.style.display="none");let _n=(si=t.statusIndicator)!=null?si:{},Xi=(ri=_n.visible)!=null?ri:!0;if(ft.style.display=Xi?"":"none",$){let L=$.getStatus(),Ce=Ge=>{var me,We,ht,kt;return Ge==="idle"?(me=_n.idleText)!=null?me:Pt.idle:Ge==="connecting"?(We=_n.connectingText)!=null?We:Pt.connecting:Ge==="connected"?(ht=_n.connectedText)!=null?ht:Pt.connected:Ge==="error"?(kt=_n.errorText)!=null?kt:Pt.error:Pt[Ge]};ft.textContent=Ce(L)}},open(){b&&tt(!0,"api")},close(){b&&tt(!1,"api")},toggle(){b&&tt(!f,"api")},clearChat(){$.clearMessages();try{localStorage.removeItem(Ln),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ln}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Ln)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(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},C.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()},setMessage(l){return!pe||$.isStreaming()?!1:(!f&&b&&tt(!0,"system"),pe.value=l,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let u=(l==null?void 0:l.trim())||pe.value.trim();return u?(!f&&b&&tt(!0,"system"),pe.value="",pe.style.height="auto",$.sendMessage(u),!0):!1},startVoiceRecognition(){return Dt||$.isStreaming()||!Ee()?!1:(!f&&b&&tt(!0,"system"),Ye.manuallyDeactivated=!1,Qt(),He("user"),!0)},stopVoiceRecognition(){return Dt?(Ye.manuallyDeactivated=!0,Qt(),Je("user"),!0):!1},injectMessage(l){return!f&&b&&tt(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!f&&b&&tt(!0,"system");let u=$.injectAssistantMessage(l);return R&&(R=!1,T&&(clearTimeout(T),T=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),u},injectUserMessage(l){return!f&&b&&tt(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!f&&b&&tt(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!f&&b&&tt(!0,"system"),$.injectMessageBatch(l)},injectTestMessage(l){!f&&b&&tt(!0,"system"),$.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(){!G||!D||xe()},hideEventStream(){fe&&$e()},isEventStreamVisible(){return fe},getMessages(){return $.getMessages()},getStatus(){return $.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 b&&f},isVoiceActive(){return Ye.active},getState(){return{open:b&&f,launcherEnabled:b,voiceActive:Ye.active,streaming:$.isStreaming()}},showCSATFeedback(l){!f&&b&&tt(!0,"system");let u=et.querySelector(".tvw-feedback-container");u&&u.remove();let S=Xs({onSubmit:async(I,E)=>{var q;$.isClientTokenMode()&&await $.submitCSATFeedback(I,E),(q=l==null?void 0:l.onSubmit)==null||q.call(l,I,E)},onDismiss:l==null?void 0:l.onDismiss,...l});et.appendChild(S),S.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!f&&b&&tt(!0,"system");let u=et.querySelector(".tvw-feedback-container");u&&u.remove();let S=Gs({onSubmit:async(I,E)=>{var q;$.isClientTokenMode()&&await $.submitNPSFeedback(I,E),(q=l==null?void 0:l.onSubmit)==null||q.call(l,I,E)},onDismiss:l==null?void 0:l.onDismiss,...l});et.appendChild(S),S.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return $.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return $.submitNPSFeedback(l,u)},destroy(){pt.forEach(l=>l()),Ie.remove(),k==null||k.destroy(),h==null||h.remove(),Jt&&V.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:Ve,getMessages:Ve.getMessages,getStatus:Ve.getStatus,getMetadata:Ve.getPersistentMetadata,updateMetadata:Ve.updatePersistentMetadata,clearHistory:()=>Ve.clearChat(),setVoiceActive:S=>S?Ve.startVoiceRecognition():Ve.stopVoiceRecognition()};window.AgentWidgetBrowser=u,pt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(G&&typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=I=>{let E=I.detail;(!(E!=null&&E.instanceId)||E.instanceId===l)&&Ve.showEventStream()},S=I=>{let E=I.detail;(!(E!=null&&E.instanceId)||E.instanceId===l)&&Ve.hideEventStream()};window.addEventListener("persona:showEventStream",u),window.addEventListener("persona:hideEventStream",S),pt.push(()=>{window.removeEventListener("persona:showEventStream",u),window.removeEventListener("persona:hideEventStream",S)})}let _e=Za(t.persistState);if(_e&&b){let l=el(_e.storage),u=`${_e.keyPrefix}widget-open`,S=`${_e.keyPrefix}widget-voice`,I=`${_e.keyPrefix}widget-voice-mode`;if(l){let E=((Cr=_e.persist)==null?void 0:Cr.openState)&&l.getItem(u)==="true",q=((xr=_e.persist)==null?void 0:xr.voiceState)&&l.getItem(S)==="true",be=((Sr=_e.persist)==null?void 0:Sr.voiceState)&&l.getItem(I)==="true";if(E&&setTimeout(()=>{Ve.open(),setTimeout(()=>{var le;if(q||be)Ve.startVoiceRecognition();else if((le=_e.persist)!=null&&le.focusInput){let Te=e.querySelector("textarea");Te&&Te.focus()}},100)},0),(Ar=_e.persist)!=null&&Ar.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Er=_e.persist)!=null&&Er.voiceState&&(s.on("voice:state",le=>{l.setItem(S,le.active?"true":"false")}),s.on("user:message",le=>{l.setItem(I,le.viaVoice?"true":"false")})),_e.clearOnChatClear){let le=()=>{l.removeItem(u),l.removeItem(S),l.removeItem(I)},Te=()=>le();window.addEventListener("persona:clear-chat",Te),pt.push(()=>{window.removeEventListener("persona:clear-chat",Te)})}}}return Ve};var er={},tl=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},nl=()=>{try{if(typeof er!="undefined"&&er.url)return new URL("../widget.css",er.url).href}catch{}return null},ji=e=>{let n=nl(),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)}},_i=e=>{var g,v,c,m;let n=tl(e.target),r=document.createElement("div");r.className="persona-host";let t=(c=(v=(g=e.config)==null?void 0:g.launcher)==null?void 0:v.enabled)!=null?c:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let w=r.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),ji(w)}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),ji(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=Zs(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 qi={name:"@runtypelabs/persona",version:"1.43.5",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 kn=qi.version;function tn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function rl(e){if(e)return{getHeaders:tn(e.getHeaders),onFeedback:tn(e.onFeedback),onCopy:tn(e.onCopy),requestMiddleware:tn(e.requestMiddleware),actionHandlers:tn(e.actionHandlers),actionParsers:tn(e.actionParsers),postprocessMessage:tn(e.postprocessMessage),contextProviders:tn(e.contextProviders),streamParser:tn(e.streamParser)}}var zi=`({ text, message }: any) => {
60
+ `}if(!I){let un="max-height: -moz-available !important; max-height: stretch !important;",pn=l?"":"padding-top: 1.25em !important;";Re.style.cssText+=un+pn}};mn(),fs(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,Wn=()=>{Ut&&(Ut(),Ut=null),t.colorScheme==="auto"&&(Ut=bi(()=>{fs(e,t)}))};Wn(),at.push(()=>{Ut&&(Ut(),Ut=null)});let tn=Hi(St),Jt=null,F,nn=!1,Vt=!0,an=0,In=0,Xt=null,Gt=!1,hn=0,fn=!1,Zn=125,es=2e3,ts=5,Pn=50,wn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Hn=(br=(yr=t.voiceRecognition)==null?void 0:yr.autoResume)!=null?br:!1,Bn=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}}))},ns=()=>{var k,E;if(((k=t.voiceRecognition)==null?void 0:k.enabled)===!1)return;let l=Qs(a.voiceState),u=!!l.active,b=Number((E=l.timestamp)!=null?E:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-b<Za&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,et("restore"))},1e3)},ss=()=>F?Di(F.getMessages()).filter(l=>!l.__skipPersist):[];function Rn(l){if(!(i!=null&&i.save))return;let b={messages:l?Di(l):F?ss():[],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 ln=(l=!1)=>{if(!Vt)return;let u=Date.now();Gt&&u<hn&&!l||(Gt&&u>=hn&&(Gt=!1),!(!l&&!nn)&&(u-In<Zn||(In=u,Xt&&cancelAnimationFrame(Xt),Xt=requestAnimationFrame(()=>{Gt||!Vt||(fn=!0,Fe.scrollTop=Fe.scrollHeight,an=Fe.scrollTop,requestAnimationFrame(()=>{fn=!1}),Xt=null)}))))},Zt=null,rs=()=>Re.querySelector("#persona-scroll-container")||Fe,os=(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)},is=l=>{let u=new Map;l.forEach(b=>{let k=wn.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)}),wn.clear(),u.forEach((b,k)=>{wn.set(k,b)})},dn=(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:()=>$s(I),config:t})}else if(I.variant==="tool"&&I.toolCall&&Ce.renderToolCall){if(!oe)return;he=Ce.renderToolCall({message:I,defaultRenderer:()=>Os(I,t),config:t})}else Ce.renderMessage&&(he=Ce.renderMessage({message:I,defaultRenderer:()=>{let K=Vn(I,b,Xe,t.messageActions,dt,{loadingIndicatorRenderer:$,widgetConfig:t});return I.role!=="user"&&Ds(K,I,t,F),K},config:t}));if(!he&&I.role==="assistant"&&!I.variant&&t.enableComponentStreaming!==!1&&Ys(I)){let _e=Vs(I);if(_e){let Kt=Ks(_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 sn=document.createElement("div");sn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",sn.innerHTML=b({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),qt.appendChild(sn)}qt.appendChild(Kt),he=qt}}}if(!he)if(I.variant==="reasoning"&&I.reasoning){if(!_)return;he=$s(I)}else if(I.variant==="tool"&&I.toolCall){if(!oe)return;he=Os(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=Vn(I,b,K,t.messageActions,dt,{loadingIndicatorRenderer:$,widgetConfig:t}),I.role!=="user"&&he&&Ds(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(nn&&u.some(I=>I.role==="user")&&!ve&&!ye){let I={config:t,streaming:!0,location:"standalone",defaultRenderer:Sn},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=Sn()),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(!nn&&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)}}Ci(l,k),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=rs();os(I)})})},cn=()=>{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="")))},rt=(l,u="user")=>{if(!C||v===l)return;let b=v;v=l,cn(),v&&(ie(),ln(!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()})},vn=l=>{J.disabled=l,j&&(j.disabled=l),tn.buttons.forEach(u=>{u.disabled=l})},Fn=()=>{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 Un(t,{onMessagesChanged(l){dn(Qe,l,se),F&&(l.some(E=>E.role==="user")?tn.render([],F,pe,l):tn.render(t.suggestionChips,F,pe,l,t.suggestionChipsConfig)),ln(!nn),is(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),Rn(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){nn=l,vn(l),F&&dn(Qe,F.getMessages(),se),l||ln(!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=Qs(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 $n=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(Bs(u))),pe.value="",pe.style.height="auto",F.sendMessage(u,{contentParts:k}),b&&de.clearAttachments()},On=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),Bn(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,Bn(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",()=>{Hn&&(Ke.active||Ke.manuallyDeactivated||Hn==="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=()=>{rt(!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:()=>Jn(t,H).element,onToggle:H});u&&(S=u)}S||(h=Jn(t,H))}h?e.appendChild(h.element):S&&e.appendChild(S),cn(),tn.render(t.suggestionChips,F,pe,void 0,t.suggestionChipsConfig),Fn(),vn(F.isStreaming()),ln(!0),ns();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)),an=Fe.scrollTop;let nt=()=>{let l=Fe.scrollTop,u=Fe.scrollHeight,b=Fe.clientHeight,k=u-l-b,E=Math.abs(l-an);if(an=l,!fn&&!(E<=ts)){if(!Vt&&k<Pn){Gt=!1,Vt=!0;return}Vt&&k>Pn&&(Gt=!0,hn=Date.now()+es,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,cn()},Y.addEventListener("click",Jt)):Y.style.display="none")};st(),(()=>{let{clearChatButton:l}=ee;l&&l.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(kn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${kn}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==kn)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",$n),pe.addEventListener("keydown",On),at.push(()=>{gt.removeEventListener("submit",$n),pe.removeEventListener("keydown",On)}),at.push(()=>{F.cancel()}),h?at.push(()=>{h==null||h.destroy()}):S&&at.push(()=>{S==null||S.remove()});let We={update(l){var Mr,kr,Lr,Wr,Ir,Pr,Hr,Br,Rr,Fr,$r,Or,Nr,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;let u=t.toolCall,b=t.colorScheme;t={...t,...l},mn(),fs(e,t),t.colorScheme!==b&&Wn();let k=ws.getForInstance(t.plugins);o.length=0,o.push(...k),C=(kr=(Mr=t.launcher)==null?void 0:Mr.enabled)!=null?kr:!0,T=(Wr=(Lr=t.launcher)==null?void 0:Lr.autoExpand)!=null?Wr:!1,_=(Pr=(Ir=t.features)==null?void 0:Ir.showReasoning)!=null?Pr:!0,oe=(Br=(Hr=t.features)==null?void 0:Hr.showToolCalls)!=null?Br:!0;let E=X;if(X=(Fr=(Rr=t.features)==null?void 0:Rr.showEventStreamToggle)!=null?Fr:!1,X&&!E){if(D||(N=new Gn(xe),D=new Xn(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=(Or=($r=t.features)==null?void 0:$r.eventStream)==null?void 0:Or.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(((Nr=t.launcher)==null?void 0:Nr.enabled)===!1&&h&&(h.destroy(),h=null),((Dr=t.launcher)==null?void 0:Dr.enabled)===!1&&S&&(S.remove(),S=null),((jr=t.launcher)==null?void 0:jr.enabled)!==!1&&!h&&!S){let M=o.find(Ee=>Ee.renderLauncher);if(M!=null&&M.renderLauncher){let Ee=M.renderLauncher({config:t,defaultRenderer:()=>Jn(t,H).element,onToggle:H});Ee&&(S=Ee,e.appendChild(S))}S||(h=Jn(t,H),e.appendChild(h.element))}h&&h.update(t),vt&&((_r=t.launcher)==null?void 0:_r.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((qr=t.launcher)==null?void 0:qr.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let $=(zr=t.layout)==null?void 0:zr.header;if(($==null?void 0:$.layout)!==V&&Q){let M=$?Kn(t,$,{showClose:C,onClose:()=>rt(!1,"user")}):on({config:t,showClose:C,onClose:()=>rt(!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=((Ur=t.layout)==null?void 0:Ur.showHeader)!==!1;Q&&(Q.style.display=le?"":"none");let ye=((Jr=t.layout)==null?void 0:Jr.showFooter)!==!1;$e&&($e.style.display=ye?"":"none"),C!==L?C?rt(T,"auto"):(v=!0,cn()):T!==A&&rt(T,"auto"),A=T,L=C,ie(),st(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&F&&dn(Qe,F.getMessages(),se);let G=(Kr=t.launcher)!=null?Kr:{},I=(Yr=G.headerIconHidden)!=null?Yr:!1,he=(Xr=(Vr=t.layout)==null?void 0:Vr.header)==null?void 0:Xr.showIcon,Ce=I||he===!1,Xe=G.headerIconName,Pe=(Gr=G.headerIconSize)!=null?Gr:"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=(Qr=G.agentIconText)!=null?Qr:"\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=(Zr=G.agentIconText)!=null?Zr:"\u{1F4AC}"}let Ge=Le.querySelector("img");Ge&&(Ge.style.height=Pe,Ge.style.width=Pe)}}let mt=(to=(eo=t.layout)==null?void 0:eo.header)==null?void 0:to.showTitle,Wt=(so=(no=t.layout)==null?void 0:no.header)==null?void 0:so.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=Wt===!1?"none":""),Y){((oo=(ro=t.layout)==null?void 0:ro.header)==null?void 0:oo.showCloseButton)===!1?Y.style.display="none":Y.style.display="";let Ee=(io=G.closeButtonSize)!=null?io:"32px",Ge=(ao=G.closeButtonPlacement)!=null?ao:"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=(co=(lo=G.clearChat)==null?void 0:lo.placement)!=null?co:"inline",xt=(po=(uo=G.clearChat)==null?void 0:uo.enabled)!=null?po:!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=(go=G.closeButtonIconName)!=null?go:"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=(ho=G.closeButtonTooltipText)!=null?ho:"Close chat",jt=(fo=G.closeButtonShowTooltip)!=null?fo:!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 qn=p("div");qn.className="tvw-clear-chat-tooltip-arrow",Me.appendChild(qn);let gn=Y.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${gn.left+gn.width/2}px`,Me.style.top=`${gn.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=(vo=M.enabled)!=null?vo:!0,Ge=(bo=(yo=t.layout)==null?void 0:yo.header)==null?void 0:bo.showClearChat,me=Ge!==void 0?Ge:Ee,Be=(Co=M.placement)!=null?Co:"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=(xo=M.size)!=null?xo:"32px";K.style.height=ht,K.style.width=ht;let kt=(So=M.iconName)!=null?So:"refresh-cw",Dt=(Ao=M.iconColor)!=null?Ao:"";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=(Eo=M.tooltipText)!=null?Eo:"Clear chat",jt=(To=M.showTooltip)!=null?To:!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 qn=p("div");qn.className="tvw-clear-chat-tooltip-arrow",Me.appendChild(qn);let gn=K.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${gn.left+gn.width/2}px`,Me.style.top=`${gn.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:[vs],qt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Mn.message,Mn.messageAndClick];x=ys({parsers:Kt,handlers:qt,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),se=ji(t,x,P),F.updateConfig(t),dn(Qe,F.getMessages(),se),tn.render(t.suggestionChips,F,pe,void 0,t.suggestionChipsConfig),Fn(),vn(F.isStreaming());let sn=((Mo=t.voiceRecognition)==null?void 0:Mo.enabled)===!0,as=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(sn&&as)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=(ko=t.voiceRecognition)!=null?ko:{},Ee=(Lo=t.sendButton)!=null?Lo:{},Ge=(Wo=M.iconName)!=null?Wo:"mic",me=(Io=Ee.size)!=null?Io:"40px",Be=(Po=M.iconSize)!=null?Po:me,ht=parseFloat(Be)||24;j.style.width=Be,j.style.height=Be,j.style.minWidth=Be,j.style.minHeight=Be;let kt=(Bo=(Ho=M.iconColor)!=null?Ho:Ee.textColor)!=null?Bo:"currentColor";j.innerHTML="";let Dt=re(Ge,ht,kt,2);Dt?j.appendChild(Dt):j.textContent="\u{1F3A4}";let Ht=(Ro=M.backgroundColor)!=null?Ro: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=(Fo=M.tooltipText)!=null?Fo:"Start voice recognition";if((($o=M.showTooltip)!=null?$o:!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(((Oo=t.attachments)==null?void 0:Oo.enabled)===!0)if(!z||!ke){let M=(No=t.attachments)!=null?No:{},Ge=(jo=((Do=t.sendButton)!=null?Do:{}).size)!=null?jo:"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=((_o=M.allowedTypes)!=null?_o:rn).join(","),R.multiple=((qo=M.maxFiles)!=null?qo: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",(zo=M.buttonTooltipText)!=null?zo:"Attach file");let me=(Uo=M.buttonIconName)!=null?Uo:"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=(Jo=M.buttonTooltipText)!=null?Jo:"Attach file",lt=p("div","tvw-send-button-tooltip");lt.textContent=Ht,z.appendChild(lt),Lt.append(z),!de&&R&&ge&&(de=Cn.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=(Ko=t.attachments)!=null?Ko:{};R&&(R.accept=((Yo=M.allowedTypes)!=null?Yo:rn).join(","),R.multiple=((Vo=M.maxFiles)!=null?Vo: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=(Xo=t.sendButton)!=null?Xo:{},ls=(Go=ut.useIcon)!=null?Go:!1,Nn=(Qo=ut.iconText)!=null?Qo:"\u2191",un=ut.iconName,pn=(Zo=ut.tooltipText)!=null?Zo:"Send message",Xi=(ei=ut.showTooltip)!=null?ei:!1,Dn=(ti=ut.size)!=null?ti:"40px",ds=ut.backgroundColor,Yt=ut.textColor;if(ls){if(J.style.width=Dn,J.style.height=Dn,J.style.minWidth=Dn,J.style.minHeight=Dn,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",un){let M=parseFloat(Dn)||24,Ee=Yt&&typeof Yt=="string"&&Yt.trim()?Yt.trim():"currentColor",Ge=re(un,M,Ee,2);Ge?(J.appendChild(Ge),J.style.color=Ee):(J.textContent=Nn,Yt?J.style.color=Yt:J.classList.add("tvw-text-white"))}else J.textContent=Nn,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",ds?(J.style.backgroundColor=ds,J.classList.remove("tvw-bg-cw-primary")):J.classList.add("tvw-bg-cw-primary")}else J.textContent=(si=(ni=t.copy)==null?void 0:ni.sendButtonLabel)!=null?si:"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",ds?(J.style.backgroundColor=ds,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 jn=pt==null?void 0:pt.querySelector(".tvw-send-button-tooltip");if(Xi&&pn)if(jn)jn.textContent=pn,jn.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=pn,pt==null||pt.insertBefore(M,J)}else jn&&(jn.style.display="none");let _n=(ri=t.statusIndicator)!=null?ri:{},Gi=(oi=_n.visible)!=null?oi:!0;if(ft.style.display=Gi?"":"none",F){let M=F.getStatus(),Ee=Ge=>{var me,Be,ht,kt;return Ge==="idle"?(me=_n.idleText)!=null?me:It.idle:Ge==="connecting"?(Be=_n.connectingText)!=null?Be:It.connecting:Ge==="connected"?(ht=_n.connectedText)!=null?ht:It.connected:Ge==="error"?(kt=_n.errorText)!=null?kt:It.error:It[Ge]};ft.textContent=Ee(M)}},open(){C&&rt(!0,"api")},close(){C&&rt(!1,"api")},toggle(){C&&rt(!v,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(kn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${kn}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==kn)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&&rt(!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&&rt(!0,"system"),pe.value="",pe.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){return Ot||F.isStreaming()||!De()?!1:(!v&&C&&rt(!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&&rt(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!v&&C&&rt(!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&&rt(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!v&&C&&rt(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!v&&C&&rt(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!v&&C&&rt(!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&&rt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Xs({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&&rt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Gs({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((((Cr=r==null?void 0:r.debugTools)!=null?Cr:!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=el(t.persistState);if(je&&C){let l=tl(je.storage),u=`${je.keyPrefix}widget-open`,b=`${je.keyPrefix}widget-voice`,k=`${je.keyPrefix}widget-voice-mode`;if(l){let E=((xr=je.persist)==null?void 0:xr.openState)&&l.getItem(u)==="true",$=((Sr=je.persist)==null?void 0:Sr.voiceState)&&l.getItem(b)==="true",ve=((Ar=je.persist)==null?void 0:Ar.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),(Er=je.persist)!=null&&Er.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Tr=je.persist)!=null&&Tr.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 er={},nl=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},sl=()=>{try{if(typeof er!="undefined"&&er.url)return new URL("../widget.css",er.url).href}catch{}return null},_i=e=>{let n=sl(),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)}},qi=e=>{var g,w,c,m;let n=nl(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),_i(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),_i(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=Zs(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 zi={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 Ln=zi.version;function en(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function ol(e){if(e)return{getHeaders:en(e.getHeaders),onFeedback:en(e.onFeedback),onCopy:en(e.onCopy),requestMiddleware:en(e.requestMiddleware),actionHandlers:en(e.actionHandlers),actionParsers:en(e.actionParsers),postprocessMessage:en(e.postprocessMessage),contextProviders:en(e.contextProviders),streamParser:en(e.streamParser)}}var Ui=`({ text, message }: any) => {
61
61
  const jsonSource = (message as any).rawContent || text || message.content;
62
62
  if (!jsonSource || typeof jsonSource !== 'string') return null;
63
63
  let cleanJson = jsonSource
@@ -70,7 +70,7 @@ import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=
70
70
  if (parsed.action) return { type: parsed.action, payload: parsed };
71
71
  } catch (e) { return null; }
72
72
  return null;
73
- }`,Ui=`function(ctx) {
73
+ }`,Ji=`function(ctx) {
74
74
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
75
75
  if (!jsonSource || typeof jsonSource !== 'string') return null;
76
76
  var cleanJson = jsonSource
@@ -83,7 +83,7 @@ import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=
83
83
  if (parsed.action) return { type: parsed.action, payload: parsed };
84
84
  } catch (e) { return null; }
85
85
  return null;
86
- }`,Ji=`(action: any, context: any) => {
86
+ }`,Ki=`(action: any, context: any) => {
87
87
  if (action.type !== 'nav_then_click') return;
88
88
  const payload = action.payload || action.raw || {};
89
89
  const url = payload?.page;
@@ -100,7 +100,7 @@ import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=
100
100
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
101
101
  window.location.href = targetUrl;
102
102
  return { handled: true, displayText: text };
103
- }`,Ki=`function(action, context) {
103
+ }`,Yi=`function(action, context) {
104
104
  if (action.type !== 'nav_then_click') return;
105
105
  var payload = action.payload || action.raw || {};
106
106
  var url = payload.page;
@@ -117,24 +117,24 @@ import{Marked as Gi}from"marked";var Qi=e=>{if(e)return e},cs=e=>{var o,s;let n=
117
117
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
118
118
  window.location.href = targetUrl;
119
119
  return { handled: true, displayText: text };
120
- }`,ol=`(parsed: any) => {
120
+ }`,il=`(parsed: any) => {
121
121
  if (!parsed || typeof parsed !== 'object') return null;
122
122
  if (parsed.action === 'nav_then_click') return 'Navigating...';
123
123
  if (parsed.action === 'message') return parsed.text || '';
124
124
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
125
125
  return parsed.text || null;
126
- }`,il=`function(parsed) {
126
+ }`,al=`function(parsed) {
127
127
  if (!parsed || typeof parsed !== 'object') return null;
128
128
  if (parsed.action === 'nav_then_click') return 'Navigating...';
129
129
  if (parsed.action === 'message') return parsed.text || '';
130
130
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
131
131
  return parsed.text || null;
132
- }`;function al(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 bs(e){var n,r;return(r=(n=e.parserType)!=null?n:al(e.streamParser))!=null?r:"plain"}function Cs(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 Ss(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 As(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 tr(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 ll(e,n="esm",r){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let o=r?{...r,hooks:rl(r.hooks)}:void 0;return n==="esm"?dl(t,o):n==="script-installer"?pl(t):n==="script-advanced"?ml(t,o):n==="react-component"?cl(t,o):n==="react-advanced"?ul(t,o):gl(t,o)}function dl(e,n){let r=n==null?void 0:n.hooks,t=bs(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(...Cs(e," ")),s.push(...xs(e," ",r)),s.push(...Ss(e," ")),s.push(...As(e," ")),s.push(...tr(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 cl(e,n){let r=n==null?void 0:n.hooks,t=bs(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(...Cs(e," ")),s.push(...xs(e," ",r)),s.push(...Ss(e," ")),s.push(...As(e," ")),s.push(...tr(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 ul(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(...Cs(e," ")),t.push(...xs(e," ",r)),t.push(...Ss(e," ")),t.push(...As(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(${ol}),`)),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(` ${zi}`),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(` ${zi}`),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(` ${Ji}`),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(` ${Ji}`),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 Yi(e){var o;let n=bs(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(([v,c])=>{v!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(g[v]=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 pl(e){let n=Yi(e),r=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${kn}/dist/install.global.js" data-config='${r}'></script>`}function gl(e,n){let r=n==null?void 0:n.hooks,t=bs(e),o=t!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${kn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${kn}/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(...Cs(e," ")),s.push(...xs(e," ",r)),s.push(...Ss(e," ")),s.push(...As(e," ")),s.push(...tr(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
- `)}function ml(e,n){let r=n==null?void 0:n.hooks,t=Yi(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
132
+ }`;function ll(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 bs(e){var n,r;return(r=(n=e.parserType)!=null?n:ll(e.streamParser))!=null?r:"plain"}function Cs(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 Ss(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 As(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 tr(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 dl(e,n="esm",r){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let o=r?{...r,hooks:ol(r.hooks)}:void 0;return n==="esm"?cl(t,o):n==="script-installer"?gl(t):n==="script-advanced"?hl(t,o):n==="react-component"?ul(t,o):n==="react-advanced"?pl(t,o):ml(t,o)}function cl(e,n){let r=n==null?void 0:n.hooks,t=bs(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(...Cs(e," ")),s.push(...xs(e," ",r)),s.push(...Ss(e," ")),s.push(...As(e," ")),s.push(...tr(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 ul(e,n){let r=n==null?void 0:n.hooks,t=bs(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(...Cs(e," ")),s.push(...xs(e," ",r)),s.push(...Ss(e," ")),s.push(...As(e," ")),s.push(...tr(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 pl(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(...Cs(e," ")),t.push(...xs(e," ",r)),t.push(...Ss(e," ")),t.push(...As(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(${il}),`)),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(` ${Ui}`),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(` ${Ui}`),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(` ${Ki}`),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(` ${Ki}`),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 Vi(e){var o;let n=bs(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 gl(e){let n=Vi(e),r=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ln}/dist/install.global.js" data-config='${r}'></script>`}function ml(e,n){let r=n==null?void 0:n.hooks,t=bs(e),o=t!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ln}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ln}/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(...Cs(e," ")),s.push(...xs(e," ",r)),s.push(...Ss(e," ")),s.push(...As(e," ")),s.push(...tr(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
+ `)}function hl(e,n){let r=n==null?void 0:n.hooks,t=Vi(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@${kn}/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(${il});`),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(` ${Ui}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Ui}`),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(` ${Ki}`),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(` ${Ki}`),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 Lc=_i;export{yn as AgentWidgetClient,Un as AgentWidgetSession,Cn as AttachmentManager,Fi as DEFAULT_DARK_THEME,Ri as DEFAULT_LIGHT_THEME,nt as DEFAULT_WIDGET_CONFIG,kn as VERSION,xn as attachHeaderToContainer,Yn as buildComposer,Ci as buildDefaultHeader,Si as buildExpandedHeader,an as buildHeader,Kn as buildHeaderWithLayout,xi as buildMinimalHeader,Qn as componentRegistry,ys as createActionManager,Zs as createAgentExperience,La as createBubbleWithLayout,Xs as createCSATFeedback,Xa as createComponentMiddleware,Js as createComponentStreamParser,ea as createDirectivePostprocessor,oa as createFlexibleJsonStreamParser,ha as createImagePart,Is as createJsonStreamParser,zs as createLocalStorageAdapter,cs as createMarkdownProcessor,us as createMarkdownProcessorFromConfig,ki as createMessageActions,Gs as createNPSFeedback,ks as createPlainTextParser,Ws as createRegexJsonParser,Vn as createStandardBubble,Bs as createTextPart,Sn as createTypingIndicator,Ps as createXmlParser,Lc as default,Mn as defaultActionHandlers,vs as defaultJsonActionParser,ta as directivePostprocessor,Ms as escapeHtml,Vs as extractComponentDirectiveFromMessage,fa as fileToImagePart,bn as generateAssistantMessageId,ll as generateCodeSnippet,la as generateMessageId,zn as generateUserMessageId,pa as getDisplayText,Ai as getHeaderLayout,ma as getImageParts,Ys as hasComponentDirective,ga as hasImages,Fs as headerLayouts,_i as initAgentWidget,Va as isComponentDirectiveType,ii as markdownPostprocessor,_s as mergeWithDefaults,ua as normalizeContent,ws as pluginRegistry,Ks as renderComponentDirective,Li as renderLoadingIndicatorWithFallback,wa as validateImageFile};
138
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ln}/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(${al});`),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(` ${Ji}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Ji}`),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(` ${Yi}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Yi}`),s.push(" ];")),s.push(""),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 Lc=qi;export{yn as AgentWidgetClient,Un as AgentWidgetSession,Cn as AttachmentManager,$i as DEFAULT_DARK_THEME,Fi as DEFAULT_LIGHT_THEME,ot as DEFAULT_WIDGET_CONFIG,Ln as VERSION,xn as attachHeaderToContainer,Yn as buildComposer,xi as buildDefaultHeader,Ai as buildExpandedHeader,on as buildHeader,Kn as buildHeaderWithLayout,Si as buildMinimalHeader,Qn as componentRegistry,ys as createActionManager,Zs as createAgentExperience,La as createBubbleWithLayout,Xs as createCSATFeedback,Ga as createComponentMiddleware,Js as createComponentStreamParser,ta as createDirectivePostprocessor,ia as createFlexibleJsonStreamParser,fa as createImagePart,Is as createJsonStreamParser,zs as createLocalStorageAdapter,cs as createMarkdownProcessor,us as createMarkdownProcessorFromConfig,Wi as createMessageActions,Gs as createNPSFeedback,Ls as createPlainTextParser,Ws as createRegexJsonParser,Vn as createStandardBubble,Bs as createTextPart,Sn as createTypingIndicator,Ps as createXmlParser,Lc as default,Mn as defaultActionHandlers,vs as defaultJsonActionParser,na as directivePostprocessor,Ms as escapeHtml,Vs as extractComponentDirectiveFromMessage,wa as fileToImagePart,bn as generateAssistantMessageId,dl as generateCodeSnippet,da as generateMessageId,zn as generateUserMessageId,ga as getDisplayText,Ei as getHeaderLayout,ha as getImageParts,Ys as hasComponentDirective,ma as hasImages,Fs as headerLayouts,qi as initAgentWidget,Xa as isComponentDirectiveType,ai as markdownPostprocessor,_s as mergeWithDefaults,pa as normalizeContent,ws as pluginRegistry,Ks as renderComponentDirective,Li as renderLoadingIndicatorWithFallback,va as validateImageFile};
140
140
  //# sourceMappingURL=index.js.map