@runtypelabs/persona 1.47.0 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import{Marked as ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=n==null?void 0:n.markedOptions,r=new ya({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=ba(n==null?void 0:n.renderer);return e&&r.use({renderer:e}),i=>r.parse(i)},js=n=>n?Ds({markedOptions:n.options,renderer:n.renderer}):Ds(),Ca=Ds(),Ii=n=>Ca(n),cr=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Li=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ki=n=>`%%FORM_PLACEHOLDER_${n}%%`,Wi=(n,t)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=ki(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=ki(t.length);return t.push({token:s,type:o}),s}),r},xa=n=>{let t=js(n);return r=>{let e=[],o=Wi(r,e),s=t(o);return e.forEach(({token:i,type:a})=>{let u=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${Li(a)}"></div>`;s=s.replace(u,v)}),s}},Sa=n=>{let t=[],r=Wi(n,t),e=Ii(r);return t.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="tvw-form-directive" data-tv-form="${Li(s)}"></div>`;e=e.replace(i,u)}),e};import{parse as Pi,STR as Ri,OBJ as Hi}from"partial-json";var _s=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fs=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},Aa=n=>{var i,a;let t=(i=n.completedAt)!=null?i:Date.now(),r=(a=n.startedAt)!=null?a:t,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Bi=n=>n.status==="complete"?Aa(n):n.status==="pending"?"Waiting":"",Ea=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.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 Fi=n=>n.status==="complete"?Ea(n):"Using tool...",Ta=()=>{let n=null,t=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1
+ import{Marked as Ta}from"marked";var Ma=n=>{if(n)return n},Ds=n=>{var o,s;let t=n==null?void 0:n.markedOptions,r=new Ta({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=Ma(n==null?void 0:n.renderer);return e&&r.use({renderer:e}),i=>r.parse(i)},js=n=>n?Ds({markedOptions:n.options,renderer:n.renderer}):Ds(),ka=Ds(),Fi=n=>ka(n),ur=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),$i=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Bi=n=>`%%FORM_PLACEHOLDER_${n}%%`,Ni=(n,t)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Bi(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=Bi(t.length);return t.push({token:s,type:o}),s}),r},Ia=n=>{let t=js(n);return r=>{let e=[],o=Ni(r,e),s=t(o);return e.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${$i(a)}"></div>`;s=s.replace(d,v)}),s}},La=n=>{let t=[],r=Ni(n,t),e=Fi(r);return t.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${$i(s)}"></div>`;e=e.replace(i,d)}),e};import{parse as Oi,STR as Di,OBJ as ji}from"partial-json";var _s=n=>n.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),hs=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},Wa=n=>{var i,a;let t=(i=n.completedAt)!=null?i:Date.now(),r=(a=n.startedAt)!=null?a:t,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},_i=n=>n.status==="complete"?Wa(n):n.status==="pending"?"Waiting":"",Pa=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.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 Ui=n=>n.status==="complete"?Pa(n):"Using tool...",Ra=()=>{let n=null,t=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.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=e.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:()=>n,processChunk:async e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(n=s),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},Vs=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},dr=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},ur=()=>{var t;let n=Ta();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},pr=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=Pi(r,Ri|Hi);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?_s(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=_s(o.text)))}catch{}return t=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Ma=n=>{let t=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?_s(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?_s(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:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return t!==null?{text:t,raw:s}:null;try{let a=Pi(s,Ri|Hi),u=o(a);u!==null&&(t=u)}catch{}return r=s.length,{text:t||"",raw:s}},close:()=>{}}},gr=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var ka="https://api.runtype.com/v1/dispatch",mr="https://api.runtype.com",hr=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function Ia(n){switch(n){case"json":return pr;case"regex-json":return ur;case"xml":return gr;default:return dr}}var On=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=t.apiUrl)!=null?r:ka,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:Ia(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}setSSEEventCallback(t){this.onSSEEvent=t}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var e;let r=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mr;return t==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,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 e=await this.sessionInitPromise;return this.clientSession=e,(r=(t=this.config).onSessionInit)==null||r.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let t=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let a=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):e.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await e.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$/,""))||mr}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});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(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var o,s,i,a;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.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 c=await this.buildPayload(t.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,d={sessionId:u.sessionId,messages:t.messages.filter(hr).map(w=>{var b,y,S;return{id:w.id,role:w.role,content:(S=(y=(b=w.contentParts)!=null?b:w.llmContent)!=null?y:w.rawContent)!=null?S:w.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:e.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 y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}if(m.status===429){let y=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:y}),y}let b=new Error(w.error||"Failed to send message");throw r({type:"error",error:b}),b}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,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&r({type:"error",error:c}),c}}async dispatchProxy(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(t.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:e.signal},o)}catch(a){let u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.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:e.signal},o)}catch(a){let u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.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,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,e){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,e)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var i;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mr}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async buildAgentPayload(t){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(hr).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}}),e={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:t,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&&(e.context=o)}return e}async buildPayload(t){let e={messages:t.slice().filter(hr).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:t,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&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async handleCustomSSEEvent(t,r,e,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let a=()=>{if(e.current)return e.current;let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return e.current=u,o(u),u};if(i.text!==void 0){let u=a();u.content+=i.text,o(u)}return i.done&&(e.current&&(e.current.streaming=!1,o(e.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(t,r,e){var ue,Be,Et,dt,gt,Ht,Ne,ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt,pe,Ce,qe,Bt,Mt,Vt,F,Qe,N,G,re,$e,oe,Je,Ke,ce,D,Se,et,tt,Yt,Gt,Ye,Zt,mn,hn,sn,M,fn,an,bn,Xn,ln,cn,Ln,Wn,Ms,ks,Is,Gn,Pn,Ee,Zn,Qt,Ut,Ls,Ws,Qn,Cn,dn,Ps,Rs,Hs,sr,xn,Sn,nt,Rn,Hn,es,ts,ns,ss,Ft,qt,un,kt,rs,An,en,Bs,En,Tn,Bn,Fs,$s,pn,Xe,Ge,wn,os,is,rr,It,or,$t,as,ls,cs,ds,us;let o=t.getReader(),s=new TextDecoder,i="",a=Date.now(),u=0,c=()=>a+u++,v=V=>{let Ie=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,De=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,lt=V.tools?V.tools.map(mt=>({...mt,chunks:mt.chunks?[...mt.chunks]:void 0})):void 0;return{...V,reasoning:Ie,toolCall:De,tools:lt}},d=V=>{r({type:"message",message:v(V)})},m=null,w={current:null},b=new Map,y=new Map,S={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=V=>{if(V==null)return null;try{return String(V)}catch{return null}},J=V=>{var Ie,De,lt,mt,At;return k((At=(mt=(lt=(De=(Ie=V.stepId)!=null?Ie:V.step_id)!=null?De:V.step)!=null?lt:V.parentId)!=null?mt:V.flowStepId)!=null?At:V.flow_step_id)},E=V=>{var Ie,De,lt,mt,At,rt,h;return k((h=(rt=(At=(mt=(lt=(De=(Ie=V.callId)!=null?Ie:V.call_id)!=null?De:V.requestId)!=null?lt:V.request_id)!=null?mt:V.toolCallId)!=null?At:V.tool_call_id)!=null?rt:V.stepId)!=null?h:V.step_id)},I=()=>m||(m={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(m),m),T=(V,Ie)=>{S.lastId=Ie,V&&S.byStep.set(V,Ie)},B=(V,Ie)=>{var At;let De=(At=V.reasoningId)!=null?At:V.id,lt=J(V);if(De){let rt=String(De);return T(lt,rt),rt}if(lt){let rt=S.byStep.get(lt);if(rt)return S.lastId=rt,rt}if(S.lastId&&!Ie)return S.lastId;if(!Ie)return null;let mt=`reason-${c()}`;return T(lt,mt),mt},le=V=>{let Ie=b.get(V);if(Ie)return Ie;let De={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:V,status:"streaming",chunks:[]}};return b.set(V,De),d(De),De},z=(V,Ie)=>{x.lastId=Ie,V&&x.byCall.set(V,Ie)},U=(V,Ie)=>{var At;let De=(At=V.toolId)!=null?At:V.id,lt=E(V);if(De){let rt=String(De);return z(lt,rt),rt}if(lt){let rt=x.byCall.get(lt);if(rt)return x.lastId=rt,rt}if(x.lastId&&!Ie)return x.lastId;if(!Ie)return null;let mt=`tool-${c()}`;return z(lt,mt),mt},K=V=>{let Ie=y.get(V);if(Ie)return Ie;let De={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:V,status:"pending"}};return y.set(V,De),d(De),De},j=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let Ie=Number(V);if(!Number.isNaN(Ie)&&Number.isFinite(Ie))return Ie;let De=Date.parse(V);if(!Number.isNaN(De))return De}return Date.now()},ye=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},se=new Map,Y=new Map,_=null,O=new Map,Q=(ue=this.config.iterationDisplay)!=null?ue:"separate";for(;;){let{done:V,value:Ie}=await o.read();if(V)break;i+=s.decode(Ie,{stream:!0});let De=i.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>n,processChunk:async e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(n=s),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},Us=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},pr=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},gr=()=>{var t;let n=Ra();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},hr=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=Oi(r,Di|ji);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?_s(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=_s(o.text)))}catch{}return t=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Ha=n=>{let t=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?_s(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?_s(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:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return t!==null?{text:t,raw:s}:null;try{let a=Oi(s,Di|ji),d=o(a);d!==null&&(t=d)}catch{}return r=s.length,{text:t||"",raw:s}},close:()=>{}}},mr=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var Ba="https://api.runtype.com/v1/dispatch",fr="https://api.runtype.com",vr=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function Fa(n){switch(n){case"json":return hr;case"regex-json":return gr;case"xml":return mr;default:return pr}}var jn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=t.apiUrl)!=null?r:Ba,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:Fa(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}setSSEEventCallback(t){this.onSSEEvent=t}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var e;let r=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fr;return t==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,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 e=await this.sessionInitPromise;return this.clientSession=e,(r=(t=this.config).onSessionInit)==null||r.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let t=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let a=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):e.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await e.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$/,""))||fr}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});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(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var o,s,i,a;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.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 c=await this.buildPayload(t.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(vr).map(w=>{var C,y,A;return{id:w.id,role:w.role,content:(A=(y=(C=w.contentParts)!=null?C:w.llmContent)!=null?y:w.rawContent)!=null?A:w.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:e.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 y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}if(m.status===429){let y=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:y}),y}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,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&r({type:"error",error:c}),c}}async dispatchProxy(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(t.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:e.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:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.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:e.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:e.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,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,e){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,e)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var i;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fr}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async buildAgentPayload(t){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(vr).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}}),e={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:t,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&&(e.context=o)}return e}async buildPayload(t){let e={messages:t.slice().filter(vr).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:t,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&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async handleCustomSSEEvent(t,r,e,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let a=()=>{if(e.current)return e.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 e.current=d,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(e.current&&(e.current.streaming=!1,o(e.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(t,r,e){var fe,Fe,Mt,gt,ft,Ht,je,ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt,ve,Se,Je,Bt,It,qt,I,nt,O,Q,re,Ne,oe,Xe,Ge,pe,D,Ee,st,rt,Yt,Qt,Ze,en,mn,fn,rn,T,vn,ln,xn,Qn,cn,dn,Wn,Pn,Es,Ts,Ms,es,Rn,Ae,ts,Xt,Dt,ks,Is,ns,Sn,un,Ls,Ws,Ps,or,An,En,ot,Hn,Bn,ss,rs,os,is,Ft,Vt,pn,ke,as,Tn,tn,Rs,Fn,$n,Mn,wn,Hs,Bs,Gt,Nn,Fs,$s,gn,Qe,et,yn,ls,cs,ir,Lt,ar,$t;let o=t.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,c=()=>a+d++,v=q=>{let We=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,_e=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,dt=q.tools?q.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...q,reasoning:We,toolCall:_e,tools:dt}},p=q=>{r({type:"message",message:v(q)})},m=null,w={current:null},C=new Map,y=new Map,A={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},H=q=>{if(q==null)return null;try{return String(q)}catch{return null}},Y=q=>{var We,_e,dt,vt,Tt;return H((Tt=(vt=(dt=(_e=(We=q.stepId)!=null?We:q.step_id)!=null?_e:q.step)!=null?dt:q.parentId)!=null?vt:q.flowStepId)!=null?Tt:q.flow_step_id)},k=q=>{var We,_e,dt,vt,Tt,it,f;return H((f=(it=(Tt=(vt=(dt=(_e=(We=q.callId)!=null?We:q.call_id)!=null?_e:q.requestId)!=null?dt:q.request_id)!=null?vt:q.toolCallId)!=null?Tt:q.tool_call_id)!=null?it:q.stepId)!=null?f:q.step_id)},P=()=>m||(m={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(m),m),L=(q,We)=>{A.lastId=We,q&&A.byStep.set(q,We)},F=(q,We)=>{var Tt;let _e=(Tt=q.reasoningId)!=null?Tt:q.id,dt=Y(q);if(_e){let it=String(_e);return L(dt,it),it}if(dt){let it=A.byStep.get(dt);if(it)return A.lastId=it,it}if(A.lastId&&!We)return A.lastId;if(!We)return null;let vt=`reason-${c()}`;return L(dt,vt),vt},ue=q=>{let We=C.get(q);if(We)return We;let _e={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:q,status:"streaming",chunks:[]}};return C.set(q,_e),p(_e),_e},z=(q,We)=>{x.lastId=We,q&&x.byCall.set(q,We)},V=(q,We)=>{var Tt;let _e=(Tt=q.toolId)!=null?Tt:q.id,dt=k(q);if(_e){let it=String(_e);return z(dt,it),it}if(dt){let it=x.byCall.get(dt);if(it)return x.lastId=it,it}if(x.lastId&&!We)return x.lastId;if(!We)return null;let vt=`tool-${c()}`;return z(dt,vt),vt},X=q=>{let We=y.get(q);if(We)return We;let _e={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:q,status:"pending"}};return y.set(q,_e),p(_e),_e},_=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let We=Number(q);if(!Number.isNaN(We)&&Number.isFinite(We))return We;let _e=Date.parse(q);if(!Number.isNaN(_e))return _e}return Date.now()},Ce=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},se=new Map,G=new Map,U=null,N=new Map,ee=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(;;){let{done:q,value:We}=await o.read();if(q)break;i+=s.decode(We,{stream:!0});let _e=i.split(`
5
5
 
6
- `);i=(Be=De.pop())!=null?Be:"";for(let lt of De){let mt=lt.split(`
7
- `),At="message",rt="";for(let $ of mt)$.startsWith("event:")?At=$.replace("event:","").trim():$.startsWith("data:")&&(rt+=$.replace("data:","").trim());if(!rt)continue;let h;try{h=JSON.parse(rt)}catch($){r({type:"error",error:$ instanceof Error?$:new Error("Failed to parse chat stream payload")});continue}let We=At!=="message"?At:(Et=h.type)!=null?Et:"message";if((dt=this.onSSEEvent)==null||dt.call(this,We,h),this.parseSSEEvent){w.current=m;let $=await this.handleCustomSSEEvent(h,r,w,d,c);if(w.current&&!m&&(m=w.current),$)continue}if(We==="reason_start"){let $=(gt=B(h,!0))!=null?gt:`reason-${c()}`,C=le($);C.reasoning=(Ht=C.reasoning)!=null?Ht:{id:$,status:"streaming",chunks:[]},C.reasoning.startedAt=(ne=C.reasoning.startedAt)!=null?ne:j((Ne=h.startedAt)!=null?Ne:h.timestamp),C.reasoning.completedAt=void 0,C.reasoning.durationMs=void 0,C.streaming=!0,C.reasoning.status="streaming",d(C)}else if(We==="reason_delta"||We==="reason_chunk"){let $=(Re=(be=B(h,!1))!=null?be:B(h,!0))!=null?Re:`reason-${c()}`,C=le($);C.reasoning=(Fe=C.reasoning)!=null?Fe:{id:$,status:"streaming",chunks:[]},C.reasoning.startedAt=(Nt=C.reasoning.startedAt)!=null?Nt:j((Ue=h.startedAt)!=null?Ue:h.timestamp);let L=(at=(X=(de=h.reasoningText)!=null?de:h.text)!=null?X:h.delta)!=null?at:"";if(L&&h.hidden!==!0&&C.reasoning.chunks.push(String(L)),C.reasoning.status=h.done?"complete":"streaming",h.done){C.reasoning.completedAt=j((vt=h.completedAt)!=null?vt:h.timestamp);let ae=(Tt=C.reasoning.startedAt)!=null?Tt:Date.now();C.reasoning.durationMs=Math.max(0,((yt=C.reasoning.completedAt)!=null?yt:Date.now())-ae)}C.streaming=C.reasoning.status!=="complete",d(C)}else if(We==="reason_complete"){let $=(ee=(Kt=B(h,!1))!=null?Kt:B(h,!0))!=null?ee:`reason-${c()}`,C=b.get($);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=j((Le=h.completedAt)!=null?Le:h.timestamp);let ae=(bt=C.reasoning.startedAt)!=null?bt:Date.now();C.reasoning.durationMs=Math.max(0,((pe=C.reasoning.completedAt)!=null?pe:Date.now())-ae),C.streaming=!1,d(C)}let L=J(h);L&&S.byStep.delete(L)}else if(We==="tool_start"){let $=(Ce=U(h,!0))!=null?Ce:`tool-${c()}`,C=K($),L=(qe=C.toolCall)!=null?qe:{id:$,status:"pending"};L.name=(Bt=h.toolName)!=null?Bt:L.name,L.status="running",h.args!==void 0?L.args=h.args:h.parameters!==void 0&&(L.args=h.parameters),L.startedAt=(Vt=L.startedAt)!=null?Vt:j((Mt=h.startedAt)!=null?Mt:h.timestamp),L.completedAt=void 0,L.durationMs=void 0,C.toolCall=L,C.streaming=!0;let ae=h.agentContext;(ae||h.executionId)&&(C.agentMetadata={executionId:(F=ae==null?void 0:ae.executionId)!=null?F:h.executionId,iteration:(Qe=ae==null?void 0:ae.iteration)!=null?Qe:h.iteration}),d(C)}else if(We==="tool_chunk"||We==="tool_delta"){let $=(G=(N=U(h,!1))!=null?N:U(h,!0))!=null?G:`tool-${c()}`,C=K($),L=(re=C.toolCall)!=null?re:{id:$,status:"running"};L.startedAt=(oe=L.startedAt)!=null?oe:j(($e=h.startedAt)!=null?$e:h.timestamp);let ae=(ce=(Ke=(Je=h.text)!=null?Je:h.delta)!=null?Ke:h.message)!=null?ce:"";ae&&(L.chunks=(D=L.chunks)!=null?D:[],L.chunks.push(String(ae))),L.status="running",C.toolCall=L,C.streaming=!0;let Ae=h.agentContext;(Ae||h.executionId)&&(C.agentMetadata=(tt=C.agentMetadata)!=null?tt:{executionId:(Se=Ae==null?void 0:Ae.executionId)!=null?Se:h.executionId,iteration:(et=Ae==null?void 0:Ae.iteration)!=null?et:h.iteration}),d(C)}else if(We==="tool_complete"){let $=(Gt=(Yt=U(h,!1))!=null?Yt:U(h,!0))!=null?Gt:`tool-${c()}`,C=K($),L=(Ye=C.toolCall)!=null?Ye:{id:$,status:"running"};L.status="complete",h.result!==void 0&&(L.result=h.result),typeof h.duration=="number"&&(L.duration=h.duration),L.completedAt=j((Zt=h.completedAt)!=null?Zt:h.timestamp);let ae=(mn=h.duration)!=null?mn:h.executionTime;if(typeof ae=="number")L.durationMs=ae;else{let Lt=(hn=L.startedAt)!=null?hn:Date.now();L.durationMs=Math.max(0,((sn=L.completedAt)!=null?sn:Date.now())-Lt)}C.toolCall=L,C.streaming=!1;let Ae=h.agentContext;(Ae||h.executionId)&&(C.agentMetadata=(an=C.agentMetadata)!=null?an:{executionId:(M=Ae==null?void 0:Ae.executionId)!=null?M:h.executionId,iteration:(fn=Ae==null?void 0:Ae.iteration)!=null?fn:h.iteration}),d(C);let ze=E(h);ze&&x.byCall.delete(ze)}else if(We==="step_chunk"||We==="step_delta"){let $=h.stepType,C=h.executionType;if($==="tool"||C==="context")continue;let L=I(),ae=(cn=(ln=(Xn=(bn=h.text)!=null?bn:h.delta)!=null?Xn:h.content)!=null?ln:h.chunk)!=null?cn:"";if(ae){let ze=((Ln=Y.get(L.id))!=null?Ln:"")+ae;L.rawContent=ze,se.has(L.id)||se.set(L.id,this.createStreamParser());let Lt=se.get(L.id),ot=ze.trim().startsWith("{")||ze.trim().startsWith("[");if(ot&&Y.set(L.id,ze),Lt.__isPlainTextParser===!0){L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L);continue}let ht=Lt.processChunk(ze);if(ht instanceof Promise)ht.then(Oe=>{var ut;let _e=typeof Oe=="string"?Oe:(ut=Oe==null?void 0:Oe.text)!=null?ut:null;if(_e!==null&&_e.trim()!==""){let Ve=m;Ve&&Ve.id===L.id&&(Ve.content=_e,d(Ve))}else if(!ot&&!ze.trim().startsWith("<")){let Ve=m;Ve&&Ve.id===L.id&&(Ve.content+=ae,Y.delete(Ve.id),se.delete(Ve.id),Ve.rawContent=void 0,d(Ve))}}).catch(()=>{L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L)});else{let Oe=typeof ht=="string"?ht:(Wn=ht==null?void 0:ht.text)!=null?Wn:null;Oe!==null&&Oe.trim()!==""?(L.content=Oe,d(L)):!ot&&!ze.trim().startsWith("<")&&(L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L))}}if(h.isComplete){let Ae=(ks=(Ms=h.result)==null?void 0:Ms.response)!=null?ks:L.content;if(Ae){let ze=Y.get(L.id),Lt=ze!=null?ze:ye(Ae);L.rawContent=Lt;let ot=se.get(L.id),Ct=null,ht=!1;if(ot&&(Ct=ot.getExtractedText(),Ct===null&&(Ct=Vs(Lt)),Ct===null)){let Oe=ot.processChunk(Lt);Oe instanceof Promise?(ht=!0,Oe.then(_e=>{var Ve;let ut=typeof _e=="string"?_e:(Ve=_e==null?void 0:_e.text)!=null?Ve:null;if(ut!==null){let xt=m;xt&&xt.id===L.id&&(xt.content=ut,xt.streaming=!1,se.delete(xt.id),Y.delete(xt.id),d(xt))}})):Ct=typeof Oe=="string"?Oe:(Is=Oe==null?void 0:Oe.text)!=null?Is:null}if(!ht){Ct!==null&&Ct.trim()!==""?L.content=Ct:Y.has(L.id)||(L.content=ye(Ae));let Oe=se.get(L.id);if(Oe){let _e=(Gn=Oe.close)==null?void 0:Gn.call(Oe);_e instanceof Promise&&_e.catch(()=>{}),se.delete(L.id)}Y.delete(L.id),L.streaming=!1,d(L)}}}}else if(We==="step_complete"){let $=h.stepType,C=h.executionType;if($==="tool"||C==="context")continue;let L=(Pn=h.result)==null?void 0:Pn.response,ae=I();if(L!=null){let Ae=se.get(ae.id),ze=!1,Lt=!1;if(Ae){let ot=Ae.getExtractedText(),Ct=Y.get(ae.id),ht=Ct!=null?Ct:ye(L);if(ae.rawContent=ht,ot!==null&&ot.trim()!=="")ae.content=ot,ze=!0;else{let Oe=Vs(ht);if(Oe!==null)ae.content=Oe,ze=!0;else{let _e=Ae.processChunk(ht);if(_e instanceof Promise)Lt=!0,_e.then(ut=>{var xt;let Ve=typeof ut=="string"?ut:(xt=ut==null?void 0:ut.text)!=null?xt:null;if(Ve!==null&&Ve.trim()!==""){let Dt=m;Dt&&Dt.id===ae.id&&(Dt.content=Ve,Dt.streaming=!1,se.delete(Dt.id),Y.delete(Dt.id),d(Dt))}else{let Dt=Ae.getExtractedText(),Xt=m;Xt&&Xt.id===ae.id&&(Dt!==null&&Dt.trim()!==""?Xt.content=Dt:Y.has(Xt.id)||(Xt.content=ye(L)),Xt.streaming=!1,se.delete(Xt.id),Y.delete(Xt.id),d(Xt))}});else{let ut=typeof _e=="string"?_e:(Ee=_e==null?void 0:_e.text)!=null?Ee:null;if(ut!==null&&ut.trim()!=="")ae.content=ut,ze=!0;else{let Ve=Ae.getExtractedText();Ve!==null&&Ve.trim()!==""&&(ae.content=Ve,ze=!0)}}}}}if(!Lt){if(!ae.rawContent){let ot=Y.get(ae.id);ae.rawContent=ot!=null?ot:ye(L)}if(!ze&&!Y.has(ae.id)&&(ae.content=ye(L)),Ae){let ot=(Zn=Ae.close)==null?void 0:Zn.call(Ae);ot instanceof Promise&&ot.catch(()=>{})}se.delete(ae.id),Y.delete(ae.id),ae.streaming=!1,d(ae)}}else se.delete(ae.id),Y.delete(ae.id),ae.streaming=!1,d(ae)}else if(We==="flow_complete"){let $=(Qt=h.result)==null?void 0:Qt.response;if($!=null){let C=I(),L=Y.get(C.id),ae=L!=null?L:ye($);C.rawContent=ae;let Ae=ye($),ze=se.get(C.id);if(ze){let Ct=Vs(ae);if(Ct!==null)Ae=Ct;else{let ht=ze.processChunk(ae);ht instanceof Promise&&ht.then(_e=>{var Ve;let ut=typeof _e=="string"?_e:(Ve=_e==null?void 0:_e.text)!=null?Ve:null;if(ut!==null){let xt=m;xt&&xt.id===C.id&&(xt.content=ut,xt.streaming=!1,d(xt))}});let Oe=ze.getExtractedText();Oe!==null&&(Ae=Oe)}}se.delete(C.id),Y.delete(C.id);let Lt=Ae!==C.content,ot=C.streaming!==!1;Lt&&(C.content=Ae),C.streaming=!1,(Lt||ot)&&d(C)}else if(m!==null){let C=m;se.delete(C.id),Y.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}r({type:"status",status:"idle"})}else if(We==="agent_start")_={executionId:h.executionId,agentId:(Ut=h.agentId)!=null?Ut:"virtual",agentName:(Ls=h.agentName)!=null?Ls:"",status:"running",currentIteration:0,maxIterations:(Ws=h.maxIterations)!=null?Ws:1,startedAt:j(h.startedAt)};else if(We==="agent_iteration_start"){if(_&&(_.currentIteration=h.iteration),Q==="separate"&&h.iteration>1){let $=m;$&&($.streaming=!1,d($),O.set(h.iteration-1,$),m=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(h.contentType==="text"){let $=I();$.content+=(Qn=h.delta)!=null?Qn:"",$.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:h.turnId,agentName:_==null?void 0:_.agentName},d($)}else if(h.contentType==="thinking"){let $=(Cn=h.turnId)!=null?Cn:`agent-think-${h.iteration}`,C=le($);C.reasoning=(dn=C.reasoning)!=null?dn:{id:$,status:"streaming",chunks:[]},C.reasoning.chunks.push((Ps=h.delta)!=null?Ps:""),C.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:h.turnId},d(C)}else if(h.contentType==="tool_input"){let $=(Rs=h.toolCallId)!=null?Rs:x.lastId;if($){let C=y.get($);C!=null&&C.toolCall&&(C.toolCall.chunks=(Hs=C.toolCall.chunks)!=null?Hs:[],C.toolCall.chunks.push((sr=h.delta)!=null?sr:""),d(C))}}}else if(We==="agent_turn_complete"){let $=h.turnId;if($){let C=b.get($);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=j(h.completedAt);let L=(xn=C.reasoning.startedAt)!=null?xn:Date.now();C.reasoning.durationMs=Math.max(0,((Sn=C.reasoning.completedAt)!=null?Sn:Date.now())-L),C.streaming=!1,d(C)}}}else if(We==="agent_tool_start"){let $=(nt=h.toolCallId)!=null?nt:`agent-tool-${c()}`;z(E(h),$);let C=K($),L=(Rn=C.toolCall)!=null?Rn:{id:$,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};L.name=(Hn=h.toolName)!=null?Hn:L.name,L.status="running",h.parameters!==void 0&&(L.args=h.parameters),L.startedAt=j((es=h.startedAt)!=null?es:h.timestamp),C.toolCall=L,C.streaming=!0,C.agentMetadata={executionId:h.executionId,iteration:h.iteration},d(C)}else if(We==="agent_tool_delta"){let $=(ts=h.toolCallId)!=null?ts:x.lastId;if($){let C=(ns=y.get($))!=null?ns:K($);C.toolCall&&(C.toolCall.chunks=(ss=C.toolCall.chunks)!=null?ss:[],C.toolCall.chunks.push((Ft=h.delta)!=null?Ft:""),C.toolCall.status="running",C.streaming=!0,d(C))}}else if(We==="agent_tool_complete"){let $=(qt=h.toolCallId)!=null?qt:x.lastId;if($){let C=(un=y.get($))!=null?un:K($);if(C.toolCall){C.toolCall.status="complete",h.result!==void 0&&(C.toolCall.result=h.result),typeof h.executionTime=="number"&&(C.toolCall.durationMs=h.executionTime),C.toolCall.completedAt=j((kt=h.completedAt)!=null?kt:h.timestamp),C.streaming=!1,d(C);let L=E(h);L&&x.byCall.delete(L)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let $=`agent-reflection-${h.executionId}-${h.iteration}`,C={id:$,role:"assistant",content:(rs=h.reflection)!=null?rs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(An=h.reflection)!=null?An:""]},agentMetadata:{executionId:h.executionId,iteration:h.iteration}};d(C)}else if(We==="agent_complete"){_&&(_.status=h.success?"complete":"error",_.completedAt=j(h.completedAt),_.stopReason=h.stopReason);let $=m;$&&($.streaming=!1,d($)),r({type:"status",status:"idle"})}else if(We==="agent_error"){let $=typeof h.error=="string"?h.error:(Bs=(en=h.error)==null?void 0:en.message)!=null?Bs:"Agent execution error";h.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):r({type:"error",error:new Error($)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let $=(En=h.approvalId)!=null?En:`approval-${c()}`,C={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Tn=_==null?void 0:_.agentId)!=null?Tn:"virtual",executionId:(Fs=(Bn=h.executionId)!=null?Bn:_==null?void 0:_.executionId)!=null?Fs:"",toolName:($s=h.toolName)!=null?$s:"",toolType:h.toolType,description:(Xe=h.description)!=null?Xe:`Execute ${(pn=h.toolName)!=null?pn:"tool"}`,parameters:h.parameters}};d(C)}else if(We==="step_await"&&h.awaitReason==="approval_required"){let $=(Ge=h.approvalId)!=null?Ge:`approval-${c()}`,C={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(wn=_==null?void 0:_.agentId)!=null?wn:"virtual",executionId:(is=(os=h.executionId)!=null?os:_==null?void 0:_.executionId)!=null?is:"",toolName:(rr=h.toolName)!=null?rr:"",toolType:h.toolType,description:(or=h.description)!=null?or:`Execute ${(It=h.toolName)!=null?It:"tool"}`,parameters:h.parameters}};d(C)}else if(We==="agent_approval_complete"){let $=h.approvalId;if($){let L={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:($t=h.decision)!=null?$t:"approved",agentId:(as=_==null?void 0:_.agentId)!=null?as:"virtual",executionId:(cs=(ls=h.executionId)!=null?ls:_==null?void 0:_.executionId)!=null?cs:"",toolName:(ds=h.toolName)!=null?ds:"",description:(us=h.description)!=null?us:"",resolvedAt:Date.now()}};d(L)}}else We==="error"&&h.error&&r({type:"error",error:h.error instanceof Error?h.error:new Error(String(h.error))})}}}}}};function La(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function ws(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function Nn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var Us="[Image]";function Wa(n){return typeof n=="string"?[{type:"text",text:n}]:n}function Pa(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ra(n){return typeof n=="string"?!1:n.some(t=>t.type==="image")}function Ha(n){return typeof n=="string"?[]:n.filter(t=>t.type==="image")}function fr(n){return{type:"text",text:n}}function Ba(n,t){return{type:"image",image:n,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function Fa(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;t({type:"image",image:o,mimeType:n.type,alt:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function $a(n,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(n.type)?n.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: ${t.join(", ")}`}}var $i=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Oa=["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"],vn=[...$i,...Oa];function Na(n){return $i.includes(n)||n.startsWith("image/")}function qs(n){return Na(n.type)}async function Oi(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;qs(n)?t({type:"image",image:o,mimeType:n.type,alt:n.name}):t({type:"file",data:o,mimeType:n.type,filename:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function Ni(n,t=vn,r=10*1024*1024){return t.includes(n.type)?n.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${t.join(", ")}`}}function Da(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function Di(n,t){let r=Da(t).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"}[n]||r||"FILE"}var vs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.analyserNode=null;this.mediaStream=null;this.silenceCheckInterval=null;this.silenceStart=null}async connect(){var t,r,e;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",i=(t=this.config)==null?void 0:t.host,a=(r=this.config)==null?void 0:r.agentId,u=(e=this.config)==null?void 0:e.clientToken;if(!a||!u)throw new Error("agentId and clientToken are required");if(!i)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${s}//${i}/ws/agents/${a}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let v=`${s}//${i}/ws/agents/${a}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((m,w)=>{if(!this.ws)return w(new Error("WebSocket not created"));let b=!1,y=x=>{b||(b=!0,clearTimeout(S),w(new Error(x)))},S=setTimeout(()=>y("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{b||(b=!0,clearTimeout(S),m())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+v+"."+d)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!b){let k=x.code!==1006?` (code ${x.code})`:"";y("WebSocket connection failed"+k+"."+d)}},{once:!0})})}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.onmessage=t=>{try{let r=JSON.parse(t.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(e=>e(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var r;switch(t.type){case"voice_response":(r=t.response.audio)!=null&&r.base64&&this.playAudio(t.response.audio).catch(e=>this.errorCallbacks.forEach(o=>o(e instanceof Error?e:new Error(String(e))))),this.resultCallbacks.forEach(e=>e({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),this.isProcessing=!1,this.statusCallbacks.forEach(e=>e("idle"));break;case"error":this.errorCallbacks.forEach(e=>e(new Error(t.error))),this.statusCallbacks.forEach(e=>e("error")),this.isProcessing=!1;break;case"pong":break}}async startListening(){var t,r,e,o;try{if(this.isProcessing)throw new Error("Already processing audio");let s=await navigator.mediaDevices.getUserMedia({audio:!0});this.mediaStream=s;let i=this.w;this.audioContext=new(i.AudioContext||i.webkitAudioContext);let a=this.audioContext,u=a.createMediaStreamSource(s);this.analyserNode=a.createAnalyser(),this.analyserNode.fftSize=2048,u.connect(this.analyserNode);let c=(r=(t=this.config)==null?void 0:t.pauseDuration)!=null?r:2e3,v=(o=(e=this.config)==null?void 0:e.silenceThreshold)!=null?o:.01;this.silenceStart=null;let d=new Float32Array(this.analyserNode.fftSize);this.silenceCheckInterval=setInterval(()=>{if(!this.analyserNode)return;this.analyserNode.getFloatTimeDomainData(d);let m=0;for(let b=0;b<d.length;b++)m+=d[b]*d[b];Math.sqrt(m/d.length)<v?this.silenceStart===null?this.silenceStart=Date.now():Date.now()-this.silenceStart>=c&&this.stopListening():this.silenceStart=null},100),this.mediaRecorder=new MediaRecorder(s),this.audioChunks=[],this.mediaRecorder.ondataavailable=m=>{m.data.size>0&&this.audioChunks.push(m.data)},this.mediaRecorder.onstop=async()=>{var m;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(y=>y("processing")),this.processingStartCallbacks.forEach(y=>y());let w=((m=this.mediaRecorder)==null?void 0:m.mimeType)||"audio/webm",b=new Blob(this.audioChunks,{type:w});await this.sendAudio(b),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(m=>m("listening"))}catch(s){throw this.errorCallbacks.forEach(i=>i(s)),this.statusCallbacks.forEach(i=>i("error")),s}}async stopListening(){this.silenceCheckInterval&&(clearInterval(this.silenceCheckInterval),this.silenceCheckInterval=null),this.analyserNode=null,this.silenceStart=null,this.mediaRecorder&&(this.mediaRecorder.stop(),this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.statusCallbacks.forEach(t=>t("idle"))}async sendAudio(t){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(e=>e(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(e=>e("error"));return}try{let e=await this.blobToBase64(t),o=this.getFormatFromMimeType(t.type);this.ws.send(JSON.stringify({type:"audio_input",audio:e,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId}))}catch(e){this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((r,e)=>{let o=new FileReader;o.onload=()=>{let i=o.result.split(",")[1];r(i)},o.onerror=e,o.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let r=atob(t.base64),e=new Uint8Array(r.length);for(let c=0;c<r.length;c++)e[c]=r.charCodeAt(c);let o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,i=new Blob([e],{type:s}),a=URL.createObjectURL(i),u=new Audio(a);u.onended=()=>URL.revokeObjectURL(a),await u.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(await this.stopListening(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var In=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var a;let s=Array.from(o.results).map(u=>u[0]).map(u=>u.transcript).join(""),i=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({text:s,confidence:i?.8:.5,provider:"browser"})),i&&!((a=this.config)!=null&&a.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Dn(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new vs(n.runtype);case"browser":if(!In.isSupported())throw new Error("Browser speech recognition not supported");return new In(n.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function wr(n){if((n==null?void 0:n.type)==="runtype"&&n.runtype)return Dn({type:"runtype",runtype:n.runtype});if(In.isSupported())return Dn({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function zs(n){try{return wr(n),!0}catch{return!1}}var ys=class n{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var r,e,o,s,i,a,u;t.type==="message"?(this.upsertMessage(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(e=t.message.agentMetadata.agentName)!=null?e:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=t.status==="error"?"error":"complete"))):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(u=(a=this.callbacks).onError)==null||u.call(a,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new On(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return zs((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}setupVoice(t){var r,e,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Dn(s);let i=(r=this.config.voiceRecognition)!=null?r:{},a=(e=i.processingText)!=null?e:"\u{1F3A4} Processing voice...",u=(o=i.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let v=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=v.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var v,d,m,w,b,y,S;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){if(this.pendingVoiceUserMessageId&&((v=c.transcript)!=null&&v.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((m=c.text)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(w=c.text)!=null&&w.trim()&&this.injectAssistantMessage({content:c.text.trim()}),(b=c.audio)!=null&&b.base64){let x=(S=this.pendingVoiceAssistantMessageId)!=null?S:(y=[...this.messages].reverse().find(k=>k.role==="assistant"))==null?void 0:y.id;x&&this.ttsSpokenMessageIds.add(x)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var v,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(v=this.callbacks).onVoiceStatusChanged)==null||d.call(v,c)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,e,o,s,i,a,u,c,v;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((e=t.runtype)==null?void 0:e.agentId)||"",clientToken:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(i=t.runtype)==null?void 0:i.voiceId,pauseDuration:(a=t.runtype)==null?void 0:a.pauseDuration,silenceThreshold:(u=t.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=t.browser)==null?void 0:c.language)||"en-US",continuous:(v=t.browser)==null?void 0:v.continuous}};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(t=this.callbacks).onError)==null||r.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new On(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:u,streaming:c=!1,voiceProcessing:v}=t,m={id:i!=null?i:r==="user"?ws():r==="assistant"?Nn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...v!==void 0&&{voiceProcessing:v}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let e of t){let{role:o,content:s,llmContent:i,contentParts:a,id:u,createdAt:c,sequence:v,streaming:d=!1}=e,w={id:u!=null?u:o==="user"?ws():o==="assistant"?Nn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:d,...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(t,r){var c,v,d,m,w;let e=t.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let o=ws(),s=Nn(),i={id:o,role:"user",content:e||Us,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 u=[...this.messages];try{await this.client.dispatch({messages:u,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(b){let y=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!y){let S={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(S)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(b instanceof Error?(d=(v=this.callbacks).onError)==null||d.call(v,b):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(b))))}}async continueConversation(){var o,s,i,a,u;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Nn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let e=[...this.messages];try{await this.client.dispatch({messages:e,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(c){let v={id:t,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,c instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,c):(u=(a=this.callbacks).onError)==null||u.call(a,new Error(String(c)))}}async connectStream(t,r){var o,s,i;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=!1;for(let a of this.messages)a.streaming&&(a.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(a){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(i=(s=this.callbacks).onError)==null||i.call(s,a instanceof Error?a:new Error(String(a)))}}async resolveApproval(t,r){var u,c,v;let e=`approval-${t.id}`,o={...t,status:r,resolvedAt:Date.now()},s={id:e,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let i=this.config.approval,a=i&&typeof i=="object"?i.onDecision:void 0;try{let d;if(a?d=await a({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):d=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),d){let m=null;if(d instanceof Response){if(!d.ok){let w=await d.json().catch(()=>null);throw new Error((u=w==null?void 0:w.error)!=null?u:`Approval request failed: ${d.status}`)}m=d.body}else d instanceof ReadableStream&&(m=d);m?await this.connectStream(m):r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(v=(c=this.callbacks).onError)==null||v.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let e=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!e)return;if(this.ttsSpokenMessageIds.has(e.id)){this.ttsSpokenMessageIds.delete(e.id);return}let o=e.content;o.trim()&&this.speak(o,t)}speak(t,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let e=window.speechSynthesis;e.cancel();let o=new SpeechSynthesisUtterance(t),s=e.getVoices();if(r.voice){let i=s.find(a=>a.name===r.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):n.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>e.speak(o),50)}static pickBestVoice(t){var e;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=t.find(i=>i.name===o);if(s)return s}return(e=t.find(o=>o.lang.startsWith("en")))!=null?e:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,e)=>{var u,c;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(u=r.sequence)!=null?u:0,a=(c=e.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(e.id)})}};var g=(n,t)=>{let r=document.createElement(n);return t&&(r.className=t),r};import*as ja from"lucide";var ie=(n,t=24,r="currentColor",e=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=ja[o];return s?_a(s,t,r,e):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function _a(n,t,r,e){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,v])=>{c!=="stroke"&&u.setAttribute(c,String(v))}),o.appendChild(u)}}}),o}var Js={allowedTypes:vn,maxFileSize:10*1024*1024,maxFiles:4};function Va(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ua(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-json":"file"}var jn=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Js.allowedTypes,maxFileSize:(e=t.maxFileSize)!=null?e:Js.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Js.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Js.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,e,o,s,i,a,u;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=Ni(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let d=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,d);continue}try{let d=await Oi(c),m=qs(c)?URL.createObjectURL(c):null,w={id:Va(),file:c,previewUrl:m,contentPart:d};this.attachments.push(w),this.renderPreview(w)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(a=this.config).onAttachmentsChange)==null||u.call(a,this.getAttachments())}}removeAttachment(t){var s,i,a;let r=this.attachments.findIndex(u=>u.id===t);if(r===-1)return;let e=this.attachments[r];e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var t,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=qs(t.file),e=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",t.id),e.style.width="48px",e.style.height="48px",r&&t.previewUrl){let i=g("img");i.src=t.previewUrl,i.alt=t.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",e.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Ua(t.file.type),u=ie(a,20,"var(--cw-muted, #6b7280)",1.5);u&&i.appendChild(u);let c=g("span");c.textContent=Di(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--cw-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),e.appendChild(i)}let o=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(t.id)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new n({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var vr=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},qa=n=>{var s,i,a;let t=(s=n==null?void 0:n.colorScheme)!=null?s:"light",r=(i=n==null?void 0:n.theme)!=null?i:{},e=(a=n==null?void 0:n.darkTheme)!=null?a:r;return t==="light"?r:t==="dark"||vr()==="dark"?e:r},ji=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{n(vr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(vr());r.addEventListener?(r.addEventListener("change",e),t.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),t.push(()=>r.removeListener(e)))}return()=>{t.forEach(r=>r())}},Ks=(n,t)=>{let r=qa(t);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${s}`,String(o))})};import{Idiomorph as za}from"idiomorph";var _i=(n,t,r={})=>{let{preserveTypingAnimation:e=!0}=r;za.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&e&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Rt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var nn={"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 bs=(n,t)=>{let r=g("button");r.type="button",r.innerHTML=`
6
+ `);i=(Fe=_e.pop())!=null?Fe:"";for(let dt of _e){let vt=dt.split(`
7
+ `),Tt="message",it="";for(let $ of vt)$.startsWith("event:")?Tt=$.replace("event:","").trim():$.startsWith("data:")&&(it+=$.replace("data:","").trim());if(!it)continue;let f;try{f=JSON.parse(it)}catch($){r({type:"error",error:$ instanceof Error?$:new Error("Failed to parse chat stream payload")});continue}let Re=Tt!=="message"?Tt:(Mt=f.type)!=null?Mt:"message";if((gt=this.onSSEEvent)==null||gt.call(this,Re,f),this.parseSSEEvent){w.current=m;let $=await this.handleCustomSSEEvent(f,r,w,p,c);if(w.current&&!m&&(m=w.current),$)continue}if(Re==="reason_start"){let $=(ft=F(f,!0))!=null?ft:`reason-${c()}`,b=ue($);b.reasoning=(Ht=b.reasoning)!=null?Ht:{id:$,status:"streaming",chunks:[]},b.reasoning.startedAt=(ne=b.reasoning.startedAt)!=null?ne:_((je=f.startedAt)!=null?je:f.timestamp),b.reasoning.completedAt=void 0,b.reasoning.durationMs=void 0,b.streaming=!0,b.reasoning.status="streaming",p(b)}else if(Re==="reason_delta"||Re==="reason_chunk"){let $=(He=(xe=F(f,!1))!=null?xe:F(f,!0))!=null?He:`reason-${c()}`,b=ue($);b.reasoning=($e=b.reasoning)!=null?$e:{id:$,status:"streaming",chunks:[]},b.reasoning.startedAt=(Ot=b.reasoning.startedAt)!=null?Ot:_((ze=f.startedAt)!=null?ze:f.timestamp);let R=(ct=(Z=(he=f.reasoningText)!=null?he:f.text)!=null?Z:f.delta)!=null?ct:"";if(R&&f.hidden!==!0&&b.reasoning.chunks.push(String(R)),b.reasoning.status=f.done?"complete":"streaming",f.done){b.reasoning.completedAt=_((bt=f.completedAt)!=null?bt:f.timestamp);let ae=(kt=b.reasoning.startedAt)!=null?kt:Date.now();b.reasoning.durationMs=Math.max(0,((Ct=b.reasoning.completedAt)!=null?Ct:Date.now())-ae)}b.streaming=b.reasoning.status!=="complete",p(b)}else if(Re==="reason_complete"){let $=(te=(Kt=F(f,!1))!=null?Kt:F(f,!0))!=null?te:`reason-${c()}`,b=C.get($);if(b!=null&&b.reasoning){b.reasoning.status="complete",b.reasoning.completedAt=_((Pe=f.completedAt)!=null?Pe:f.timestamp);let ae=(xt=b.reasoning.startedAt)!=null?xt:Date.now();b.reasoning.durationMs=Math.max(0,((ve=b.reasoning.completedAt)!=null?ve:Date.now())-ae),b.streaming=!1,p(b)}let R=Y(f);R&&A.byStep.delete(R)}else if(Re==="tool_start"){let $=(Se=V(f,!0))!=null?Se:`tool-${c()}`,b=X($),R=(Je=b.toolCall)!=null?Je:{id:$,status:"pending"};R.name=(Bt=f.toolName)!=null?Bt:R.name,R.status="running",f.args!==void 0?R.args=f.args:f.parameters!==void 0&&(R.args=f.parameters),R.startedAt=(qt=R.startedAt)!=null?qt:_((It=f.startedAt)!=null?It:f.timestamp),R.completedAt=void 0,R.durationMs=void 0,b.toolCall=R,b.streaming=!0;let ae=f.agentContext;(ae||f.executionId)&&(b.agentMetadata={executionId:(I=ae==null?void 0:ae.executionId)!=null?I:f.executionId,iteration:(nt=ae==null?void 0:ae.iteration)!=null?nt:f.iteration}),p(b)}else if(Re==="tool_chunk"||Re==="tool_delta"){let $=(Q=(O=V(f,!1))!=null?O:V(f,!0))!=null?Q:`tool-${c()}`,b=X($),R=(re=b.toolCall)!=null?re:{id:$,status:"running"};R.startedAt=(oe=R.startedAt)!=null?oe:_((Ne=f.startedAt)!=null?Ne:f.timestamp);let ae=(pe=(Ge=(Xe=f.text)!=null?Xe:f.delta)!=null?Ge:f.message)!=null?pe:"";ae&&(R.chunks=(D=R.chunks)!=null?D:[],R.chunks.push(String(ae))),R.status="running",b.toolCall=R,b.streaming=!0;let Te=f.agentContext;(Te||f.executionId)&&(b.agentMetadata=(rt=b.agentMetadata)!=null?rt:{executionId:(Ee=Te==null?void 0:Te.executionId)!=null?Ee:f.executionId,iteration:(st=Te==null?void 0:Te.iteration)!=null?st:f.iteration}),p(b)}else if(Re==="tool_complete"){let $=(Qt=(Yt=V(f,!1))!=null?Yt:V(f,!0))!=null?Qt:`tool-${c()}`,b=X($),R=(Ze=b.toolCall)!=null?Ze:{id:$,status:"running"};R.status="complete",f.result!==void 0&&(R.result=f.result),typeof f.duration=="number"&&(R.duration=f.duration),R.completedAt=_((en=f.completedAt)!=null?en:f.timestamp);let ae=(mn=f.duration)!=null?mn:f.executionTime;if(typeof ae=="number")R.durationMs=ae;else{let Wt=(fn=R.startedAt)!=null?fn:Date.now();R.durationMs=Math.max(0,((rn=R.completedAt)!=null?rn:Date.now())-Wt)}b.toolCall=R,b.streaming=!1;let Te=f.agentContext;(Te||f.executionId)&&(b.agentMetadata=(ln=b.agentMetadata)!=null?ln:{executionId:(T=Te==null?void 0:Te.executionId)!=null?T:f.executionId,iteration:(vn=Te==null?void 0:Te.iteration)!=null?vn:f.iteration}),p(b);let Ke=k(f);Ke&&x.byCall.delete(Ke)}else if(Re==="step_chunk"||Re==="step_delta"){let $=f.stepType,b=f.executionType;if($==="tool"||b==="context")continue;let R=P(),ae=(dn=(cn=(Qn=(xn=f.text)!=null?xn:f.delta)!=null?Qn:f.content)!=null?cn:f.chunk)!=null?dn:"";if(ae){let Ke=((Wn=G.get(R.id))!=null?Wn:"")+ae;R.rawContent=Ke,se.has(R.id)||se.set(R.id,this.createStreamParser());let Wt=se.get(R.id),at=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(at&&G.set(R.id,Ke),Wt.__isPlainTextParser===!0){R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R);continue}let wt=Wt.processChunk(Ke);if(wt instanceof Promise)wt.then(De=>{var ht;let qe=typeof De=="string"?De:(ht=De==null?void 0:De.text)!=null?ht:null;if(qe!==null&&qe.trim()!==""){let Ve=m;Ve&&Ve.id===R.id&&(Ve.content=qe,p(Ve))}else if(!at&&!Ke.trim().startsWith("<")){let Ve=m;Ve&&Ve.id===R.id&&(Ve.content+=ae,G.delete(Ve.id),se.delete(Ve.id),Ve.rawContent=void 0,p(Ve))}}).catch(()=>{R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R)});else{let De=typeof wt=="string"?wt:(Pn=wt==null?void 0:wt.text)!=null?Pn:null;De!==null&&De.trim()!==""?(R.content=De,p(R)):!at&&!Ke.trim().startsWith("<")&&(R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R))}}if(f.isComplete){let Te=(Ts=(Es=f.result)==null?void 0:Es.response)!=null?Ts:R.content;if(Te){let Ke=G.get(R.id),Wt=Ke!=null?Ke:Ce(Te);R.rawContent=Wt;let at=se.get(R.id),St=null,wt=!1;if(at&&(St=at.getExtractedText(),St===null&&(St=Us(Wt)),St===null)){let De=at.processChunk(Wt);De instanceof Promise?(wt=!0,De.then(qe=>{var Ve;let ht=typeof qe=="string"?qe:(Ve=qe==null?void 0:qe.text)!=null?Ve:null;if(ht!==null){let At=m;At&&At.id===R.id&&(At.content=ht,At.streaming=!1,se.delete(At.id),G.delete(At.id),p(At))}})):St=typeof De=="string"?De:(Ms=De==null?void 0:De.text)!=null?Ms:null}if(!wt){St!==null&&St.trim()!==""?R.content=St:G.has(R.id)||(R.content=Ce(Te));let De=se.get(R.id);if(De){let qe=(es=De.close)==null?void 0:es.call(De);qe instanceof Promise&&qe.catch(()=>{}),se.delete(R.id)}G.delete(R.id),R.streaming=!1,p(R)}}}}else if(Re==="step_complete"){let $=f.stepType,b=f.executionType;if($==="tool"||b==="context")continue;let R=(Rn=f.result)==null?void 0:Rn.response,ae=P();if(R!=null){let Te=se.get(ae.id),Ke=!1,Wt=!1;if(Te){let at=Te.getExtractedText(),St=G.get(ae.id),wt=St!=null?St:Ce(R);if(ae.rawContent=wt,at!==null&&at.trim()!=="")ae.content=at,Ke=!0;else{let De=Us(wt);if(De!==null)ae.content=De,Ke=!0;else{let qe=Te.processChunk(wt);if(qe instanceof Promise)Wt=!0,qe.then(ht=>{var At;let Ve=typeof ht=="string"?ht:(At=ht==null?void 0:ht.text)!=null?At:null;if(Ve!==null&&Ve.trim()!==""){let jt=m;jt&&jt.id===ae.id&&(jt.content=Ve,jt.streaming=!1,se.delete(jt.id),G.delete(jt.id),p(jt))}else{let jt=Te.getExtractedText(),Zt=m;Zt&&Zt.id===ae.id&&(jt!==null&&jt.trim()!==""?Zt.content=jt:G.has(Zt.id)||(Zt.content=Ce(R)),Zt.streaming=!1,se.delete(Zt.id),G.delete(Zt.id),p(Zt))}});else{let ht=typeof qe=="string"?qe:(Ae=qe==null?void 0:qe.text)!=null?Ae:null;if(ht!==null&&ht.trim()!=="")ae.content=ht,Ke=!0;else{let Ve=Te.getExtractedText();Ve!==null&&Ve.trim()!==""&&(ae.content=Ve,Ke=!0)}}}}}if(!Wt){if(!ae.rawContent){let at=G.get(ae.id);ae.rawContent=at!=null?at:Ce(R)}if(!Ke&&!G.has(ae.id)&&(ae.content=Ce(R)),Te){let at=(ts=Te.close)==null?void 0:ts.call(Te);at instanceof Promise&&at.catch(()=>{})}se.delete(ae.id),G.delete(ae.id),ae.streaming=!1,p(ae)}}else se.delete(ae.id),G.delete(ae.id),ae.streaming=!1,p(ae)}else if(Re==="flow_complete"){let $=(Xt=f.result)==null?void 0:Xt.response;if($!=null){let b=P(),R=G.get(b.id),ae=R!=null?R:Ce($);b.rawContent=ae;let Te=Ce($),Ke=se.get(b.id);if(Ke){let St=Us(ae);if(St!==null)Te=St;else{let wt=Ke.processChunk(ae);wt instanceof Promise&&wt.then(qe=>{var Ve;let ht=typeof qe=="string"?qe:(Ve=qe==null?void 0:qe.text)!=null?Ve:null;if(ht!==null){let At=m;At&&At.id===b.id&&(At.content=ht,At.streaming=!1,p(At))}});let De=Ke.getExtractedText();De!==null&&(Te=De)}}se.delete(b.id),G.delete(b.id);let Wt=Te!==b.content,at=b.streaming!==!1;Wt&&(b.content=Te),b.streaming=!1,(Wt||at)&&p(b)}else if(m!==null){let b=m;se.delete(b.id),G.delete(b.id),b.streaming!==!1&&(b.streaming=!1,p(b))}r({type:"status",status:"idle"})}else if(Re==="agent_start")U={executionId:f.executionId,agentId:(Dt=f.agentId)!=null?Dt:"virtual",agentName:(ks=f.agentName)!=null?ks:"",status:"running",currentIteration:0,maxIterations:(Is=f.maxIterations)!=null?Is:1,startedAt:_(f.startedAt)};else if(Re==="agent_iteration_start"){if(U&&(U.currentIteration=f.iteration),ee==="separate"&&f.iteration>1){let $=m;$&&($.streaming=!1,p($),N.set(f.iteration-1,$),m=null)}}else if(Re!=="agent_turn_start"){if(Re==="agent_turn_delta"){if(f.contentType==="text"){let $=P();$.content+=(ns=f.delta)!=null?ns:"",$.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId,agentName:U==null?void 0:U.agentName},p($)}else if(f.contentType==="thinking"){let $=(Sn=f.turnId)!=null?Sn:`agent-think-${f.iteration}`,b=ue($);b.reasoning=(un=b.reasoning)!=null?un:{id:$,status:"streaming",chunks:[]},b.reasoning.chunks.push((Ls=f.delta)!=null?Ls:""),b.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId},p(b)}else if(f.contentType==="tool_input"){let $=(Ws=f.toolCallId)!=null?Ws:x.lastId;if($){let b=y.get($);b!=null&&b.toolCall&&(b.toolCall.chunks=(Ps=b.toolCall.chunks)!=null?Ps:[],b.toolCall.chunks.push((or=f.delta)!=null?or:""),p(b))}}}else if(Re==="agent_turn_complete"){let $=f.turnId;if($){let b=C.get($);if(b!=null&&b.reasoning){b.reasoning.status="complete",b.reasoning.completedAt=_(f.completedAt);let R=(An=b.reasoning.startedAt)!=null?An:Date.now();b.reasoning.durationMs=Math.max(0,((En=b.reasoning.completedAt)!=null?En:Date.now())-R),b.streaming=!1,p(b)}}}else if(Re==="agent_tool_start"){let $=(ot=f.toolCallId)!=null?ot:`agent-tool-${c()}`;z(k(f),$);let b=X($),R=(Hn=b.toolCall)!=null?Hn:{id:$,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};R.name=(Bn=f.toolName)!=null?Bn:R.name,R.status="running",f.parameters!==void 0&&(R.args=f.parameters),R.startedAt=_((ss=f.startedAt)!=null?ss:f.timestamp),b.toolCall=R,b.streaming=!0,b.agentMetadata={executionId:f.executionId,iteration:f.iteration},p(b)}else if(Re==="agent_tool_delta"){let $=(rs=f.toolCallId)!=null?rs:x.lastId;if($){let b=(os=y.get($))!=null?os:X($);b.toolCall&&(b.toolCall.chunks=(is=b.toolCall.chunks)!=null?is:[],b.toolCall.chunks.push((Ft=f.delta)!=null?Ft:""),b.toolCall.status="running",b.streaming=!0,p(b))}}else if(Re==="agent_tool_complete"){let $=(Vt=f.toolCallId)!=null?Vt:x.lastId;if($){let b=(pn=y.get($))!=null?pn:X($);if(b.toolCall){b.toolCall.status="complete",f.result!==void 0&&(b.toolCall.result=f.result),typeof f.executionTime=="number"&&(b.toolCall.durationMs=f.executionTime),b.toolCall.completedAt=_((ke=f.completedAt)!=null?ke:f.timestamp),b.streaming=!1,p(b);let R=k(f);R&&x.byCall.delete(R)}}}else if(Re!=="agent_iteration_complete"){if(Re==="agent_reflection"||Re==="agent_reflect"){let $=`agent-reflection-${f.executionId}-${f.iteration}`,b={id:$,role:"assistant",content:(as=f.reflection)!=null?as:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(Tn=f.reflection)!=null?Tn:""]},agentMetadata:{executionId:f.executionId,iteration:f.iteration}};p(b)}else if(Re==="agent_complete"){U&&(U.status=f.success?"complete":"error",U.completedAt=_(f.completedAt),U.stopReason=f.stopReason);let $=m;$&&($.streaming=!1,p($)),r({type:"status",status:"idle"})}else if(Re==="agent_error"){let $=typeof f.error=="string"?f.error:(Rs=(tn=f.error)==null?void 0:tn.message)!=null?Rs:"Agent execution error";f.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):r({type:"error",error:new Error($)})}else if(Re!=="agent_ping")if(Re==="agent_approval_start"){let $=(Fn=f.approvalId)!=null?Fn:`approval-${c()}`,b={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:($n=U==null?void 0:U.agentId)!=null?$n:"virtual",executionId:(wn=(Mn=f.executionId)!=null?Mn:U==null?void 0:U.executionId)!=null?wn:"",toolName:(Hs=f.toolName)!=null?Hs:"",toolType:f.toolType,description:(Gt=f.description)!=null?Gt:`Execute ${(Bs=f.toolName)!=null?Bs:"tool"}`,parameters:f.parameters}};p(b)}else if(Re==="step_await"&&f.awaitReason==="approval_required"){let $=(Nn=f.approvalId)!=null?Nn:`approval-${c()}`,b={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Fs=U==null?void 0:U.agentId)!=null?Fs:"virtual",executionId:(gn=($s=f.executionId)!=null?$s:U==null?void 0:U.executionId)!=null?gn:"",toolName:(Qe=f.toolName)!=null?Qe:"",toolType:f.toolType,description:(yn=f.description)!=null?yn:`Execute ${(et=f.toolName)!=null?et:"tool"}`,parameters:f.parameters}};p(b)}else if(Re==="agent_approval_complete"){let $=f.approvalId;if($){let R={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(ls=f.decision)!=null?ls:"approved",agentId:(cs=U==null?void 0:U.agentId)!=null?cs:"virtual",executionId:(Lt=(ir=f.executionId)!=null?ir:U==null?void 0:U.executionId)!=null?Lt:"",toolName:(ar=f.toolName)!=null?ar:"",description:($t=f.description)!=null?$t:"",resolvedAt:Date.now()}};p(R)}}else Re==="error"&&f.error&&r({type:"error",error:f.error instanceof Error?f.error:new Error(String(f.error))})}}}}}};function $a(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function ms(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function _n(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var qs="[Image]";function Na(n){return typeof n=="string"?[{type:"text",text:n}]:n}function Oa(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}function Da(n){return typeof n=="string"?!1:n.some(t=>t.type==="image")}function ja(n){return typeof n=="string"?[]:n.filter(t=>t.type==="image")}function wr(n){return{type:"text",text:n}}function _a(n,t){return{type:"image",image:n,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function Ua(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;t({type:"image",image:o,mimeType:n.type,alt:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function qa(n,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(n.type)?n.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: ${t.join(", ")}`}}var qi=["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"],bn=[...qi,...Va];function za(n){return qi.includes(n)||n.startsWith("image/")}function Vs(n){return za(n.type)}async function Vi(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;Vs(n)?t({type:"image",image:o,mimeType:n.type,alt:n.name}):t({type:"file",data:o,mimeType:n.type,filename:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function zi(n,t=bn,r=10*1024*1024){return t.includes(n.type)?n.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${t.join(", ")}`}}function Ja(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function Ji(n,t){let r=Ja(t).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"}[n]||r||"FILE"}var zs=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let e=r.AudioContext||r.webkitAudioContext;this.ctx=new e({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),r=d,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let e=this.ensureContext(),o=this.pcmToFloat32(r),s=e.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let i=e.createBufferSource();i.buffer=s,i.connect(e.destination);let a=e.currentTime;this.nextStartTime<a&&(this.nextStartTime=a),i.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(i),this.pendingCount++,this.playing=!0,i.onended=()=>{let d=this.activeSources.indexOf(i);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),e=new Float32Array(r),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<r;s++){let i=o.getInt16(s*2,!0);e[s]=i/32768}return e}};var Js=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,r,e,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(r),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let i=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(i);let a=0;for(let v=0;v<i.length;v++)a+=i[v]*i[v];let d=Math.sqrt(a/i.length);(e==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var fs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Js;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,r,e;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",i=(t=this.config)==null?void 0:t.host,a=(r=this.config)==null?void 0:r.agentId,d=(e=this.config)==null?void 0:e.clientToken;if(!a||!d)throw new Error("agentId and clientToken are required");if(!i)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${s}//${i}/ws/agents/${a}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let v=`${s}//${i}/ws/agents/${a}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((m,w)=>{if(!this.ws)return w(new Error("WebSocket not created"));let C=!1,y=x=>{C||(C=!0,clearTimeout(A),w(new Error(x)))},A=setTimeout(()=>y("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(A),m())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+v+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let H=x.code!==1006?` (code ${x.code})`:"";y("WebSocket connection failed"+H+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let r=JSON.parse(t.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(e=>e(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var r,e;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(r=t.response.audio)!=null&&r.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(e=t.response.audio)!=null&&e.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new zs(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(r=>r("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,r,e,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let i=this.audioContext,a=(r=(t=this.config)==null?void 0:t.pauseDuration)!=null?r:2e3,d=(o=(e=this.config)==null?void 0:e.silenceThreshold)!=null?o:.01;this.vad.start(i,this.mediaStream,"silence",{threshold:d,duration:a},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(m=>m("processing")),this.processingStartCallbacks.forEach(m=>m());let v=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:v});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(s){throw this.errorCallbacks.forEach(i=>i(s)),this.statusCallbacks.forEach(i=>i("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,i;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let r=this.audioContext,e=(i=(s=this.config)==null?void 0:s.silenceThreshold)!=null?i:.01;this.vad.start(r,this.mediaStream,"speech",{threshold:e,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(r=>r(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(e=>e(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(e=>e("error"));return}try{let e=await this.blobToBase64(t),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:e,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:s}))}catch(e){this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((r,e)=>{let o=new FileReader;o.onload=()=>{let i=o.result.split(",")[1];r(i)},o.onerror=e,o.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let r=atob(t.base64),e=new Uint8Array(r.length);for(let c=0;c<r.length;c++)e[c]=r.charCodeAt(c);let o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,i=new Blob([e],{type:s}),a=URL.createObjectURL(i),d=new Audio(a);this.currentAudio=d,this.currentAudioUrl=a,d.onended=()=>{URL.revokeObjectURL(a),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ln=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var a;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),i=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:i?.8:.5,provider:"browser"})),i&&!((a=this.config)!=null&&a.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Un(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new fs(n.runtype);case"browser":if(!Ln.isSupported())throw new Error("Browser speech recognition not supported");return new Ln(n.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function yr(n){if((n==null?void 0:n.type)==="runtype"&&n.runtype)return Un({type:"runtype",runtype:n.runtype});if(Ln.isSupported())return Un({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ks(n){try{return yr(n),!0}catch{return!1}}var vs=class n{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var r,e,o,s,i,a,d;t.type==="message"?(this.upsertMessage(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(e=t.message.agentMetadata.agentName)!=null?e:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=t.status==="error"?"error":"complete"))):t.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,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new jn(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ks((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,e;return(e=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?e:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var r,e,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Un(s);let i=(r=this.config.voiceRecognition)!=null?r:{},a=(e=i.processingText)!=null?e:"\u{1F3A4} Processing voice...",d=(o=i.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let v=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=v.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var v,p,m,w,C,y;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((v=c.transcript)!=null&&v.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((m=c.text)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(w=c.text)!=null&&w.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let A=(y=this.pendingVoiceAssistantMessageId)!=null?y:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;A&&this.ttsSpokenMessageIds.add(A)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var v,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(v=this.callbacks).onVoiceStatusChanged)==null||p.call(v,c)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,e,o,s,i,a,d,c,v;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((e=t.runtype)==null?void 0:e.agentId)||"",clientToken:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(i=t.runtype)==null?void 0:i.voiceId,pauseDuration:(a=t.runtype)==null?void 0:a.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=t.browser)==null?void 0:c.language)||"en-US",continuous:(v=t.browser)==null?void 0:v.continuous}};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(t=this.callbacks).onError)==null||r.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new jn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:c=!1,voiceProcessing:v}=t,m={id:i!=null?i:r==="user"?ms():r==="assistant"?_n():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...v!==void 0&&{voiceProcessing:v}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let e of t){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:c,sequence:v,streaming:p=!1}=e,w={id:d!=null?d:o==="user"?ms():o==="assistant"?_n():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:p,...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(t,r){var c,v,p,m,w;let e=t.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let o=ms(),s=_n(),i={id:o,role:"user",content:e||qs,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 y=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!y){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,y||(C instanceof Error?(p=(v=this.callbacks).onError)==null||p.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 t=_n();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let e=[...this.messages];try{await this.client.dispatch({messages:e,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(c){let v={id:t,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,c instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,c):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(c)))}}async connectStream(t,r){var o,s,i;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=!1;for(let a of this.messages)a.streaming&&(a.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(a){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(i=(s=this.callbacks).onError)==null||i.call(s,a instanceof Error?a:new Error(String(a)))}}async resolveApproval(t,r){var d,c,v;let e=`approval-${t.id}`,o={...t,status:r,resolvedAt:Date.now()},s={id:e,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let i=this.config.approval,a=i&&typeof i=="object"?i.onDecision:void 0;try{let p;if(a?p=await a({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),p){let m=null;if(p instanceof Response){if(!p.ok){let w=await p.json().catch(()=>null);throw new Error((d=w==null?void 0:w.error)!=null?d:`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m):r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(v=(c=this.callbacks).onError)==null||v.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let e=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!e)return;if(this.ttsSpokenMessageIds.has(e.id)){this.ttsSpokenMessageIds.delete(e.id);return}let o=e.content;o.trim()&&this.speak(o,t)}speak(t,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let e=window.speechSynthesis;e.cancel();let o=new SpeechSynthesisUtterance(t),s=e.getVoices();if(r.voice){let i=s.find(a=>a.name===r.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):n.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>e.speak(o),50)}static pickBestVoice(t){var e;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=t.find(i=>i.name===o);if(s)return s}return(e=t.find(o=>o.lang.startsWith("en")))!=null?e:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,e)=>{var d,c;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(c=e.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(e.id)})}};var g=(n,t)=>{let r=document.createElement(n);return t&&(r.className=t),r};import*as Ka from"lucide";var ie=(n,t=24,r="currentColor",e=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ka[o];return s?Ya(s,t,r,e):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function Ya(n,t,r,e){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.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(([c,v])=>{c!=="stroke"&&d.setAttribute(c,String(v))}),o.appendChild(d)}}}),o}var Ys={allowedTypes:bn,maxFileSize:10*1024*1024,maxFiles:4};function Xa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ga(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-json":"file"}var qn=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ys.allowedTypes,maxFileSize:(e=t.maxFileSize)!=null?e:Ys.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ys.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ys.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,e,o,s,i,a,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=zi(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let p=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,p);continue}try{let p=await Vi(c),m=Vs(c)?URL.createObjectURL(c):null,w={id:Xa(),file:c,previewUrl:m,contentPart:p};this.attachments.push(w),this.renderPreview(w)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(a=this.config).onAttachmentsChange)==null||d.call(a,this.getAttachments())}}removeAttachment(t){var s,i,a;let r=this.attachments.findIndex(d=>d.id===t);if(r===-1)return;let e=this.attachments[r];e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var t,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=Vs(t.file),e=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",t.id),e.style.width="48px",e.style.height="48px",r&&t.previewUrl){let i=g("img");i.src=t.previewUrl,i.alt=t.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",e.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Ga(t.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let c=g("span");c.textContent=Ji(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--cw-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),e.appendChild(i)}let o=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(t.id)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new n({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var br=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Za=n=>{var s,i,a;let t=(s=n==null?void 0:n.colorScheme)!=null?s:"light",r=(i=n==null?void 0:n.theme)!=null?i:{},e=(a=n==null?void 0:n.darkTheme)!=null?a:r;return t==="light"?r:t==="dark"||br()==="dark"?e:r},Ki=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{n(br())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(br());r.addEventListener?(r.addEventListener("change",e),t.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),t.push(()=>r.removeListener(e)))}return()=>{t.forEach(r=>r())}},Xs=(n,t)=>{let r=Za(t);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${s}`,String(o))})};import{Idiomorph as Qa}from"idiomorph";var Yi=(n,t,r={})=>{let{preserveTypingAnimation:e=!0}=r;Qa.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&e&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Rt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var sn={"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 ws=(n,t)=>{let r=g("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,23 +12,23 @@ import{Marked as ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=
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",t);let e=s=>{var x,k,J,E,I,T,B,le,z,U,K,j;let i=(x=s.launcher)!=null?x:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(k=i.title)!=null?k:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(J=i.subtitle)!=null?J:"Get answers fast");let c=r.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let v=r.querySelector("[data-role='launcher-icon']");if(v)if(i.agentIconHidden)v.style.display="none";else{let ye=(E=i.agentIconSize)!=null?E:"40px";if(v.style.height=ye,v.style.width=ye,v.innerHTML="",i.agentIconName){let se=parseFloat(ye)||24,Y=ie(i.agentIconName,se*.6,"#ffffff",2);Y?(v.appendChild(Y),v.style.display=""):(v.textContent=(I=i.agentIconText)!=null?I:"\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 d=r.querySelector("[data-role='launcher-image']");if(d){let ye=(B=i.agentIconSize)!=null?B:"40px";d.style.height=ye,d.style.width=ye,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(d.src=i.iconUrl,d.style.display="block"):d.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(le=i.callToActionIconSize)!=null?le:"32px";m.style.height=ye,m.style.width=ye,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 se=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,se=(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 Y=parseFloat(ye)||24,_=Math.max(Y-se,8),O=ie(i.callToActionIconName,_,"currentColor",2);O?m.appendChild(O):m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(U=i.callToActionIconText)!=null?U:"\u2197"}let w=i.position&&nn[i.position]?nn[i.position]:nn["bottom-right"],b="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=`${b} ${w}`;let y="1px solid #e5e7eb",S="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(K=i.border)!=null?K:y,r.style.boxShadow=(j=i.shadow)!=null?j:S},o=()=>{r.removeEventListener("click",t),r.remove()};return n&&e(n),{element:r,update:e,destroy:o}};var yn=n=>{var U,K,j,ye,se,Y,_,O,Q,ue,Be,Et,dt,gt,Ht,Ne,ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt;let{config:t,showClose:r=!0}=n,e=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(U=t==null?void 0:t.launcher)!=null?U:{},s=(K=o.headerIconSize)!=null?K:"48px",i=(j=o.closeButtonSize)!=null?j:"32px",a=(ye=o.closeButtonPlacement)!=null?ye:"inline",u=(se=o.headerIconHidden)!=null?se:!1,c=o.headerIconName,v=g("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,!u)if(c){let pe=parseFloat(s)||24,Ce=ie(c,pe*.6,"#ffffff",1);Ce?v.replaceChildren(Ce):v.textContent=(_=(Y=t==null?void 0:t.launcher)==null?void 0:Y.agentIconText)!=null?_:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let pe=g("img");pe.src=t.launcher.iconUrl,pe.alt="",pe.className="tvw-rounded-xl tvw-object-cover",pe.style.height=s,pe.style.width=s,v.replaceChildren(pe)}else v.textContent=(ue=(Q=t==null?void 0:t.launcher)==null?void 0:Q.agentIconText)!=null?ue:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(Et=(Be=t==null?void 0:t.launcher)==null?void 0:Be.title)!=null?Et:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(gt=(dt=t==null?void 0:t.launcher)==null?void 0:dt.subtitle)!=null?gt:"Here to help you get answers fast",d.append(m,w),u?e.append(d):e.append(v,d);let b=(Ht=o.clearChat)!=null?Ht:{},y=(Ne=b.enabled)!=null?Ne:!0,S=(ne=b.placement)!=null?ne:"inline",x=null,k=null;if(y){let pe=(be=b.size)!=null?be:"32px",Ce=(Re=b.iconName)!=null?Re:"refresh-cw",qe=(Fe=b.iconColor)!=null?Fe:"",Bt=(Ue=b.backgroundColor)!=null?Ue:"",Mt=(Nt=b.borderWidth)!=null?Nt:"",Vt=(de=b.borderColor)!=null?de:"",F=(X=b.borderRadius)!=null?X:"",Qe=(at=b.paddingX)!=null?at:"",N=(vt=b.paddingY)!=null?vt:"",G=(Tt=b.tooltipText)!=null?Tt:"Clear chat",re=(yt=b.showTooltip)!=null?yt:!0;k=g("div",S==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),S==="top-right"&&(k.style.right="48px"),x=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),x.style.height=pe,x.style.width=pe,x.type="button",x.setAttribute("aria-label",G);let $e=ie(Ce,"20px",qe||"",1);if($e&&x.appendChild($e),qe&&(x.style.color=qe,x.classList.remove("tvw-text-cw-muted")),Bt&&(x.style.backgroundColor=Bt,x.classList.remove("hover:tvw-bg-gray-100")),Mt||Vt){let oe=Mt||"0px",Je=Vt||"transparent";x.style.border=`${oe} solid ${Je}`,x.classList.remove("tvw-border-none")}if(F&&(x.style.borderRadius=F,x.classList.remove("tvw-rounded-full")),Qe?(x.style.paddingLeft=Qe,x.style.paddingRight=Qe):(x.style.paddingLeft="",x.style.paddingRight=""),N?(x.style.paddingTop=N,x.style.paddingBottom=N):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),re&&G&&x&&k){let oe=null,Je=()=>{if(oe||!x)return;oe=g("div","tvw-clear-chat-tooltip"),oe.textContent=G;let ce=g("div");ce.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(ce);let D=x.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${D.left+D.width/2}px`,oe.style.top=`${D.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},Ke=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};k.addEventListener("mouseenter",Je),k.addEventListener("mouseleave",Ke),x.addEventListener("focus",Je),x.addEventListener("blur",Ke),k._cleanupTooltip=()=>{Ke(),k&&(k.removeEventListener("mouseenter",Je),k.removeEventListener("mouseleave",Ke)),x&&(x.removeEventListener("focus",Je),x.removeEventListener("blur",Ke))}}S==="inline"&&e.appendChild(k)}let J=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":y&&S==="inline"?"":"tvw-ml-auto"),E=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");E.style.height=i,E.style.width=i,E.type="button";let I=(Kt=o.closeButtonTooltipText)!=null?Kt:"Close chat",T=(ee=o.closeButtonShowTooltip)!=null?ee:!0;E.setAttribute("aria-label",I),E.style.display=r?"":"none";let B=(Le=o.closeButtonIconName)!=null?Le:"x",le=(bt=o.closeButtonIconText)!=null?bt:"\xD7",z=ie(B,"20px",o.closeButtonColor||"",1);if(z?E.appendChild(z):E.textContent=le,o.closeButtonColor?(E.style.color=o.closeButtonColor,E.classList.remove("tvw-text-cw-muted")):(E.style.color="",E.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(E.style.backgroundColor=o.closeButtonBackgroundColor,E.classList.remove("hover:tvw-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let pe=o.closeButtonBorderWidth||"0px",Ce=o.closeButtonBorderColor||"transparent";E.style.border=`${pe} solid ${Ce}`,E.classList.remove("tvw-border-none")}else E.style.border="",E.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(E.style.borderRadius=o.closeButtonBorderRadius,E.classList.remove("tvw-rounded-full")):(E.style.borderRadius="",E.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(E.style.paddingLeft=o.closeButtonPaddingX,E.style.paddingRight=o.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),o.closeButtonPaddingY?(E.style.paddingTop=o.closeButtonPaddingY,E.style.paddingBottom=o.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom=""),J.appendChild(E),T&&I){let pe=null,Ce=()=>{if(pe)return;pe=g("div","tvw-clear-chat-tooltip"),pe.textContent=I;let Bt=g("div");Bt.className="tvw-clear-chat-tooltip-arrow",pe.appendChild(Bt);let Mt=E.getBoundingClientRect();pe.style.position="fixed",pe.style.left=`${Mt.left+Mt.width/2}px`,pe.style.top=`${Mt.top-8}px`,pe.style.transform="translate(-50%, -100%)",document.body.appendChild(pe)},qe=()=>{pe&&pe.parentNode&&(pe.parentNode.removeChild(pe),pe=null)};J.addEventListener("mouseenter",Ce),J.addEventListener("mouseleave",qe),E.addEventListener("focus",Ce),E.addEventListener("blur",qe),J._cleanupTooltip=()=>{qe(),J.removeEventListener("mouseenter",Ce),J.removeEventListener("mouseleave",qe),E.removeEventListener("focus",Ce),E.removeEventListener("blur",qe)}}return a!=="top-right"&&e.appendChild(J),{header:e,iconHolder:v,headerTitle:m,headerSubtitle:w,closeButton:E,closeButtonWrapper:J,clearChatButton:x,clearChatButtonWrapper:k}},_n=(n,t,r)=>{var i,a,u,c;let e=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=e.closeButtonPlacement)!=null?a:"inline",s=(c=(u=e.clearChat)==null?void 0:u.placement)!=null?c:"inline";n.appendChild(t.header),o==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var Vi=n=>yn({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Ui=n=>{var b,y,S,x;let{config:t,showClose:r=!0,onClose:e}=n,o=(b=t==null?void 0:t.launcher)!=null?b:{},s=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=g("span","tvw-text-base tvw-font-semibold");i.textContent=(y=o.title)!=null?y:"Chat Assistant",s.appendChild(i);let a=(S=o.closeButtonSize)!=null?S:"32px",u=g("div",""),c=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=a,c.style.width=a,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=r?"":"none";let v=(x=o.closeButtonIconName)!=null?x:"x",d=ie(v,"20px",o.closeButtonColor||"",2);d?c.appendChild(d):c.textContent="\xD7",e&&c.addEventListener("click",e),u.appendChild(c),s.appendChild(u);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},qi=n=>{var E,I,T,B,le,z,U,K;let{config:t,showClose:r=!0,onClose:e,onClearChat:o}=n,s=(E=t==null?void 0:t.launcher)!=null?E:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),u=(I=s.headerIconSize)!=null?I:"56px",c=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=u,c.style.width=u;let v=s.headerIconName;if(v){let j=parseFloat(u)||24,ye=ie(v,j*.5,"#ffffff",2);ye?c.replaceChildren(ye):c.textContent=(T=s.agentIconText)!=null?T:"\u{1F4AC}"}else if(s.iconUrl){let j=g("img");j.src=s.iconUrl,j.alt="",j.className="tvw-rounded-xl tvw-object-cover",j.style.height=u,j.style.width=u,c.replaceChildren(j)}else c.textContent=(B=s.agentIconText)!=null?B:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(le=s.title)!=null?le:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(z=s.subtitle)!=null?z:"Here to help you get answers fast",d.append(m,w),a.append(c,d);let b=(U=s.closeButtonSize)!=null?U:"32px",y=g("div",""),S=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");S.style.height=b,S.style.width=b,S.type="button",S.setAttribute("aria-label","Close chat"),S.style.display=r?"":"none";let x=(K=s.closeButtonIconName)!=null?K:"x",k=ie(x,"20px",s.closeButtonColor||"",2);k?S.appendChild(k):S.textContent="\xD7",e&&S.addEventListener("click",e),y.appendChild(S),a.appendChild(y),i.appendChild(a);let J=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return J.textContent="Online and ready to help",i.appendChild(J),{header:i,iconHolder:c,headerTitle:m,headerSubtitle:w,closeButton:S,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},yr={default:Vi,minimal:Ui,expanded:qi},zi=n=>{var t;return(t=yr[n])!=null?t:yr.default},Cs=(n,t,r)=>{var i,a,u;if(t!=null&&t.render){let c=t.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),v=g("div");v.style.display="none";let d=g("span"),m=g("span"),w=g("button");w.style.display="none";let b=g("div");return b.style.display="none",{header:c,iconHolder:v,headerTitle:d,headerSubtitle:m,closeButton:w,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",s=zi(e)({config:n,showClose:(u=(a=t==null?void 0:t.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?u:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ja=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},xs=n=>{var ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt,pe,Ce,qe,Bt,Mt,Vt,F,Qe,N,G,re,$e,oe,Je,Ke;let{config:t}=n,r=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=g("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=g("textarea");s.placeholder=(be=(ne=t==null?void 0:t.copy)==null?void 0:ne.inputPlaceholder)!=null?be:"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=(Fe=(Re=t==null?void 0:t.theme)==null?void 0:Re.inputFontFamily)!=null?Fe:"sans-serif",a=(Nt=(Ue=t==null?void 0:t.theme)==null?void 0:Ue.inputFontWeight)!=null?Nt:"400";s.style.fontFamily=Ja(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let d=()=>{s.style.height="auto";let ce=Math.min(s.scrollHeight,v);s.style.height=`${ce}px`};s.addEventListener("input",d),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=(de=t==null?void 0:t.sendButton)!=null?de:{},w=(X=m.useIcon)!=null?X:!1,b=(at=m.iconText)!=null?at:"\u2191",y=m.iconName,S=(vt=m.tooltipText)!=null?vt:"Send message",x=(Tt=m.showTooltip)!=null?Tt:!1,k=(yt=m.size)!=null?yt:"40px",J=m.backgroundColor,E=m.textColor,I=g("div","tvw-send-button-wrapper"),T=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(T.type="submit",w){if(T.style.width=k,T.style.height=k,T.style.minWidth=k,T.style.minHeight=k,T.style.fontSize="18px",T.style.lineHeight="1",T.innerHTML="",y){let ce=parseFloat(k)||24,D=E&&typeof E=="string"&&E.trim()?E.trim():"currentColor",Se=ie(y,ce,D,2);Se?(T.appendChild(Se),T.style.color=D):(T.textContent=b,E?T.style.color=E:T.classList.add("tvw-text-white"))}else T.textContent=b,E?T.style.color=E:T.classList.add("tvw-text-white");J?T.style.backgroundColor=J:T.classList.add("tvw-bg-cw-primary")}else T.textContent=(ee=(Kt=t==null?void 0:t.copy)==null?void 0:Kt.sendButtonLabel)!=null?ee:"Send",E?T.style.color=E: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&&S){let ce=g("div","tvw-send-button-tooltip");ce.textContent=S,I.appendChild(ce)}I.appendChild(T);let B=(Le=t==null?void 0:t.voiceRecognition)!=null?Le:{},le=B.enabled===!0,z=null,U=null,K=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),j=((bt=B.provider)==null?void 0:bt.type)==="runtype";if(le&&(K||j)){U=g("div","tvw-send-button-wrapper"),z=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),z.type="button",z.setAttribute("aria-label","Start voice recognition");let ce=(pe=B.iconName)!=null?pe:"mic",D=(Ce=B.iconSize)!=null?Ce:k,Se=parseFloat(D)||24,et=(qe=B.backgroundColor)!=null?qe:J,tt=(Bt=B.iconColor)!=null?Bt:E;z.style.width=D,z.style.height=D,z.style.minWidth=D,z.style.minHeight=D,z.style.fontSize="18px",z.style.lineHeight="1";let Yt=tt||"currentColor",Gt=ie(ce,Se,Yt,1.5);Gt?(z.appendChild(Gt),z.style.color=Yt):(z.textContent="\u{1F3A4}",z.style.color=Yt),et?z.style.backgroundColor=et:z.classList.add("tvw-bg-cw-primary"),tt?z.style.color=tt:!tt&&!E&&z.classList.add("tvw-text-white"),B.borderWidth&&(z.style.borderWidth=B.borderWidth,z.style.borderStyle="solid"),B.borderColor&&(z.style.borderColor=B.borderColor),B.paddingX&&(z.style.paddingLeft=B.paddingX,z.style.paddingRight=B.paddingX),B.paddingY&&(z.style.paddingTop=B.paddingY,z.style.paddingBottom=B.paddingY),U.appendChild(z);let Ye=(Mt=B.tooltipText)!=null?Mt:"Start voice recognition";if(((Vt=B.showTooltip)!=null?Vt:!1)&&Ye){let mn=g("div","tvw-send-button-tooltip");mn.textContent=Ye,U.appendChild(mn)}}let se=(F=t==null?void 0:t.attachments)!=null?F:{},Y=se.enabled===!0,_=null,O=null,Q=null,ue=null;if(Y){ue=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ue.style.display="none",Q=g("input"),Q.type="file",Q.accept=((Qe=se.allowedTypes)!=null?Qe:vn).join(","),Q.multiple=((N=se.maxFiles)!=null?N:4)>1,Q.style.display="none",Q.setAttribute("aria-label","Attach files"),O=g("div","tvw-send-button-wrapper"),_=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),_.type="button",_.setAttribute("aria-label",(G=se.buttonTooltipText)!=null?G:"Attach file");let ce=(re=se.buttonIconName)!=null?re:"paperclip",D=k,Se=parseFloat(D)||40,et=Math.round(Se*.6);_.style.width=D,_.style.height=D,_.style.minWidth=D,_.style.minHeight=D,_.style.fontSize="18px",_.style.lineHeight="1",_.style.backgroundColor="transparent",_.style.color="var(--cw-primary, #111827)",_.style.border="none",_.style.borderRadius="6px",_.style.transition="background-color 0.15s ease",_.addEventListener("mouseenter",()=>{_.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),_.addEventListener("mouseleave",()=>{_.style.backgroundColor="transparent"});let tt=ie(ce,et,"currentColor",1.5);tt?_.appendChild(tt):_.textContent="\u{1F4CE}",_.addEventListener("click",Ye=>{Ye.preventDefault(),Q==null||Q.click()}),O.appendChild(_);let Yt=($e=se.buttonTooltipText)!=null?$e:"Attach file",Gt=g("div","tvw-send-button-tooltip");Gt.textContent=Yt,O.appendChild(Gt)}o.addEventListener("click",ce=>{ce.target!==T&&ce.target!==I&&ce.target!==z&&ce.target!==U&&ce.target!==_&&ce.target!==O&&s.focus()}),ue&&(ue.style.gap="8px",o.append(ue)),Q&&o.append(Q),o.append(s);let Be=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Et=g("div","tvw-flex tvw-items-center tvw-gap-2");O&&Et.append(O);let dt=g("div","tvw-flex tvw-items-center tvw-gap-1");U&&dt.append(U),dt.append(I),Be.append(Et,dt),o.append(Be);let gt=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Ht=(oe=t==null?void 0:t.statusIndicator)!=null?oe:{},Ne=(Je=Ht.visible)!=null?Je:!0;return gt.style.display=Ne?"":"none",gt.textContent=(Ke=Ht.idleText)!=null?Ke:"Online",r.append(e,o,gt),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:T,sendButtonWrapper:I,micButton:z,micButtonWrapper:U,statusText:gt,attachmentButton:_,attachmentButtonWrapper:O,attachmentInput:Q,attachmentPreviewsContainer:ue,actionsRow:Be,leftActions:Et,rightActions:dt}};var Ji=n=>{var u,c,v,d,m,w,b;if(!((c=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?c:!0)){let y=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),S=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(d=(v=n==null?void 0:n.launcher)==null?void 0:v.width)!=null?d:"100%";return y.style.width=x,S.style.width="100%",y.appendChild(S),{wrapper:y,panel:S}}let r=(m=n==null?void 0:n.launcher)!=null?m:{},e=r.position&&nn[r.position]?nn[r.position]:nn["bottom-right"],o=g("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(b=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?b:n==null?void 0:n.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}},Ki=(n,t=!0)=>{var w,b,y,S,x,k,J;let r=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),e=(w=n==null?void 0:n.layout)==null?void 0:w.header,o=((b=n==null?void 0:n.layout)==null?void 0:b.showHeader)!==!1,s=e?Cs(n,e,{showClose:t}):yn({config:n,showClose:t}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),u=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");u.textContent=(S=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeTitle)!=null?S:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(k=(x=n==null?void 0:n.copy)==null?void 0:x.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",a.append(u,c);let v=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let d=xs({config:n}),m=((J=n==null?void 0:n.layout)==null?void 0:J.showFooter)!==!1;return o?_n(r,s,n):(s.header.style.display="none",_n(r,s,n)),r.append(i),m||(d.footer.style.display="none"),r.append(d.footer),{container:r,body:i,messagesWrapper:v,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:u,introSubtitle:c,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:d.footer,attachmentButton:d.attachmentButton,attachmentButtonWrapper:d.attachmentButtonWrapper,attachmentInput:d.attachmentInput,attachmentPreviewsContainer:d.attachmentPreviewsContainer,actionsRow:d.actionsRow,leftActions:d.leftActions,rightActions:d.rightActions}};var Ka=320,Ya=320,Xa=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ga=(n,t,r)=>{if(n.length===0)return null;try{let e=g("div","tvw-flex tvw-flex-col tvw-gap-2");e.setAttribute("data-message-attachments","images"),t&&(e.style.marginBottom="8px");let o=0,s=!1,i=()=>{s||(s=!0,e.remove(),r==null||r())};return n.forEach((a,u)=>{var d;let c=g("img");c.alt=((d=a.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Ka}px`,c.style.maxHeight=`${Ya}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--cw-container, #f3f4f6)",c.style.border="1px solid var(--cw-border, #e5e7eb)";let v=!1;o+=1,c.addEventListener("error",()=>{v||(v=!0,o=Math.max(0,o-1),c.remove(),o===0&&i())}),c.addEventListener("load",()=>{v=!0}),c.src=a.image,e.appendChild(c)}),o===0?(i(),null):e}catch{return r==null||r(),null}},Vn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(t),n.appendChild(r),n.appendChild(e),n.appendChild(o),n},Xi=(n,t,r)=>{let e={config:r!=null?r:{},streaming:!0,location:n,defaultRenderer:Vn};if(t){let o=t(e);if(o!==null)return o}return Vn()},Za=(n,t)=>{let r=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let o=g("img");o.src=e,o.alt=t==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=e,r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Yi=(n,t)=>{let r=g("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?r.textContent=t.format(e):r.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Qa=(n,t="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="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"),n==="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;default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="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},Gi=(n,t,r)=>{var w,b,y,S,x,k;let e=(w=t.showCopy)!=null?w:!0,o=(b=t.showUpvote)!=null?b:!0,s=(y=t.showDownvote)!=null?y:!0,i=(S=t.visibility)!=null?S:"hover",a=(x=t.align)!=null?x:"right",u=(k=t.layout)!=null?k:"pill-inside",c={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"}[u],d=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);d.id=`actions-${n.id}`,d.setAttribute("data-actions-for",n.id);let m=(J,E,I)=>{let T=document.createElement("button");T.className="tvw-message-action-btn",T.setAttribute("aria-label",E),T.setAttribute("title",E),T.setAttribute("data-action",I);let B=ie(J,14,"currentColor",2);return B&&T.appendChild(B),T};return e&&d.appendChild(m("copy","Copy message","copy")),o&&d.appendChild(m("thumbs-up","Upvote","upvote")),s&&d.appendChild(m("thumbs-down","Downvote","downvote")),d},Ss=(n,t,r,e,o,s)=>{var U,K,j,ye,se,Y,_;let i=r!=null?r:{},a=(U=i.layout)!=null?U:"bubble",u=i.avatar,c=i.timestamp,v=(K=u==null?void 0:u.show)!=null?K:!1,d=(j=c==null?void 0:c.show)!=null?j:!1,m=(ye=u==null?void 0:u.position)!=null?ye:"left",w=(se=c==null?void 0:c.position)!=null?se:"below",b=Qa(n.role,a),y=g("div",b.join(" "));y.id=`bubble-${n.id}`,y.setAttribute("data-message-id",n.id);let S=Xa(n),x=(_=(Y=n.content)==null?void 0:Y.trim())!=null?_:"",J=S.length>0&&x===Us,E=document.createElement("div"),I=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),T=null;if(J?(T=document.createElement("div"),T.innerHTML=I,T.style.display="none",E.appendChild(T)):E.innerHTML=I,d&&w==="inline"&&n.createdAt){let O=Yi(n,c);O.classList.add("tvw-ml-2","tvw-inline"),E.appendChild(O)}if(S.length>0){let O=Ga(S,!J&&!!x,()=>{J&&T&&(T.style.display="")});O?y.appendChild(O):J&&T&&(T.style.display="")}if(y.appendChild(E),d&&w==="below"&&n.createdAt){let O=Yi(n,c);O.classList.add("tvw-mt-1"),y.appendChild(O)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let O=Xi("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);O&&y.appendChild(O)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let O=Gi(n,e,o);y.appendChild(O)}if(!v||n.role==="system")return y;let le=g("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),z=Za(u,n.role);return m==="right"||m==="left"&&n.role==="user"?le.append(y,z):le.append(z,y),y.classList.remove("tvw-max-w-[85%]"),y.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),le},el=(n,t,r,e,o,s)=>{let i=r!=null?r:{};return n.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):Ss(n,t,r,e,o,s)};var Un=new Set,Zi=(n,t)=>{let r=Un.has(n),e=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".tvw-border-t");if(!e||!o)return;e.setAttribute("aria-expanded",r?"true":"false");let s=e.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let u=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);u?i.appendChild(u):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},br=n=>{let t=n.reasoning,r=g("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let e=Un.has(n.id),o=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Bi(t),s.appendChild(a),t.status==="complete"?i.style.display="none":i.style.display="";let u=g("div","tvw-flex tvw-items-center"),v=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);v?u.appendChild(v):u.textContent=e?"Hide":"Show";let d=g("div","tvw-flex tvw-items-center tvw-ml-auto");d.append(u),o.append(s,d);let m=g("div","tvw-border-t tvw-px-4 tvw-py-3");m.style.display=e?"":"none";let w=t.chunks.join(""),b=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return b.textContent=w||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(b),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),u.innerHTML="";let x=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);x?u.appendChild(x):u.textContent=e?"Hide":"Show",m.style.display=e?"":"none"})(),r.append(o,m),r};var qn=new Set,Qi=(n,t,r)=>{var c;let e=qn.has(n),o=(c=r==null?void 0:r.toolCall)!=null?c:{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",e?"true":"false");let a=s.querySelector(".tvw-ml-auto"),u=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(u){u.innerHTML="";let v=o.toggleTextColor||o.headerTextColor||"currentColor",d=ie(e?"chevron-up":"chevron-down",16,v,2);d?u.appendChild(d):u.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},Cr=(n,t)=>{var y;let r=n.toolCall,e=(y=t==null?void 0:t.toolCall)!=null?y:{},o=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=qn.has(n.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),u=g("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(u.style.color=e.headerTextColor),u.textContent=Fi(r),a.appendChild(u);let c=g("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",d=ie(s?"chevron-up":"chevron-down",16,v,2);d?c.appendChild(d):c.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(c),i.append(a,m);let w=g("div","tvw-border-t tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",e.contentBackgroundColor&&(w.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(w.style.color=e.contentTextColor),e.contentPaddingX&&(w.style.paddingLeft=e.contentPaddingX,w.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(w.style.paddingTop=e.contentPaddingY,w.style.paddingBottom=e.contentPaddingY),r.name){let S=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?S.style.color=e.contentTextColor:e.headerTextColor&&(S.style.color=e.headerTextColor),S.textContent=r.name,w.appendChild(S)}if(r.args!==void 0){let S=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Arguments";let k=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=fs(r.args),S.append(x,k),w.appendChild(S)}if(r.chunks&&r.chunks.length){let S=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Activity";let k=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=r.chunks.join(`
16
- `),S.append(x,k),w.appendChild(S)}if(r.status==="complete"&&r.result!==void 0){let S=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Result";let k=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=fs(r.result),S.append(x,k),w.appendChild(S)}if(r.status==="complete"&&typeof r.duration=="number"){let S=g("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(S.style.color=e.contentTextColor),S.textContent=`Duration: ${r.duration}ms`,w.appendChild(S)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let S=e.toggleTextColor||e.headerTextColor||"currentColor",x=ie(s?"chevron-up":"chevron-down",16,S,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var xr=(n,t)=>{var y,S,x,k,J,E,I,T,B,le,z;let r=n.approval,e=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=g("div",["vanilla-message-bubble","vanilla-approval-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-border","tvw-shadow-sm","tvw-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),e!=null&&e.backgroundColor&&(s.style.backgroundColor=e.backgroundColor),e!=null&&e.borderColor&&(s.style.borderColor=e.borderColor),!r)return s;let i=g("div","tvw-flex tvw-items-start tvw-gap-3 tvw-px-4 tvw-py-3"),a=g("div","tvw-flex-shrink-0 tvw-mt-0.5");a.setAttribute("data-approval-icon","true");let u=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",c=r.status==="approved"?"#16a34a":r.status==="denied"?"#dc2626":r.status==="timeout"?"#ca8a04":(y=e==null?void 0:e.titleColor)!=null?y:"currentColor",v=ie(u,20,c,2);v&&a.appendChild(v);let d=g("div","tvw-flex-1 tvw-min-w-0"),m=g("div","tvw-flex tvw-items-center tvw-gap-2"),w=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary");if(e!=null&&e.titleColor&&(w.style.color=e.titleColor),w.textContent=(S=e==null?void 0:e.title)!=null?S:"Approval Required",m.appendChild(w),!o){let U=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");U.setAttribute("data-approval-status",r.status),r.status==="approved"?(U.className+=" tvw-approval-badge-approved",U.textContent="Approved"):r.status==="denied"?(U.className+=" tvw-approval-badge-denied",U.textContent="Denied"):r.status==="timeout"&&(U.className+=" tvw-approval-badge-timeout",U.textContent="Timeout"),m.appendChild(U)}d.appendChild(m);let b=g("p","tvw-text-sm tvw-mt-0.5 tvw-text-cw-muted");if(e!=null&&e.descriptionColor&&(b.style.color=e.descriptionColor),b.textContent=r.description,d.appendChild(b),r.parameters){let U=g("pre","tvw-mt-2 tvw-text-xs tvw-p-2 tvw-rounded tvw-overflow-x-auto tvw-max-h-32 tvw-bg-cw-container tvw-text-cw-primary");e!=null&&e.parameterBackgroundColor&&(U.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(U.style.color=e.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=fs(r.parameters),d.appendChild(U)}if(o){let U=g("div","tvw-flex tvw-gap-2 tvw-mt-2");U.setAttribute("data-approval-buttons","true");let K=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-border-none tvw-cursor-pointer");K.type="button",K.style.backgroundColor=(x=e==null?void 0:e.approveButtonColor)!=null?x:"#16a34a",K.style.color=(k=e==null?void 0:e.approveButtonTextColor)!=null?k:"#ffffff",K.setAttribute("data-approval-action","approve");let j=ie("shield-check",14,(J=e==null?void 0:e.approveButtonTextColor)!=null?J:"#ffffff",2);j&&(j.style.marginRight="4px",K.appendChild(j));let ye=document.createTextNode((E=e==null?void 0:e.approveLabel)!=null?E:"Approve");K.appendChild(ye);let se=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-cursor-pointer");se.type="button",se.style.backgroundColor=(I=e==null?void 0:e.denyButtonColor)!=null?I:"transparent",se.style.color=(T=e==null?void 0:e.denyButtonTextColor)!=null?T:"#dc2626",se.style.border=`1px solid ${(B=e==null?void 0:e.denyButtonTextColor)!=null?B:"#fca5a5"}`,se.setAttribute("data-approval-action","deny");let Y=ie("shield-x",14,(le=e==null?void 0:e.denyButtonTextColor)!=null?le:"#dc2626",2);Y&&(Y.style.marginRight="4px",se.appendChild(Y));let _=document.createTextNode((z=e==null?void 0:e.denyLabel)!=null?z:"Deny");se.appendChild(_),U.append(K,se),d.appendChild(U)}return i.append(a,d),s.appendChild(i),s};var ea=n=>{let t=[];return{buttons:t,render:(e,o,s,i,a)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:o?o.getMessages():[]).some(w=>w.role==="user"))return;let v=document.createDocumentFragment(),d=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';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(w=>{let b=g("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");b.type="button",b.textContent=w,b.disabled=d,a!=null&&a.fontFamily&&(b.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(b.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(b.style.paddingLeft=a.paddingX,b.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(b.style.paddingTop=a.paddingY,b.style.paddingBottom=a.paddingY),b.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),v.appendChild(b),t.push(b)}),n.appendChild(v)}}};var As=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let e of r)this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(e.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Es=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let e=indexedDB.open(this.dbName,1);e.onupgradeneeded=()=>{let o=e.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},e.onsuccess=()=>{this.db=e.result,t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(i.error)}}catch(e){r(e)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let e=indexedDB.deleteDatabase(this.dbName);e.onsuccess=()=>{t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}};function zn(n,t){t&&t.split(/\s+/).forEach(r=>r&&n.classList.add(r))}var tl={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"}},nl={bg:"#f3f4f6",text:"#4b5563"},sl=["flowName","stepName","reasoningText","text","name","tool","toolName"],rl=100;function ol(n,t){let r={...tl,...t};if(r[n])return r[n];for(let e of Object.keys(r))if(e.endsWith("_")&&n.startsWith(e))return r[e];return nl}function il(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function al(n){let t=new Date(n),r=String(t.getHours()).padStart(2,"0"),e=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${e}:${o}.${s}`}function ll(n,t){try{let r=JSON.parse(n);if(typeof r!="object"||r===null)return null;for(let e of t){let o=e.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 cl(n){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(n):new Promise(r=>{let e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),r()})}function dl(n){let t;try{t=JSON.parse(n.payload)}catch{t=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:t},null,2)}function ul(n,t,r){let e,o;try{o=JSON.parse(n.payload),e=JSON.stringify(o,null,2)}catch{o=n.payload,e=n.payload}let s=t.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:n,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=g("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]"),u=g("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return u.textContent=e,a.appendChild(u),a}}function Sr(n,t,r,e,o,s,i,a){var m;let u=o.has(n.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");zn(c,(m=e.classNames)==null?void 0:m.eventRow);let v=i.find(w=>w.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let w=v.renderEventStreamRow({event:n,index:t,config:a,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>s(n.id)});if(w)return c.appendChild(w),c}return c.appendChild(d()),c;function d(){var j,ye;let w=g("div",""),b=g("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");b.setAttribute("data-event-id",n.id);let y=g("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),S=ie(u?"chevron-down":"chevron-right","14px","currentColor",2);S&&y.appendChild(S);let x=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),k=(j=e.timestampFormat)!=null?j:"relative";x.textContent=k==="relative"?il(n.timestamp,r):al(n.timestamp);let J=null;e.showSequenceNumbers!==!1&&(J=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),J.textContent=String(t+1));let E=ol(n.type,e.badgeColors),I=g("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");I.style.backgroundColor=E.bg,I.style.color=E.text,I.style.borderColor=E.text+"50",I.textContent=n.type;let T=(ye=e.descriptionFields)!=null?ye:sl,B=ll(n.payload,T),le=null;B&&(le=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),le.textContent=B);let z=g("div","tvw-flex-1 tvw-min-w-0"),U=g("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"),K=ie("clipboard","12px","currentColor",1.5);return K&&U.appendChild(K),U.addEventListener("click",async se=>{se.stopPropagation(),await cl(dl(n)),U.innerHTML="";let Y=ie("check","12px","currentColor",1.5);Y&&U.appendChild(Y),setTimeout(()=>{U.innerHTML="";let _=ie("clipboard","12px","currentColor",1.5);_&&U.appendChild(_)},1500)}),b.appendChild(y),b.appendChild(x),J&&b.appendChild(J),b.appendChild(I),le&&b.appendChild(le),b.appendChild(z),b.appendChild(U),w.appendChild(b),u&&w.appendChild(ul(n,i,a)),w}}function ta(n){var c,v;let{buffer:t,getFullHistory:r,onClose:e,config:o,plugins:s=[]}=n,i=(v=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?v:{},a=s.find(d=>d.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let d=a.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>u().element,onClose:e});if(d)return{element:d,update:()=>{},destroy:()=>{}}}return u();function u(){let d=i.classNames,m=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");zn(m,d==null?void 0:d.panel);let w=[],b="",y="",S=null,x=[],k={},J=0,E=!1,I=0,T=0,B=!1,le=null,z=!1,U=0,K=new Set,j=new Map,ye="",se="",Y=null,_,O,Q,ue,Be;function Et(){let N=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),G=g("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");zn(G,d==null?void 0:d.headerBar);let re=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");re.textContent="Events",_=g("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"),_.textContent="0";let $e=g("div","tvw-flex-1");O=g("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 oe=g("option","");oe.value="",oe.textContent="All events",O.appendChild(oe),Q=g("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"),Q.type="button",Q.title="Copy All";let Ke=ie("clipboard-copy","12px","currentColor",1.5);Ke&&Q.appendChild(Ke);let ce=g("span","tvw-text-xs");ce.textContent="Copy All",Q.appendChild(ce),G.appendChild(re),G.appendChild(_),G.appendChild($e),G.appendChild(O),G.appendChild(Q);let D=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");zn(D,d==null?void 0:d.searchBar);let Se=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),et=g("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Se&&et.appendChild(Se),ue=g("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"),zn(ue,d==null?void 0:d.searchInput),ue.type="text",ue.placeholder="Search event payloads...",Be=g("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"),Be.type="button",Be.style.display="none";let tt=ie("x","12px","currentColor",2);return tt&&Be.appendChild(tt),D.appendChild(et),D.appendChild(ue),D.appendChild(Be),N.appendChild(G),N.appendChild(D),N}let dt,gt=s.find(N=>N.renderEventStreamToolbar);if(gt!=null&&gt.renderEventStreamToolbar&&o){let N=gt.renderEventStreamToolbar({config:o,defaultRenderer:()=>Et(),eventCount:t.getSize(),filteredCount:0,onFilterChange:G=>{b=G,at(),yt()},onSearchChange:G=>{y=G,at(),yt()}});dt=N!=null?N:Et()}else dt=Et();let Ht=g("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");Ht.style.display="none";let Ne=g("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ne=g("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ne.style.height="100%";let be=g("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");zn(be,d==null?void 0:d.scrollIndicator),be.style.display="none";let Re=ie("arrow-down","12px","currentColor",2);Re&&be.appendChild(Re);let Fe=g("span","");be.appendChild(Fe);let Ue=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");Ue.style.display="none",Ne.appendChild(ne),Ne.appendChild(Ue),Ne.appendChild(be),m.setAttribute("tabindex","0"),m.appendChild(dt),m.appendChild(Ht),m.appendChild(Ne);function Nt(){let N=t.getAll(),G={};for(let ce of N)G[ce.type]=(G[ce.type]||0)+1;let re=Object.keys(G).sort(),$e=re.length!==x.length||!re.every((ce,D)=>ce===x[D]),oe=!$e&&re.some(ce=>G[ce]!==k[ce]),Je=N.length!==Object.values(k).reduce((ce,D)=>ce+D,0);if(!$e&&!oe&&!Je||(x=re,k=G,!O))return;let Ke=O.value;if(O.options[0].textContent="All events",$e){for(;O.options.length>1;)O.remove(1);for(let ce of re){let D=g("option","");D.value=ce,D.textContent=`${ce} (${G[ce]||0})`,O.appendChild(D)}Ke&&re.includes(Ke)?O.value=Ke:Ke&&(O.value="",b="")}else for(let ce=1;ce<O.options.length;ce++){let D=O.options[ce];D.textContent=`${D.value} (${G[D.value]||0})`}}function de(){let N=t.getAll();if(b&&(N=N.filter(G=>G.type===b)),y){let G=y.toLowerCase();N=N.filter(re=>re.type.toLowerCase().includes(G)||re.payload.toLowerCase().includes(G))}return N}function X(){return b!==""||y!==""}function at(){J=0,I=0,E=!1,be.style.display="none"}function vt(N){K.has(N)?K.delete(N):K.add(N),Y=N;let G=ne.scrollTop,re=E;z=!0,E=!0,yt(),ne.scrollTop=G,E=re,z=!1}function Tt(){return ne.scrollHeight-ne.scrollTop-ne.clientHeight<=50}function yt(){T=Date.now(),B=!1,Nt();let N=t.getEvictedCount();N>0?(Ht.textContent=`${N.toLocaleString()} older events truncated`,Ht.style.display=""):Ht.style.display="none",w=de();let G=w.length,re=t.getSize()>0;_&&(_.textContent=String(t.getSize())),G===0&&re&&X()?(Ue.textContent=y?`No events matching '${y}'`:"No events matching filter",Ue.style.display="",ne.style.display="none"):(Ue.style.display="none",ne.style.display=""),Q&&(Q.title=X()?`Copy Filtered (${G})`:"Copy All"),E&&G>J&&(I+=G-J,Fe.textContent=`${I} new event${I===1?"":"s"}`,be.style.display=""),J=G;let $e=t.getAll(),oe=$e.length>0?$e[0].timestamp:0,Je=new Set(w.map(D=>D.id));for(let D of K)Je.has(D)||K.delete(D);let Ke=b!==ye||y!==se,ce=j.size===0&&w.length>0;if(Ke||ce||w.length===0){ne.innerHTML="",j.clear();let D=document.createDocumentFragment();for(let Se=0;Se<w.length;Se++){let et=Sr(w[Se],Se,oe,i,K,vt,s,o);j.set(w[Se].id,et),D.appendChild(et)}ne.appendChild(D),ye=b,se=y,Y=null}else{if(Y!==null){let Se=j.get(Y);if(Se&&Se.parentNode===ne){let et=w.findIndex(tt=>tt.id===Y);if(et>=0){let tt=Sr(w[et],et,oe,i,K,vt,s,o);ne.insertBefore(tt,Se),Se.remove(),j.set(Y,tt)}}Y=null}let D=new Set(w.map(Se=>Se.id));for(let[Se,et]of j)D.has(Se)||(et.remove(),j.delete(Se));for(let Se=0;Se<w.length;Se++){let et=w[Se];if(!j.has(et.id)){let tt=Sr(et,Se,oe,i,K,vt,s,o);j.set(et.id,tt),ne.appendChild(tt)}}}E||(ne.scrollTop=ne.scrollHeight)}function Kt(){if(Date.now()-T>=rl){le!==null&&(cancelAnimationFrame(le),le=null),yt();return}B||(B=!0,le=requestAnimationFrame(()=>{le=null,yt()}))}let ee=(N,G)=>{if(!Q)return;Q.innerHTML="";let re=ie(N,"12px","currentColor",1.5);re&&Q.appendChild(re);let $e=g("span","tvw-text-xs");$e.textContent="Copy All",Q.appendChild($e),setTimeout(()=>{Q.innerHTML="";let oe=ie("clipboard-copy","12px","currentColor",1.5);oe&&Q.appendChild(oe);let Je=g("span","tvw-text-xs");Je.textContent="Copy All",Q.appendChild(Je),Q.disabled=!1},G)},Le=async()=>{if(Q){Q.disabled=!0;try{let N;X()?N=w:r?(N=await r(),N.length===0&&(N=t.getAll())):N=t.getAll();let G=N.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(G,null,2)),ee("check",1500)}catch{ee("x",1500)}}},bt=()=>{O&&(b=O.value,at(),yt())},pe=()=>{!ue||!Be||(Be.style.display=ue.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{y=ue.value,at(),yt()},150))},Ce=()=>{!ue||!Be||(ue.value="",y="",Be.style.display="none",S&&clearTimeout(S),at(),yt())},qe=()=>{if(z)return;let N=ne.scrollTop,G=N>U;U=N,Tt()&&G?(E=!1,I=0,be.style.display="none"):Tt()||(E=!0)},Bt=N=>{N.deltaY<0&&(E=!0)},Mt=()=>{ne.scrollTop=ne.scrollHeight,E=!1,I=0,be.style.display="none"},Vt=N=>{let G=N.target;if(!G||G.closest("button"))return;let re=G.closest("[data-event-id]");if(!re)return;let $e=re.getAttribute("data-event-id");$e&&vt($e)},F=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}N.key==="Escape"&&(ue&&document.activeElement===ue?(Ce(),ue.blur(),m.focus()):e&&e())};Q&&Q.addEventListener("click",Le),O&&O.addEventListener("change",bt),ue&&ue.addEventListener("input",pe),Be&&Be.addEventListener("click",Ce),ne.addEventListener("scroll",qe),ne.addEventListener("wheel",Bt,{passive:!0}),ne.addEventListener("click",Vt),be.addEventListener("click",Mt),m.addEventListener("keydown",F);function Qe(){S&&clearTimeout(S),le!==null&&(cancelAnimationFrame(le),le=null),B=!1,j.clear(),Q&&Q.removeEventListener("click",Le),O&&O.removeEventListener("change",bt),ue&&ue.removeEventListener("input",pe),Be&&Be.removeEventListener("click",Ce),ne.removeEventListener("scroll",qe),ne.removeEventListener("wheel",Bt),ne.removeEventListener("click",Vt),be.removeEventListener("click",Mt),m.removeEventListener("keydown",F)}return{element:m,update:Kt,destroy:Qe}}}var na={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"}},Ar=(n,t,r,e)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var b,y,S;if(s.dataset.enhanced==="true")return;let i=(b=s.dataset.tvForm)!=null?b:"init";s.dataset.enhanced="true";let a=(y=na[i])!=null?y:na.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=g("div","tvw-space-y-1"),c=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,u.appendChild(c),a.description){let x=g("p","tvw-text-sm tvw-text-cw-muted");x.textContent=a.description,u.appendChild(x)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(x=>{var T,B;let k=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");k.htmlFor=`${t.id}-${i}-${x.name}`;let J=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");J.textContent=x.label,k.appendChild(J);let E=(T=x.type)!=null?T:"text",I;E==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=E),I.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",I.id=`${t.id}-${i}-${x.name}`,I.name=x.name,I.placeholder=(B=x.placeholder)!=null?B:"",x.required&&(I.required=!0),k.appendChild(I),v.appendChild(k)});let d=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(S=a.submitLabel)!=null?S:"Submit",d.appendChild(m),d.appendChild(w),v.appendChild(d),s.replaceChildren(u,v),v.addEventListener("submit",async x=>{var I,T;x.preventDefault();let k=(I=r.formEndpoint)!=null?I:"/form",J=new FormData(v),E={};J.forEach((B,le)=>{E[le]=B}),E.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let B=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!B.ok)throw new Error(`Form submission failed (${B.status})`);let le=await B.json();m.textContent=(T=le.message)!=null?T:"Thanks! We'll be in touch soon.",le.success&&le.nextPrompt&&await e.sendMessage(String(le.nextPrompt))}catch(B){m.textContent=B instanceof Error?B.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Er=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var e;let r=this.plugins.get(t);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let e=new Set(t.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...t].sort((s,i)=>{var a,u;return((a=i.priority)!=null?a:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Ys=new Er;var sa={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"},ra={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"},it={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:sa,darkTheme:ra,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 Tr(n){var t,r,e,o,s,i,a,u,c,v,d,m,w,b,y,S,x,k,J;return n?{...it,...n,theme:{...it.theme,...n.theme},darkTheme:{...it.darkTheme,...n.darkTheme},launcher:{...it.launcher,...n.launcher,clearChat:{...(t=it.launcher)==null?void 0:t.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...it.copy,...n.copy},sendButton:{...it.sendButton,...n.sendButton},statusIndicator:{...it.statusIndicator,...n.statusIndicator},voiceRecognition:{...it.voiceRecognition,...n.voiceRecognition},features:{...it.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...it.layout,...n.layout,header:{...(o=it.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=it.layout)==null?void 0:i.messages,...(a=n.layout)==null?void 0:a.messages,avatar:{...(c=(u=it.layout)==null?void 0:u.messages)==null?void 0:c.avatar,...(d=(v=n.layout)==null?void 0:v.messages)==null?void 0:d.avatar},timestamp:{...(w=(m=it.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(y=(b=n.layout)==null?void 0:b.messages)==null?void 0:y.timestamp}},slots:{...(S=it.layout)==null?void 0:S.slots,...(x=n.layout)==null?void 0:x.slots}},markdown:{...it.markdown,...n.markdown,options:{...(k=it.markdown)==null?void 0:k.options,...(J=n.markdown)==null?void 0:J.options}},messageActions:{...it.messageActions,...n.messageActions}}:it}var oa=()=>{let n=new Map,t=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:t,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(a=>{try{a(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var pl=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},gl=n=>{let t=n.trim(),r=t.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<t.length;o+=1){let s=t[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return t.slice(r,o+1)}return null},Xs=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=pl(n),r=gl(t);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},Mr=n=>typeof n=="string"?n:n==null?"":String(n),Jn={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Mr(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,e=Mr(r.element);if(e&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Mr(r.text)}}},ia=n=>Array.isArray(n)?n.map(t=>String(t)):[],Gs=n=>{let t=new Set(ia(n.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ia(n.getSessionMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(t);n.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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?n.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;t.add(s.message.id),e();let u={action:a,message:s.message};n.emit("action:detected",u);for(let c of n.handlers)if(c)try{let v=()=>{n.emit("action:resubmit",u)},d=c(a,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:v});if(!d)continue;if(d.handled){let m=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:m,resubmit:d.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var ml=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},hl=n=>n.map(t=>({...t,streaming:!1})),kr=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?ml(r.getItem(n)):null},save:r=>{let e=t();if(e)try{let o={...r,messages:r.messages?hl(r.messages):void 0};e.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=t();if(r)try{r.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Ir=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,e])=>{this.register(r,e)})}},Ts=new Ir;import{parse as fl,STR as wl,OBJ as vl}from"partial-json";function yl(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function bl(n,t){if(!yl(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:t}}function Lr(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n;try{let o=fl(r,wl|vl),s=bl(o,r);s&&(n=s)}catch{}return t=r.length,n},reset:()=>{n=null,t=0}}}function Cl(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Wr(n,t){let{config:r,message:e,onPropsUpdate:o}=t,s=Ts.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:e,config:r,updateProps:a=>{o&&o(a)}};try{return s(n.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,a),null}}function xl(){let n=Lr();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Pr(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Rr(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var Sl=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Hr(n){let{onSubmit:t,onDismiss:r,title:e="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:u=!0,ratingLabels:c=Sl}=n,v=document.createElement("div");v.className="tvw-feedback-container tvw-feedback-csat",v.setAttribute("role","dialog"),v.setAttribute("aria-label","Customer satisfaction feedback");let d=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let b=document.createElement("h3");b.className="tvw-feedback-title",b.textContent=e,w.appendChild(b);let y=document.createElement("p");y.className="tvw-feedback-subtitle",y.textContent=o,w.appendChild(y),m.appendChild(w);let S=document.createElement("div");S.className="tvw-feedback-rating tvw-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let T=1;T<=5;T++){let B=document.createElement("button");B.type="button",B.className="tvw-feedback-rating-btn tvw-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${T} star${T>1?"s":""}: ${c[T-1]}`),B.title=c[T-1],B.dataset.rating=String(T),B.innerHTML=`
15
+ `,r.addEventListener("click",t);let e=s=>{var x,H,Y,k,P,L,F,ue,z,V,X,_;let i=(x=s.launcher)!=null?x:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(H=i.title)!=null?H:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(Y=i.subtitle)!=null?Y:"Get answers fast");let c=r.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let v=r.querySelector("[data-role='launcher-icon']");if(v)if(i.agentIconHidden)v.style.display="none";else{let Ce=(k=i.agentIconSize)!=null?k:"40px";if(v.style.height=Ce,v.style.width=Ce,v.innerHTML="",i.agentIconName){let se=parseFloat(Ce)||24,G=ie(i.agentIconName,se*.6,"#ffffff",2);G?(v.appendChild(G),v.style.display=""):(v.textContent=(P=i.agentIconText)!=null?P:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(L=i.agentIconText)!=null?L:"\u{1F4AC}",v.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let Ce=(F=i.agentIconSize)!=null?F:"40px";p.style.height=Ce,p.style.width=Ce,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(p.src=i.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(ue=i.callToActionIconSize)!=null?ue:"32px";m.style.height=Ce,m.style.width=Ce,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 se=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,se=(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 G=parseFloat(Ce)||24,U=Math.max(G-se,8),N=ie(i.callToActionIconName,U,"currentColor",2);N?m.appendChild(N):m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}let w=i.position&&sn[i.position]?sn[i.position]:sn["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 y="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=(X=i.border)!=null?X:y,r.style.boxShadow=(_=i.shadow)!=null?_:A},o=()=>{r.removeEventListener("click",t),r.remove()};return n&&e(n),{element:r,update:e,destroy:o}};var Cn=n=>{var V,X,_,Ce,se,G,U,N,ee,fe,Fe,Mt,gt,ft,Ht,je,ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt;let{config:t,showClose:r=!0}=n,e=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(V=t==null?void 0:t.launcher)!=null?V:{},s=(X=o.headerIconSize)!=null?X:"48px",i=(_=o.closeButtonSize)!=null?_:"32px",a=(Ce=o.closeButtonPlacement)!=null?Ce:"inline",d=(se=o.headerIconHidden)!=null?se:!1,c=o.headerIconName,v=g("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(c){let ve=parseFloat(s)||24,Se=ie(c,ve*.6,"#ffffff",1);Se?v.replaceChildren(Se):v.textContent=(U=(G=t==null?void 0:t.launcher)==null?void 0:G.agentIconText)!=null?U:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let ve=g("img");ve.src=t.launcher.iconUrl,ve.alt="",ve.className="tvw-rounded-xl tvw-object-cover",ve.style.height=s,ve.style.width=s,v.replaceChildren(ve)}else v.textContent=(fe=(ee=t==null?void 0:t.launcher)==null?void 0:ee.agentIconText)!=null?fe:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(Mt=(Fe=t==null?void 0:t.launcher)==null?void 0:Fe.title)!=null?Mt:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(ft=(gt=t==null?void 0:t.launcher)==null?void 0:gt.subtitle)!=null?ft:"Here to help you get answers fast",p.append(m,w),d?e.append(p):e.append(v,p);let C=(Ht=o.clearChat)!=null?Ht:{},y=(je=C.enabled)!=null?je:!0,A=(ne=C.placement)!=null?ne:"inline",x=null,H=null;if(y){let ve=(xe=C.size)!=null?xe:"32px",Se=(He=C.iconName)!=null?He:"refresh-cw",Je=($e=C.iconColor)!=null?$e:"",Bt=(ze=C.backgroundColor)!=null?ze:"",It=(Ot=C.borderWidth)!=null?Ot:"",qt=(he=C.borderColor)!=null?he:"",I=(Z=C.borderRadius)!=null?Z:"",nt=(ct=C.paddingX)!=null?ct:"",O=(bt=C.paddingY)!=null?bt:"",Q=(kt=C.tooltipText)!=null?kt:"Clear chat",re=(Ct=C.showTooltip)!=null?Ct:!0;H=g("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"&&(H.style.right="48px"),x=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),x.style.height=ve,x.style.width=ve,x.type="button",x.setAttribute("aria-label",Q);let Ne=ie(Se,"20px",Je||"",1);if(Ne&&x.appendChild(Ne),Je&&(x.style.color=Je,x.classList.remove("tvw-text-cw-muted")),Bt&&(x.style.backgroundColor=Bt,x.classList.remove("hover:tvw-bg-gray-100")),It||qt){let oe=It||"0px",Xe=qt||"transparent";x.style.border=`${oe} solid ${Xe}`,x.classList.remove("tvw-border-none")}if(I&&(x.style.borderRadius=I,x.classList.remove("tvw-rounded-full")),nt?(x.style.paddingLeft=nt,x.style.paddingRight=nt):(x.style.paddingLeft="",x.style.paddingRight=""),O?(x.style.paddingTop=O,x.style.paddingBottom=O):(x.style.paddingTop="",x.style.paddingBottom=""),H.appendChild(x),re&&Q&&x&&H){let oe=null,Xe=()=>{if(oe||!x)return;oe=g("div","tvw-clear-chat-tooltip"),oe.textContent=Q;let pe=g("div");pe.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(pe);let D=x.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${D.left+D.width/2}px`,oe.style.top=`${D.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},Ge=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};H.addEventListener("mouseenter",Xe),H.addEventListener("mouseleave",Ge),x.addEventListener("focus",Xe),x.addEventListener("blur",Ge),H._cleanupTooltip=()=>{Ge(),H&&(H.removeEventListener("mouseenter",Xe),H.removeEventListener("mouseleave",Ge)),x&&(x.removeEventListener("focus",Xe),x.removeEventListener("blur",Ge))}}A==="inline"&&e.appendChild(H)}let Y=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":y&&A==="inline"?"":"tvw-ml-auto"),k=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");k.style.height=i,k.style.width=i,k.type="button";let P=(Kt=o.closeButtonTooltipText)!=null?Kt:"Close chat",L=(te=o.closeButtonShowTooltip)!=null?te:!0;k.setAttribute("aria-label",P),k.style.display=r?"":"none";let F=(Pe=o.closeButtonIconName)!=null?Pe:"x",ue=(xt=o.closeButtonIconText)!=null?xt:"\xD7",z=ie(F,"20px",o.closeButtonColor||"",1);if(z?k.appendChild(z):k.textContent=ue,o.closeButtonColor?(k.style.color=o.closeButtonColor,k.classList.remove("tvw-text-cw-muted")):(k.style.color="",k.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(k.style.backgroundColor=o.closeButtonBackgroundColor,k.classList.remove("hover:tvw-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let ve=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";k.style.border=`${ve} solid ${Se}`,k.classList.remove("tvw-border-none")}else k.style.border="",k.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(k.style.borderRadius=o.closeButtonBorderRadius,k.classList.remove("tvw-rounded-full")):(k.style.borderRadius="",k.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(k.style.paddingLeft=o.closeButtonPaddingX,k.style.paddingRight=o.closeButtonPaddingX):(k.style.paddingLeft="",k.style.paddingRight=""),o.closeButtonPaddingY?(k.style.paddingTop=o.closeButtonPaddingY,k.style.paddingBottom=o.closeButtonPaddingY):(k.style.paddingTop="",k.style.paddingBottom=""),Y.appendChild(k),L&&P){let ve=null,Se=()=>{if(ve)return;ve=g("div","tvw-clear-chat-tooltip"),ve.textContent=P;let Bt=g("div");Bt.className="tvw-clear-chat-tooltip-arrow",ve.appendChild(Bt);let It=k.getBoundingClientRect();ve.style.position="fixed",ve.style.left=`${It.left+It.width/2}px`,ve.style.top=`${It.top-8}px`,ve.style.transform="translate(-50%, -100%)",document.body.appendChild(ve)},Je=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};Y.addEventListener("mouseenter",Se),Y.addEventListener("mouseleave",Je),k.addEventListener("focus",Se),k.addEventListener("blur",Je),Y._cleanupTooltip=()=>{Je(),Y.removeEventListener("mouseenter",Se),Y.removeEventListener("mouseleave",Je),k.removeEventListener("focus",Se),k.removeEventListener("blur",Je)}}return a!=="top-right"&&e.appendChild(Y),{header:e,iconHolder:v,headerTitle:m,headerSubtitle:w,closeButton:k,closeButtonWrapper:Y,clearChatButton:x,clearChatButtonWrapper:H}},Vn=(n,t,r)=>{var i,a,d,c;let e=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=e.closeButtonPlacement)!=null?a:"inline",s=(c=(d=e.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),o==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var Xi=n=>Cn({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Gi=n=>{var C,y,A,x;let{config:t,showClose:r=!0,onClose:e}=n,o=(C=t==null?void 0:t.launcher)!=null?C:{},s=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=g("span","tvw-text-base tvw-font-semibold");i.textContent=(y=o.title)!=null?y:"Chat Assistant",s.appendChild(i);let a=(A=o.closeButtonSize)!=null?A:"32px",d=g("div",""),c=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=a,c.style.width=a,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=r?"":"none";let v=(x=o.closeButtonIconName)!=null?x:"x",p=ie(v,"20px",o.closeButtonColor||"",2);p?c.appendChild(p):c.textContent="\xD7",e&&c.addEventListener("click",e),d.appendChild(c),s.appendChild(d);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Zi=n=>{var k,P,L,F,ue,z,V,X;let{config:t,showClose:r=!0,onClose:e,onClearChat:o}=n,s=(k=t==null?void 0:t.launcher)!=null?k:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),d=(P=s.headerIconSize)!=null?P:"56px",c=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let v=s.headerIconName;if(v){let _=parseFloat(d)||24,Ce=ie(v,_*.5,"#ffffff",2);Ce?c.replaceChildren(Ce):c.textContent=(L=s.agentIconText)!=null?L:"\u{1F4AC}"}else if(s.iconUrl){let _=g("img");_.src=s.iconUrl,_.alt="",_.className="tvw-rounded-xl tvw-object-cover",_.style.height=d,_.style.width=d,c.replaceChildren(_)}else c.textContent=(F=s.agentIconText)!=null?F:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(ue=s.title)!=null?ue:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(z=s.subtitle)!=null?z:"Here to help you get answers fast",p.append(m,w),a.append(c,p);let C=(V=s.closeButtonSize)!=null?V:"32px",y=g("div",""),A=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");A.style.height=C,A.style.width=C,A.type="button",A.setAttribute("aria-label","Close chat"),A.style.display=r?"":"none";let x=(X=s.closeButtonIconName)!=null?X:"x",H=ie(x,"20px",s.closeButtonColor||"",2);H?A.appendChild(H):A.textContent="\xD7",e&&A.addEventListener("click",e),y.appendChild(A),a.appendChild(y),i.appendChild(a);let Y=g("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:c,headerTitle:m,headerSubtitle:w,closeButton:A,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},Cr={default:Xi,minimal:Gi,expanded:Zi},Qi=n=>{var t;return(t=Cr[n])!=null?t:Cr.default},ys=(n,t,r)=>{var i,a,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),v=g("div");v.style.display="none";let p=g("span"),m=g("span"),w=g("button");w.style.display="none";let C=g("div");return C.style.display="none",{header:c,iconHolder:v,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",s=Qi(e)({config:n,showClose:(d=(a=t==null?void 0:t.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 t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var el=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},bs=n=>{var ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt,ve,Se,Je,Bt,It,qt,I,nt,O,Q,re,Ne,oe,Xe,Ge;let{config:t}=n,r=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=g("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=g("textarea");s.placeholder=(xe=(ne=t==null?void 0:t.copy)==null?void 0:ne.inputPlaceholder)!=null?xe:"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=($e=(He=t==null?void 0:t.theme)==null?void 0:He.inputFontFamily)!=null?$e:"sans-serif",a=(Ot=(ze=t==null?void 0:t.theme)==null?void 0:ze.inputFontWeight)!=null?Ot:"400";s.style.fontFamily=el(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let pe=Math.min(s.scrollHeight,v);s.style.height=`${pe}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=(he=t==null?void 0:t.sendButton)!=null?he:{},w=(Z=m.useIcon)!=null?Z:!1,C=(ct=m.iconText)!=null?ct:"\u2191",y=m.iconName,A=(bt=m.tooltipText)!=null?bt:"Send message",x=(kt=m.showTooltip)!=null?kt:!1,H=(Ct=m.size)!=null?Ct:"40px",Y=m.backgroundColor,k=m.textColor,P=g("div","tvw-send-button-wrapper"),L=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(L.type="submit",w){if(L.style.width=H,L.style.height=H,L.style.minWidth=H,L.style.minHeight=H,L.style.fontSize="18px",L.style.lineHeight="1",L.innerHTML="",y){let pe=parseFloat(H)||24,D=k&&typeof k=="string"&&k.trim()?k.trim():"currentColor",Ee=ie(y,pe,D,2);Ee?(L.appendChild(Ee),L.style.color=D):(L.textContent=C,k?L.style.color=k:L.classList.add("tvw-text-white"))}else L.textContent=C,k?L.style.color=k:L.classList.add("tvw-text-white");Y?L.style.backgroundColor=Y:L.classList.add("tvw-bg-cw-primary")}else L.textContent=(te=(Kt=t==null?void 0:t.copy)==null?void 0:Kt.sendButtonLabel)!=null?te:"Send",k?L.style.color=k:L.classList.add("tvw-text-white");if(m.borderWidth&&(L.style.borderWidth=m.borderWidth,L.style.borderStyle="solid"),m.borderColor&&(L.style.borderColor=m.borderColor),m.paddingX?(L.style.paddingLeft=m.paddingX,L.style.paddingRight=m.paddingX):(L.style.paddingLeft="",L.style.paddingRight=""),m.paddingY?(L.style.paddingTop=m.paddingY,L.style.paddingBottom=m.paddingY):(L.style.paddingTop="",L.style.paddingBottom=""),x&&A){let pe=g("div","tvw-send-button-tooltip");pe.textContent=A,P.appendChild(pe)}P.appendChild(L);let F=(Pe=t==null?void 0:t.voiceRecognition)!=null?Pe:{},ue=F.enabled===!0,z=null,V=null,X=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),_=((xt=F.provider)==null?void 0:xt.type)==="runtype";if(ue&&(X||_)){V=g("div","tvw-send-button-wrapper"),z=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),z.type="button",z.setAttribute("aria-label","Start voice recognition");let pe=(ve=F.iconName)!=null?ve:"mic",D=(Se=F.iconSize)!=null?Se:H,Ee=parseFloat(D)||24,st=(Je=F.backgroundColor)!=null?Je:Y,rt=(Bt=F.iconColor)!=null?Bt:k;z.style.width=D,z.style.height=D,z.style.minWidth=D,z.style.minHeight=D,z.style.fontSize="18px",z.style.lineHeight="1";let Yt=rt||"currentColor",Qt=ie(pe,Ee,Yt,1.5);Qt?(z.appendChild(Qt),z.style.color=Yt):(z.textContent="\u{1F3A4}",z.style.color=Yt),st?z.style.backgroundColor=st:z.classList.add("tvw-bg-cw-primary"),rt?z.style.color=rt:!rt&&!k&&z.classList.add("tvw-text-white"),F.borderWidth&&(z.style.borderWidth=F.borderWidth,z.style.borderStyle="solid"),F.borderColor&&(z.style.borderColor=F.borderColor),F.paddingX&&(z.style.paddingLeft=F.paddingX,z.style.paddingRight=F.paddingX),F.paddingY&&(z.style.paddingTop=F.paddingY,z.style.paddingBottom=F.paddingY),V.appendChild(z);let Ze=(It=F.tooltipText)!=null?It:"Start voice recognition";if(((qt=F.showTooltip)!=null?qt:!1)&&Ze){let mn=g("div","tvw-send-button-tooltip");mn.textContent=Ze,V.appendChild(mn)}}let se=(I=t==null?void 0:t.attachments)!=null?I:{},G=se.enabled===!0,U=null,N=null,ee=null,fe=null;if(G){fe=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),fe.style.display="none",ee=g("input"),ee.type="file",ee.accept=((nt=se.allowedTypes)!=null?nt:bn).join(","),ee.multiple=((O=se.maxFiles)!=null?O:4)>1,ee.style.display="none",ee.setAttribute("aria-label","Attach files"),N=g("div","tvw-send-button-wrapper"),U=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),U.type="button",U.setAttribute("aria-label",(Q=se.buttonTooltipText)!=null?Q:"Attach file");let pe=(re=se.buttonIconName)!=null?re:"paperclip",D=H,Ee=parseFloat(D)||40,st=Math.round(Ee*.6);U.style.width=D,U.style.height=D,U.style.minWidth=D,U.style.minHeight=D,U.style.fontSize="18px",U.style.lineHeight="1",U.style.backgroundColor="transparent",U.style.color="var(--cw-primary, #111827)",U.style.border="none",U.style.borderRadius="6px",U.style.transition="background-color 0.15s ease",U.addEventListener("mouseenter",()=>{U.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),U.addEventListener("mouseleave",()=>{U.style.backgroundColor="transparent"});let rt=ie(pe,st,"currentColor",1.5);rt?U.appendChild(rt):U.textContent="\u{1F4CE}",U.addEventListener("click",Ze=>{Ze.preventDefault(),ee==null||ee.click()}),N.appendChild(U);let Yt=(Ne=se.buttonTooltipText)!=null?Ne:"Attach file",Qt=g("div","tvw-send-button-tooltip");Qt.textContent=Yt,N.appendChild(Qt)}o.addEventListener("click",pe=>{pe.target!==L&&pe.target!==P&&pe.target!==z&&pe.target!==V&&pe.target!==U&&pe.target!==N&&s.focus()}),fe&&(fe.style.gap="8px",o.append(fe)),ee&&o.append(ee),o.append(s);let Fe=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Mt=g("div","tvw-flex tvw-items-center tvw-gap-2");N&&Mt.append(N);let gt=g("div","tvw-flex tvw-items-center tvw-gap-1");V&&gt.append(V),gt.append(P),Fe.append(Mt,gt),o.append(Fe);let ft=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Ht=(oe=t==null?void 0:t.statusIndicator)!=null?oe:{},je=(Xe=Ht.visible)!=null?Xe:!0;return ft.style.display=je?"":"none",ft.textContent=(Ge=Ht.idleText)!=null?Ge:"Online",r.append(e,o,ft),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:L,sendButtonWrapper:P,micButton:z,micButtonWrapper:V,statusText:ft,attachmentButton:U,attachmentButtonWrapper:N,attachmentInput:ee,attachmentPreviewsContainer:fe,actionsRow:Fe,leftActions:Mt,rightActions:gt}};var ea=n=>{var d,c,v,p,m,w,C;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let y=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),A=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(p=(v=n==null?void 0:n.launcher)==null?void 0:v.width)!=null?p:"100%";return y.style.width=x,A.style.width="100%",y.appendChild(A),{wrapper:y,panel:A}}let r=(m=n==null?void 0:n.launcher)!=null?m:{},e=r.position&&sn[r.position]?sn[r.position]:sn["bottom-right"],o=g("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(C=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?C:n==null?void 0:n.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}},ta=(n,t=!0)=>{var w,C,y,A,x,H,Y;let r=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),e=(w=n==null?void 0:n.layout)==null?void 0:w.header,o=((C=n==null?void 0:n.layout)==null?void 0:C.showHeader)!==!1,s=e?ys(n,e,{showClose:t}):Cn({config:n,showClose:t}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(A=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(H=(x=n==null?void 0:n.copy)==null?void 0:x.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",a.append(d,c);let v=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let p=bs({config:n}),m=((Y=n==null?void 0:n.layout)==null?void 0:Y.showFooter)!==!1;return o?Vn(r,s,n):(s.header.style.display="none",Vn(r,s,n)),r.append(i),m||(p.footer.style.display="none"),r.append(p.footer),{container:r,body:i,messagesWrapper:v,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.statusText,introTitle:d,introSubtitle:c,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions}};var tl=320,nl=320,sl=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),rl=(n,t,r)=>{if(n.length===0)return null;try{let e=g("div","tvw-flex tvw-flex-col tvw-gap-2");e.setAttribute("data-message-attachments","images"),t&&(e.style.marginBottom="8px");let o=0,s=!1,i=()=>{s||(s=!0,e.remove(),r==null||r())};return n.forEach((a,d)=>{var p;let c=g("img");c.alt=((p=a.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${tl}px`,c.style.maxHeight=`${nl}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--cw-container, #f3f4f6)",c.style.border="1px solid var(--cw-border, #e5e7eb)";let v=!1;o+=1,c.addEventListener("error",()=>{v||(v=!0,o=Math.max(0,o-1),c.remove(),o===0&&i())}),c.addEventListener("load",()=>{v=!0}),c.src=a.image,e.appendChild(c)}),o===0?(i(),null):e}catch{return r==null||r(),null}},zn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(t),n.appendChild(r),n.appendChild(e),n.appendChild(o),n},sa=(n,t,r)=>{let e={config:r!=null?r:{},streaming:!0,location:n,defaultRenderer:zn};if(t){let o=t(e);if(o!==null)return o}return zn()},ol=(n,t)=>{let r=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let o=g("img");o.src=e,o.alt=t==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=e,r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},na=(n,t)=>{let r=g("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?r.textContent=t.format(e):r.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},il=(n,t="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="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"),n==="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;default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="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},ra=(n,t,r)=>{var w,C,y,A,x,H;let e=(w=t.showCopy)!=null?w:!0,o=(C=t.showUpvote)!=null?C:!0,s=(y=t.showDownvote)!=null?y:!0,i=(A=t.visibility)!=null?A:"hover",a=(x=t.align)!=null?x:"right",d=(H=t.layout)!=null?H:"pill-inside",c={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],p=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);p.id=`actions-${n.id}`,p.setAttribute("data-actions-for",n.id);let m=(Y,k,P)=>{let L=document.createElement("button");L.className="tvw-message-action-btn",L.setAttribute("aria-label",k),L.setAttribute("title",k),L.setAttribute("data-action",P);let F=ie(Y,14,"currentColor",2);return F&&L.appendChild(F),L};return e&&p.appendChild(m("copy","Copy message","copy")),o&&p.appendChild(m("thumbs-up","Upvote","upvote")),s&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},Cs=(n,t,r,e,o,s)=>{var V,X,_,Ce,se,G,U;let i=r!=null?r:{},a=(V=i.layout)!=null?V:"bubble",d=i.avatar,c=i.timestamp,v=(X=d==null?void 0:d.show)!=null?X:!1,p=(_=c==null?void 0:c.show)!=null?_:!1,m=(Ce=d==null?void 0:d.position)!=null?Ce:"left",w=(se=c==null?void 0:c.position)!=null?se:"below",C=il(n.role,a),y=g("div",C.join(" "));y.id=`bubble-${n.id}`,y.setAttribute("data-message-id",n.id);let A=sl(n),x=(U=(G=n.content)==null?void 0:G.trim())!=null?U:"",Y=A.length>0&&x===qs,k=document.createElement("div"),P=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),L=null;if(Y?(L=document.createElement("div"),L.innerHTML=P,L.style.display="none",k.appendChild(L)):k.innerHTML=P,p&&w==="inline"&&n.createdAt){let N=na(n,c);N.classList.add("tvw-ml-2","tvw-inline"),k.appendChild(N)}if(A.length>0){let N=rl(A,!Y&&!!x,()=>{Y&&L&&(L.style.display="")});N?y.appendChild(N):Y&&L&&(L.style.display="")}if(y.appendChild(k),p&&w==="below"&&n.createdAt){let N=na(n,c);N.classList.add("tvw-mt-1"),y.appendChild(N)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let N=sa("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);N&&y.appendChild(N)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let N=ra(n,e,o);y.appendChild(N)}if(!v||n.role==="system")return y;let ue=g("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),z=ol(d,n.role);return m==="right"||m==="left"&&n.role==="user"?ue.append(y,z):ue.append(z,y),y.classList.remove("tvw-max-w-[85%]"),y.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),ue},al=(n,t,r,e,o,s)=>{let i=r!=null?r:{};return n.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):Cs(n,t,r,e,o,s)};var Jn=new Set,oa=(n,t)=>{let r=Jn.has(n),e=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".tvw-border-t");if(!e||!o)return;e.setAttribute("aria-expanded",r?"true":"false");let s=e.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},xr=n=>{let t=n.reasoning,r=g("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let e=Jn.has(n.id),o=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=_i(t),s.appendChild(a),t.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),v=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);v?d.appendChild(v):d.textContent=e?"Hide":"Show";let p=g("div","tvw-flex tvw-items-center tvw-ml-auto");p.append(d),o.append(s,p);let m=g("div","tvw-border-t tvw-px-4 tvw-py-3");m.style.display=e?"":"none";let w=t.chunks.join(""),C=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return C.textContent=w||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(C),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),d.innerHTML="";let x=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=e?"Hide":"Show",m.style.display=e?"":"none"})(),r.append(o,m),r};var Kn=new Set,ia=(n,t,r)=>{var c;let e=Kn.has(n),o=(c=r==null?void 0:r.toolCall)!=null?c:{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",e?"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",p=ie(e?"chevron-up":"chevron-down",16,v,2);p?d.appendChild(p):d.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},Sr=(n,t)=>{var y;let r=n.toolCall,e=(y=t==null?void 0:t.toolCall)!=null?y:{},o=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=Kn.has(n.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),d=g("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(d.style.color=e.headerTextColor),d.textContent=Ui(r),a.appendChild(d);let c=g("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",p=ie(s?"chevron-up":"chevron-down",16,v,2);p?c.appendChild(p):c.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(c),i.append(a,m);let w=g("div","tvw-border-t tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",e.contentBackgroundColor&&(w.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(w.style.color=e.contentTextColor),e.contentPaddingX&&(w.style.paddingLeft=e.contentPaddingX,w.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(w.style.paddingTop=e.contentPaddingY,w.style.paddingBottom=e.contentPaddingY),r.name){let A=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?A.style.color=e.contentTextColor:e.headerTextColor&&(A.style.color=e.headerTextColor),A.textContent=r.name,w.appendChild(A)}if(r.args!==void 0){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Arguments";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=hs(r.args),A.append(x,H),w.appendChild(A)}if(r.chunks&&r.chunks.length){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Activity";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=r.chunks.join(`
16
+ `),A.append(x,H),w.appendChild(A)}if(r.status==="complete"&&r.result!==void 0){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Result";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=hs(r.result),A.append(x,H),w.appendChild(A)}if(r.status==="complete"&&typeof r.duration=="number"){let A=g("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(A.style.color=e.contentTextColor),A.textContent=`Duration: ${r.duration}ms`,w.appendChild(A)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let A=e.toggleTextColor||e.headerTextColor||"currentColor",x=ie(s?"chevron-up":"chevron-down",16,A,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var Ar=(n,t)=>{var y,A,x,H,Y,k,P,L,F,ue,z;let r=n.approval,e=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=g("div",["vanilla-message-bubble","vanilla-approval-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-border","tvw-shadow-sm","tvw-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),e!=null&&e.backgroundColor&&(s.style.backgroundColor=e.backgroundColor),e!=null&&e.borderColor&&(s.style.borderColor=e.borderColor),!r)return s;let i=g("div","tvw-flex tvw-items-start tvw-gap-3 tvw-px-4 tvw-py-3"),a=g("div","tvw-flex-shrink-0 tvw-mt-0.5");a.setAttribute("data-approval-icon","true");let d=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",c=r.status==="approved"?"#16a34a":r.status==="denied"?"#dc2626":r.status==="timeout"?"#ca8a04":(y=e==null?void 0:e.titleColor)!=null?y:"currentColor",v=ie(d,20,c,2);v&&a.appendChild(v);let p=g("div","tvw-flex-1 tvw-min-w-0"),m=g("div","tvw-flex tvw-items-center tvw-gap-2"),w=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary");if(e!=null&&e.titleColor&&(w.style.color=e.titleColor),w.textContent=(A=e==null?void 0:e.title)!=null?A:"Approval Required",m.appendChild(w),!o){let V=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");V.setAttribute("data-approval-status",r.status),r.status==="approved"?(V.className+=" tvw-approval-badge-approved",V.textContent="Approved"):r.status==="denied"?(V.className+=" tvw-approval-badge-denied",V.textContent="Denied"):r.status==="timeout"&&(V.className+=" tvw-approval-badge-timeout",V.textContent="Timeout"),m.appendChild(V)}p.appendChild(m);let C=g("p","tvw-text-sm tvw-mt-0.5 tvw-text-cw-muted");if(e!=null&&e.descriptionColor&&(C.style.color=e.descriptionColor),C.textContent=r.description,p.appendChild(C),r.parameters){let V=g("pre","tvw-mt-2 tvw-text-xs tvw-p-2 tvw-rounded tvw-overflow-x-auto tvw-max-h-32 tvw-bg-cw-container tvw-text-cw-primary");e!=null&&e.parameterBackgroundColor&&(V.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(V.style.color=e.parameterTextColor),V.style.fontSize="0.75rem",V.style.lineHeight="1rem",V.textContent=hs(r.parameters),p.appendChild(V)}if(o){let V=g("div","tvw-flex tvw-gap-2 tvw-mt-2");V.setAttribute("data-approval-buttons","true");let X=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-border-none tvw-cursor-pointer");X.type="button",X.style.backgroundColor=(x=e==null?void 0:e.approveButtonColor)!=null?x:"#16a34a",X.style.color=(H=e==null?void 0:e.approveButtonTextColor)!=null?H:"#ffffff",X.setAttribute("data-approval-action","approve");let _=ie("shield-check",14,(Y=e==null?void 0:e.approveButtonTextColor)!=null?Y:"#ffffff",2);_&&(_.style.marginRight="4px",X.appendChild(_));let Ce=document.createTextNode((k=e==null?void 0:e.approveLabel)!=null?k:"Approve");X.appendChild(Ce);let se=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-cursor-pointer");se.type="button",se.style.backgroundColor=(P=e==null?void 0:e.denyButtonColor)!=null?P:"transparent",se.style.color=(L=e==null?void 0:e.denyButtonTextColor)!=null?L:"#dc2626",se.style.border=`1px solid ${(F=e==null?void 0:e.denyButtonTextColor)!=null?F:"#fca5a5"}`,se.setAttribute("data-approval-action","deny");let G=ie("shield-x",14,(ue=e==null?void 0:e.denyButtonTextColor)!=null?ue:"#dc2626",2);G&&(G.style.marginRight="4px",se.appendChild(G));let U=document.createTextNode((z=e==null?void 0:e.denyLabel)!=null?z:"Deny");se.appendChild(U),V.append(X,se),p.appendChild(V)}return i.append(a,p),s.appendChild(i),s};var aa=n=>{let t=[];return{buttons:t,render:(e,o,s,i,a)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:o?o.getMessages():[]).some(w=>w.role==="user"))return;let v=document.createDocumentFragment(),p=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';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(w=>{let C=g("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");C.type="button",C.textContent=w,C.disabled=p,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),t.push(C)}),n.appendChild(v)}}};var xs=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let e of r)this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(e.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ss=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let e=indexedDB.open(this.dbName,1);e.onupgradeneeded=()=>{let o=e.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},e.onsuccess=()=>{this.db=e.result,t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(i.error)}}catch(e){r(e)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let e=indexedDB.deleteDatabase(this.dbName);e.onsuccess=()=>{t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}};function Yn(n,t){t&&t.split(/\s+/).forEach(r=>r&&n.classList.add(r))}var ll={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"}},cl={bg:"#f3f4f6",text:"#4b5563"},dl=["flowName","stepName","reasoningText","text","name","tool","toolName"],ul=100;function pl(n,t){let r={...ll,...t};if(r[n])return r[n];for(let e of Object.keys(r))if(e.endsWith("_")&&n.startsWith(e))return r[e];return cl}function gl(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function hl(n){let t=new Date(n),r=String(t.getHours()).padStart(2,"0"),e=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${e}:${o}.${s}`}function ml(n,t){try{let r=JSON.parse(n);if(typeof r!="object"||r===null)return null;for(let e of t){let o=e.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 fl(n){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(n):new Promise(r=>{let e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),r()})}function vl(n){let t;try{t=JSON.parse(n.payload)}catch{t=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:t},null,2)}function wl(n,t,r){let e,o;try{o=JSON.parse(n.payload),e=JSON.stringify(o,null,2)}catch{o=n.payload,e=n.payload}let s=t.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:n,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=g("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=g("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return d.textContent=e,a.appendChild(d),a}}function Er(n,t,r,e,o,s,i,a){var m;let d=o.has(n.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");Yn(c,(m=e.classNames)==null?void 0:m.eventRow);let v=i.find(w=>w.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let w=v.renderEventStreamRow({event:n,index:t,config:a,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(w)return c.appendChild(w),c}return c.appendChild(p()),c;function p(){var _,Ce;let w=g("div",""),C=g("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",n.id);let y=g("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),A=ie(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&y.appendChild(A);let x=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),H=(_=e.timestampFormat)!=null?_:"relative";x.textContent=H==="relative"?gl(n.timestamp,r):hl(n.timestamp);let Y=null;e.showSequenceNumbers!==!1&&(Y=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),Y.textContent=String(t+1));let k=pl(n.type,e.badgeColors),P=g("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");P.style.backgroundColor=k.bg,P.style.color=k.text,P.style.borderColor=k.text+"50",P.textContent=n.type;let L=(Ce=e.descriptionFields)!=null?Ce:dl,F=ml(n.payload,L),ue=null;F&&(ue=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),ue.textContent=F);let z=g("div","tvw-flex-1 tvw-min-w-0"),V=g("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),X=ie("clipboard","12px","currentColor",1.5);return X&&V.appendChild(X),V.addEventListener("click",async se=>{se.stopPropagation(),await fl(vl(n)),V.innerHTML="";let G=ie("check","12px","currentColor",1.5);G&&V.appendChild(G),setTimeout(()=>{V.innerHTML="";let U=ie("clipboard","12px","currentColor",1.5);U&&V.appendChild(U)},1500)}),C.appendChild(y),C.appendChild(x),Y&&C.appendChild(Y),C.appendChild(P),ue&&C.appendChild(ue),C.appendChild(z),C.appendChild(V),w.appendChild(C),d&&w.appendChild(wl(n,i,a)),w}}function la(n){var c,v;let{buffer:t,getFullHistory:r,onClose:e,config:o,plugins:s=[]}=n,i=(v=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?v:{},a=s.find(p=>p.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let p=a.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>d().element,onClose:e});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=i.classNames,m=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");Yn(m,p==null?void 0:p.panel);let w=[],C="",y="",A=null,x=[],H={},Y=0,k=!1,P=0,L=0,F=!1,ue=null,z=!1,V=0,X=new Set,_=new Map,Ce="",se="",G=null,U,N,ee,fe,Fe;function Mt(){let O=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),Q=g("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");Yn(Q,p==null?void 0:p.headerBar);let re=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");re.textContent="Events",U=g("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"),U.textContent="0";let Ne=g("div","tvw-flex-1");N=g("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 oe=g("option","");oe.value="",oe.textContent="All events",N.appendChild(oe),ee=g("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"),ee.type="button",ee.title="Copy All";let Ge=ie("clipboard-copy","12px","currentColor",1.5);Ge&&ee.appendChild(Ge);let pe=g("span","tvw-text-xs");pe.textContent="Copy All",ee.appendChild(pe),Q.appendChild(re),Q.appendChild(U),Q.appendChild(Ne),Q.appendChild(N),Q.appendChild(ee);let D=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");Yn(D,p==null?void 0:p.searchBar);let Ee=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),st=g("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Ee&&st.appendChild(Ee),fe=g("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"),Yn(fe,p==null?void 0:p.searchInput),fe.type="text",fe.placeholder="Search event payloads...",Fe=g("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"),Fe.type="button",Fe.style.display="none";let rt=ie("x","12px","currentColor",2);return rt&&Fe.appendChild(rt),D.appendChild(st),D.appendChild(fe),D.appendChild(Fe),O.appendChild(Q),O.appendChild(D),O}let gt,ft=s.find(O=>O.renderEventStreamToolbar);if(ft!=null&&ft.renderEventStreamToolbar&&o){let O=ft.renderEventStreamToolbar({config:o,defaultRenderer:()=>Mt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Q=>{C=Q,ct(),Ct()},onSearchChange:Q=>{y=Q,ct(),Ct()}});gt=O!=null?O:Mt()}else gt=Mt();let Ht=g("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");Ht.style.display="none";let je=g("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ne=g("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ne.style.height="100%";let xe=g("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");Yn(xe,p==null?void 0:p.scrollIndicator),xe.style.display="none";let He=ie("arrow-down","12px","currentColor",2);He&&xe.appendChild(He);let $e=g("span","");xe.appendChild($e);let ze=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");ze.style.display="none",je.appendChild(ne),je.appendChild(ze),je.appendChild(xe),m.setAttribute("tabindex","0"),m.appendChild(gt),m.appendChild(Ht),m.appendChild(je);function Ot(){let O=t.getAll(),Q={};for(let pe of O)Q[pe.type]=(Q[pe.type]||0)+1;let re=Object.keys(Q).sort(),Ne=re.length!==x.length||!re.every((pe,D)=>pe===x[D]),oe=!Ne&&re.some(pe=>Q[pe]!==H[pe]),Xe=O.length!==Object.values(H).reduce((pe,D)=>pe+D,0);if(!Ne&&!oe&&!Xe||(x=re,H=Q,!N))return;let Ge=N.value;if(N.options[0].textContent="All events",Ne){for(;N.options.length>1;)N.remove(1);for(let pe of re){let D=g("option","");D.value=pe,D.textContent=`${pe} (${Q[pe]||0})`,N.appendChild(D)}Ge&&re.includes(Ge)?N.value=Ge:Ge&&(N.value="",C="")}else for(let pe=1;pe<N.options.length;pe++){let D=N.options[pe];D.textContent=`${D.value} (${Q[D.value]||0})`}}function he(){let O=t.getAll();if(C&&(O=O.filter(Q=>Q.type===C)),y){let Q=y.toLowerCase();O=O.filter(re=>re.type.toLowerCase().includes(Q)||re.payload.toLowerCase().includes(Q))}return O}function Z(){return C!==""||y!==""}function ct(){Y=0,P=0,k=!1,xe.style.display="none"}function bt(O){X.has(O)?X.delete(O):X.add(O),G=O;let Q=ne.scrollTop,re=k;z=!0,k=!0,Ct(),ne.scrollTop=Q,k=re,z=!1}function kt(){return ne.scrollHeight-ne.scrollTop-ne.clientHeight<=50}function Ct(){L=Date.now(),F=!1,Ot();let O=t.getEvictedCount();O>0?(Ht.textContent=`${O.toLocaleString()} older events truncated`,Ht.style.display=""):Ht.style.display="none",w=he();let Q=w.length,re=t.getSize()>0;U&&(U.textContent=String(t.getSize())),Q===0&&re&&Z()?(ze.textContent=y?`No events matching '${y}'`:"No events matching filter",ze.style.display="",ne.style.display="none"):(ze.style.display="none",ne.style.display=""),ee&&(ee.title=Z()?`Copy Filtered (${Q})`:"Copy All"),k&&Q>Y&&(P+=Q-Y,$e.textContent=`${P} new event${P===1?"":"s"}`,xe.style.display=""),Y=Q;let Ne=t.getAll(),oe=Ne.length>0?Ne[0].timestamp:0,Xe=new Set(w.map(D=>D.id));for(let D of X)Xe.has(D)||X.delete(D);let Ge=C!==Ce||y!==se,pe=_.size===0&&w.length>0;if(Ge||pe||w.length===0){ne.innerHTML="",_.clear();let D=document.createDocumentFragment();for(let Ee=0;Ee<w.length;Ee++){let st=Er(w[Ee],Ee,oe,i,X,bt,s,o);_.set(w[Ee].id,st),D.appendChild(st)}ne.appendChild(D),Ce=C,se=y,G=null}else{if(G!==null){let Ee=_.get(G);if(Ee&&Ee.parentNode===ne){let st=w.findIndex(rt=>rt.id===G);if(st>=0){let rt=Er(w[st],st,oe,i,X,bt,s,o);ne.insertBefore(rt,Ee),Ee.remove(),_.set(G,rt)}}G=null}let D=new Set(w.map(Ee=>Ee.id));for(let[Ee,st]of _)D.has(Ee)||(st.remove(),_.delete(Ee));for(let Ee=0;Ee<w.length;Ee++){let st=w[Ee];if(!_.has(st.id)){let rt=Er(st,Ee,oe,i,X,bt,s,o);_.set(st.id,rt),ne.appendChild(rt)}}}k||(ne.scrollTop=ne.scrollHeight)}function Kt(){if(Date.now()-L>=ul){ue!==null&&(cancelAnimationFrame(ue),ue=null),Ct();return}F||(F=!0,ue=requestAnimationFrame(()=>{ue=null,Ct()}))}let te=(O,Q)=>{if(!ee)return;ee.innerHTML="";let re=ie(O,"12px","currentColor",1.5);re&&ee.appendChild(re);let Ne=g("span","tvw-text-xs");Ne.textContent="Copy All",ee.appendChild(Ne),setTimeout(()=>{ee.innerHTML="";let oe=ie("clipboard-copy","12px","currentColor",1.5);oe&&ee.appendChild(oe);let Xe=g("span","tvw-text-xs");Xe.textContent="Copy All",ee.appendChild(Xe),ee.disabled=!1},Q)},Pe=async()=>{if(ee){ee.disabled=!0;try{let O;Z()?O=w:r?(O=await r(),O.length===0&&(O=t.getAll())):O=t.getAll();let Q=O.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(Q,null,2)),te("check",1500)}catch{te("x",1500)}}},xt=()=>{N&&(C=N.value,ct(),Ct())},ve=()=>{!fe||!Fe||(Fe.style.display=fe.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{y=fe.value,ct(),Ct()},150))},Se=()=>{!fe||!Fe||(fe.value="",y="",Fe.style.display="none",A&&clearTimeout(A),ct(),Ct())},Je=()=>{if(z)return;let O=ne.scrollTop,Q=O>V;V=O,kt()&&Q?(k=!1,P=0,xe.style.display="none"):kt()||(k=!0)},Bt=O=>{O.deltaY<0&&(k=!0)},It=()=>{ne.scrollTop=ne.scrollHeight,k=!1,P=0,xe.style.display="none"},qt=O=>{let Q=O.target;if(!Q||Q.closest("button"))return;let re=Q.closest("[data-event-id]");if(!re)return;let Ne=re.getAttribute("data-event-id");Ne&&bt(Ne)},I=O=>{if((O.metaKey||O.ctrlKey)&&O.key==="f"){O.preventDefault(),fe==null||fe.focus(),fe==null||fe.select();return}O.key==="Escape"&&(fe&&document.activeElement===fe?(Se(),fe.blur(),m.focus()):e&&e())};ee&&ee.addEventListener("click",Pe),N&&N.addEventListener("change",xt),fe&&fe.addEventListener("input",ve),Fe&&Fe.addEventListener("click",Se),ne.addEventListener("scroll",Je),ne.addEventListener("wheel",Bt,{passive:!0}),ne.addEventListener("click",qt),xe.addEventListener("click",It),m.addEventListener("keydown",I);function nt(){A&&clearTimeout(A),ue!==null&&(cancelAnimationFrame(ue),ue=null),F=!1,_.clear(),ee&&ee.removeEventListener("click",Pe),N&&N.removeEventListener("change",xt),fe&&fe.removeEventListener("input",ve),Fe&&Fe.removeEventListener("click",Se),ne.removeEventListener("scroll",Je),ne.removeEventListener("wheel",Bt),ne.removeEventListener("click",qt),xe.removeEventListener("click",It),m.removeEventListener("keydown",I)}return{element:m,update:Kt,destroy:nt}}}var ca={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"}},Tr=(n,t,r,e)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,y,A;if(s.dataset.enhanced==="true")return;let i=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let a=(y=ca[i])!=null?y:ca.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=g("div","tvw-space-y-1"),c=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,d.appendChild(c),a.description){let x=g("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 L,F;let H=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");H.htmlFor=`${t.id}-${i}-${x.name}`;let Y=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");Y.textContent=x.label,H.appendChild(Y);let k=(L=x.type)!=null?L:"text",P;k==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=k),P.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",P.id=`${t.id}-${i}-${x.name}`,P.name=x.name,P.placeholder=(F=x.placeholder)!=null?F:"",x.required&&(P.required=!0),H.appendChild(P),v.appendChild(H)});let p=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(A=a.submitLabel)!=null?A:"Submit",p.appendChild(m),p.appendChild(w),v.appendChild(p),s.replaceChildren(d,v),v.addEventListener("submit",async x=>{var P,L;x.preventDefault();let H=(P=r.formEndpoint)!=null?P:"/form",Y=new FormData(v),k={};Y.forEach((F,ue)=>{k[ue]=F}),k.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let F=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!F.ok)throw new Error(`Form submission failed (${F.status})`);let ue=await F.json();m.textContent=(L=ue.message)!=null?L:"Thanks! We'll be in touch soon.",ue.success&&ue.nextPrompt&&await e.sendMessage(String(ue.nextPrompt))}catch(F){m.textContent=F instanceof Error?F.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Mr=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var e;let r=this.plugins.get(t);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let e=new Set(t.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...t].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Gs=new Mr;var da={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"},ua={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"},lt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:da,darkTheme:ua,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 kr(n){var t,r,e,o,s,i,a,d,c,v,p,m,w,C,y,A,x,H,Y;return n?{...lt,...n,theme:{...lt.theme,...n.theme},darkTheme:{...lt.darkTheme,...n.darkTheme},launcher:{...lt.launcher,...n.launcher,clearChat:{...(t=lt.launcher)==null?void 0:t.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...lt.copy,...n.copy},sendButton:{...lt.sendButton,...n.sendButton},statusIndicator:{...lt.statusIndicator,...n.statusIndicator},voiceRecognition:{...lt.voiceRecognition,...n.voiceRecognition},features:{...lt.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:lt.suggestionChips,suggestionChipsConfig:{...lt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...lt.layout,...n.layout,header:{...(o=lt.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=lt.layout)==null?void 0:i.messages,...(a=n.layout)==null?void 0:a.messages,avatar:{...(c=(d=lt.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(p=(v=n.layout)==null?void 0:v.messages)==null?void 0:p.avatar},timestamp:{...(w=(m=lt.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(y=(C=n.layout)==null?void 0:C.messages)==null?void 0:y.timestamp}},slots:{...(A=lt.layout)==null?void 0:A.slots,...(x=n.layout)==null?void 0:x.slots}},markdown:{...lt.markdown,...n.markdown,options:{...(H=lt.markdown)==null?void 0:H.options,...(Y=n.markdown)==null?void 0:Y.options}},messageActions:{...lt.messageActions,...n.messageActions}}:lt}var pa=()=>{let n=new Map,t=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:t,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var yl=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},bl=n=>{let t=n.trim(),r=t.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<t.length;o+=1){let s=t[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return t.slice(r,o+1)}return null},Zs=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=yl(n),r=bl(t);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},Ir=n=>typeof n=="string"?n:n==null?"":String(n),Xn={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Ir(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,e=Ir(r.element);if(e&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Ir(r.text)}}},ga=n=>Array.isArray(n)?n.map(t=>String(t)):[],Qs=n=>{let t=new Set(ga(n.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ga(n.getSessionMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(t);n.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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?n.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;t.add(s.message.id),e();let d={action:a,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let v=()=>{n.emit("action:resubmit",d)},p=c(a,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:v});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var Cl=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},xl=n=>n.map(t=>({...t,streaming:!1})),Lr=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Cl(r.getItem(n)):null},save:r=>{let e=t();if(e)try{let o={...r,messages:r.messages?xl(r.messages):void 0};e.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=t();if(r)try{r.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Wr=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,e])=>{this.register(r,e)})}},As=new Wr;import{parse as Sl,STR as Al,OBJ as El}from"partial-json";function Tl(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function Ml(n,t){if(!Tl(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:t}}function Pr(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n;try{let o=Sl(r,Al|El),s=Ml(o,r);s&&(n=s)}catch{}return t=r.length,n},reset:()=>{n=null,t=0}}}function kl(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Rr(n,t){let{config:r,message:e,onPropsUpdate:o}=t,s=As.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:e,config:r,updateProps:a=>{o&&o(a)}};try{return s(n.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,a),null}}function Il(){let n=Pr();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Hr(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Br(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var Ll=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fr(n){let{onSubmit:t,onDismiss:r,title:e="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:c=Ll}=n,v=document.createElement("div");v.className="tvw-feedback-container tvw-feedback-csat",v.setAttribute("role","dialog"),v.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=e,w.appendChild(C);let y=document.createElement("p");y.className="tvw-feedback-subtitle",y.textContent=o,w.appendChild(y),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 L=1;L<=5;L++){let F=document.createElement("button");F.type="button",F.className="tvw-feedback-rating-btn tvw-feedback-star-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${c[L-1]}`),F.title=c[L-1],F.dataset.rating=String(L),F.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
- `,B.addEventListener("click",()=>{d=T,x.forEach((le,z)=>{let U=z<T;le.classList.toggle("selected",U),le.setAttribute("aria-checked",z===T-1?"true":"false")})}),x.push(B),S.appendChild(B)}m.appendChild(S);let k=null;if(u){let T=document.createElement("div");T.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),T.appendChild(k),m.appendChild(T)}let J=document.createElement("div");J.className="tvw-feedback-actions";let E=document.createElement("button");E.type="button",E.className="tvw-feedback-btn tvw-feedback-btn-skip",E.textContent=a,E.addEventListener("click",()=>{r==null||r(),v.remove()});let I=document.createElement("button");return I.type="button",I.className="tvw-feedback-btn tvw-feedback-btn-submit",I.textContent=i,I.addEventListener("click",async()=>{if(d===null){S.classList.add("tvw-feedback-shake"),setTimeout(()=>S.classList.remove("tvw-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let T=(k==null?void 0:k.value.trim())||void 0;await t(d,T),v.remove()}catch(T){I.disabled=!1,I.textContent=i,console.error("[CSAT Feedback] Failed to submit:",T)}}),J.appendChild(E),J.appendChild(I),m.appendChild(J),v.appendChild(m),v}function Br(n){let{onSubmit:t,onDismiss:r,title:e="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:u=!0,lowLabel:c="Not likely",highLabel:v="Very likely"}=n,d=document.createElement("div");d.className="tvw-feedback-container tvw-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let b=document.createElement("div");b.className="tvw-feedback-header";let y=document.createElement("h3");y.className="tvw-feedback-title",y.textContent=e,b.appendChild(y);let S=document.createElement("p");S.className="tvw-feedback-subtitle",S.textContent=o,b.appendChild(S),w.appendChild(b);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 k=document.createElement("div");k.className="tvw-feedback-labels";let J=document.createElement("span");J.className="tvw-feedback-label-low",J.textContent=c;let E=document.createElement("span");E.className="tvw-feedback-label-high",E.textContent=v,k.appendChild(J),k.appendChild(E);let I=document.createElement("div");I.className="tvw-feedback-numbers";let T=[];for(let K=0;K<=10;K++){let j=document.createElement("button");j.type="button",j.className="tvw-feedback-rating-btn tvw-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${K} out of 10`),j.textContent=String(K),j.dataset.rating=String(K),K<=6?j.classList.add("tvw-feedback-detractor"):K<=8?j.classList.add("tvw-feedback-passive"):j.classList.add("tvw-feedback-promoter"),j.addEventListener("click",()=>{m=K,T.forEach((ye,se)=>{ye.classList.toggle("selected",se===K),ye.setAttribute("aria-checked",se===K?"true":"false")})}),T.push(j),I.appendChild(j)}x.appendChild(k),x.appendChild(I),w.appendChild(x);let B=null;if(u){let K=document.createElement("div");K.className="tvw-feedback-comment-container",B=document.createElement("textarea"),B.className="tvw-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),K.appendChild(B),w.appendChild(K)}let le=document.createElement("div");le.className="tvw-feedback-actions";let z=document.createElement("button");z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-skip",z.textContent=a,z.addEventListener("click",()=>{r==null||r(),d.remove()});let U=document.createElement("button");return U.type="button",U.className="tvw-feedback-btn tvw-feedback-btn-submit",U.textContent=i,U.addEventListener("click",async()=>{if(m===null){I.classList.add("tvw-feedback-shake"),setTimeout(()=>I.classList.remove("tvw-feedback-shake"),500);return}U.disabled=!0,U.textContent="Submitting...";try{let K=(B==null?void 0:B.value.trim())||void 0;await t(m,K),d.remove()}catch(K){U.disabled=!1,U.textContent=i,console.error("[NPS Feedback] Failed to submit:",K)}}),le.appendChild(z),le.appendChild(U),w.appendChild(le),d.appendChild(w),d}var Kn="persona-chat-history",Al=30*1e3,El={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Tl(n){var e,o,s;if(!n)return[];let t=[],r=Array.from((e=n.items)!=null?e:[]);for(let i of r){if(i.kind!=="file"||!i.type.startsWith("image/"))continue;let a=i.getAsFile();if(!a)continue;if(a.name){t.push(a);continue}let u=(o=El[a.type])!=null?o:"png";t.push(new File([a],`clipboard-image-${Date.now()}.${u}`,{type:a.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let i of Array.from((s=n.files)!=null?s:[]))i.type.startsWith("image/")&&t.push(i);return t}function Ml(n){var t,r,e,o,s,i,a,u,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=n.storage)!=null?t:"session",keyPrefix:(r=n.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(e=n.persist)==null?void 0:e.openState)!=null?o:!0,voiceState:(i=(s=n.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(u=(a=n.persist)==null?void 0:a.focusInput)!=null?u:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function kl(n){try{let t=n==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Fr=n=>!n||typeof n!="object"?{}:{...n},aa=n=>n.map(t=>({...t,streaming:!1})),la=(n,t,r)=>{let e=n!=null&&n.markdown?js(n.markdown):null;return o=>{var a,u,c;let s=(a=o.text)!=null?a:"",i=(u=o.message.rawContent)!=null?u:null;if(t){let v=t.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 n!=null&&n.postprocessMessage?n.postprocessMessage({...o,text:s,raw:(c=i!=null?i:o.text)!=null?c:""}):e?e(s):cr(s)}},$r=(n,t,r)=>{var as,ls,cs,ds,us,V,Ie,De,lt,mt,At,rt,h,We,$,C,L,ae,Ae,ze,Lt,ot,Ct,ht,Oe,_e,ut,Ve,xt,Dt,Xt,Dr,jr,_r,Vr;n.id&&n.id!=="persona-root"&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.id="persona-root";let e=Tr(t),o=Ys.getForInstance(e.plugins);e.components&&Ts.registerAll(e.components);let s=oa(),i=(as=e.storageAdapter)!=null?as:kr(),a={},u=null,c=l=>{if(e.onStateLoaded)try{return e.onStateLoaded(l)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")u=l.then(p=>{let f=p!=null?p:{messages:[],metadata:{}};return c(f)});else{let p=l!=null?l:{messages:[],metadata:{}},f=c(p);f.metadata&&(a=Fr(f.metadata)),(ls=f.messages)!=null&&ls.length&&(e={...e,initialMessages:f.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(e.onStateLoaded)try{let l=c({messages:[],metadata:{}});(cs=l.messages)!=null&&cs.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,d=l=>{var f;a=(f=l({...a}))!=null?f:{},Qn()},m=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Xs],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Jn.message,Jn.messageAndClick],b=Gs({parsers:m,handlers:w,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let y=(us=(ds=e.launcher)==null?void 0:ds.enabled)!=null?us:!0,S=(Ie=(V=e.launcher)==null?void 0:V.autoExpand)!=null?Ie:!1,x=(De=e.autoFocusInput)!=null?De:!1,k=S,J=y,E=(mt=(lt=e.layout)==null?void 0:lt.header)==null?void 0:mt.layout,I=y?S:!0,T=!1,B=null,le=()=>{T=!0,B&&clearTimeout(B),B=setTimeout(()=>{T&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),T=!1)},1e4)},z=la(e,b,le),U=(rt=(At=e.features)==null?void 0:At.showReasoning)!=null?rt:!0,K=(We=(h=e.features)==null?void 0:h.showToolCalls)!=null?We:!0,j=(C=($=e.features)==null?void 0:$.showEventStreamToggle)!=null?C:!1,se=`${(ae=typeof e.persistState=="object"?(L=e.persistState)==null?void 0:L.keyPrefix:void 0)!=null?ae:"persona-"}event-stream`,Y=j?new Es(se):null,_=(Lt=(ze=(Ae=e.features)==null?void 0:Ae.eventStream)==null?void 0:ze.maxEvents)!=null?Lt:2e3,O=j?new As(_,Y):null,Q=null,ue=!1,Be=null,Et=0;Y==null||Y.open().then(()=>O==null?void 0:O.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let dt={onCopy:l=>{var p,f;s.emit("message:copy",l),M!=null&&M.isClientTokenMode()&&M.submitMessageFeedback(l.id,"copy").catch(A=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(f=(p=e.messageActions)==null?void 0:p.onCopy)==null||f.call(p,l)},onFeedback:l=>{var p,f;s.emit("message:feedback",l),M!=null&&M.isClientTokenMode()&&M.submitMessageFeedback(l.messageId,l.type).catch(A=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(f=(p=e.messageActions)==null?void 0:p.onFeedback)==null||f.call(p,l)}},gt=(ot=e.statusIndicator)!=null?ot:{},Ht=l=>{var p,f,A,H;return l==="idle"?(p=gt.idleText)!=null?p:Rt.idle:l==="connecting"?(f=gt.connectingText)!=null?f:Rt.connecting:l==="connected"?(A=gt.connectedText)!=null?A:Rt.connected:l==="error"?(H=gt.errorText)!=null?H:Rt.error:Rt[l]},{wrapper:Ne,panel:ne}=Ji(e),be=Ki(e,y),{container:Re,body:Fe,messagesWrapper:Ue,suggestions:Nt,textarea:de,sendButton:X,sendButtonWrapper:at,composerForm:vt,statusText:Tt,introTitle:yt,introSubtitle:Kt,closeButton:ee,iconHolder:Le,headerTitle:bt,headerSubtitle:pe,header:Ce,footer:qe,actionsRow:Bt,leftActions:Mt,rightActions:Vt}=be,F=be.micButton,Qe=be.micButtonWrapper,N=be.attachmentButton,G=be.attachmentButtonWrapper,re=be.attachmentInput,$e=be.attachmentPreviewsContainer,oe=null;(Ct=e.attachments)!=null&&Ct.enabled&&re&&$e&&(oe=jn.fromConfig(e.attachments),oe.setPreviewsContainer($e),re.addEventListener("change",l=>{let p=l.target;oe==null||oe.handleFileSelect(p.files),p.value=""}));let Je=o.find(l=>l.renderHeader);if(Je!=null&&Je.renderHeader){let l=Je.renderHeader({config:e,defaultRenderer:()=>{let p=yn({config:e,showClose:y});return _n(Re,p,e),p.header},onClose:()=>nt(!1,"user")});if(l){let p=Re.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(l),Ce=l)}}let Ke=()=>{var p,f,A,H;if(!O)return;if(ue=!0,!Q&&O&&(Q=ta({buffer:O,getFullHistory:()=>O.getAllFromStore(),onClose:()=>ce(),config:e,plugins:o})),Q&&(Fe.style.display="none",(p=qe.parentNode)==null||p.insertBefore(Q.element,qe),Q.update()),D){D.classList.remove("tvw-text-cw-muted"),D.classList.add("tvw-text-cw-accent"),D.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let P=(H=(A=(f=e.features)==null?void 0:f.eventStream)==null?void 0:A.classNames)==null?void 0:H.toggleButtonActive;P&&P.split(/\s+/).forEach(q=>q&&D.classList.add(q))}let l=()=>{if(!ue)return;let P=Date.now();P-Et>=200&&(Q==null||Q.update(),Et=P),Be=requestAnimationFrame(l)};Et=0,Be=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},ce=()=>{var l,p,f;if(ue){if(ue=!1,Q&&Q.element.remove(),Fe.style.display="",D){D.classList.remove("tvw-text-cw-accent"),D.classList.add("tvw-text-cw-muted"),D.style.boxShadow="";let A=(f=(p=(l=e.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:f.toggleButtonActive;A&&A.split(/\s+/).forEach(H=>H&&D.classList.remove(H))}Be!==null&&(cancelAnimationFrame(Be),Be=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},D=null;if(j){let l=(Oe=(ht=e.features)==null?void 0:ht.eventStream)==null?void 0:Oe.classNames,p="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:"");D=g("button",p),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let f=ie("activity","18px","currentColor",1.5);f&&D.appendChild(f);let A=be.clearChatButtonWrapper,H=be.closeButtonWrapper,P=A||H;P&&P.parentNode===Ce?Ce.insertBefore(D,P):Ce.appendChild(D),D.addEventListener("click",()=>{ue?ce():Ke()})}let Se=o.find(l=>l.renderComposer);if(Se!=null&&Se.renderComposer){let l=Se.renderComposer({config:e,defaultRenderer:()=>xs({config:e}).footer,onSubmit:p=>{M&&!M.isStreaming()&&M.sendMessage(p)},disabled:!1});l&&(qe.replaceWith(l),qe=l)}(()=>{var A,H;let l=(H=(A=e.layout)==null?void 0:A.slots)!=null?H:{},p=P=>{switch(P){case"body-top":return Re.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Ue;case"footer-top":return Nt;case"composer":return vt;case"footer-bottom":return Tt;default:return null}},f=(P,q)=>{var ge;switch(P){case"header-left":case"header-center":case"header-right":if(P==="header-left")Ce.insertBefore(q,Ce.firstChild);else if(P==="header-right")Ce.appendChild(q);else{let me=Ce.querySelector(".tvw-flex-col");me?(ge=me.parentNode)==null||ge.insertBefore(q,me.nextSibling):Ce.appendChild(q)}break;case"body-top":{let me=Fe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");me?me.replaceWith(q):Fe.insertBefore(q,Fe.firstChild);break}case"body-bottom":Fe.appendChild(q);break;case"footer-top":Nt.replaceWith(q);break;case"footer-bottom":Tt.replaceWith(q);break;default:break}};for(let[P,q]of Object.entries(l))if(q)try{let ge=q({config:e,defaultContent:()=>p(P)});ge&&f(P,ge)}catch(ge){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${P}":`,ge)}})();let tt=l=>{let f=l.target.closest('button[data-expand-header="true"]');if(!f)return;let A=f.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let H=A.getAttribute("data-message-id");if(!H)return;let P=f.getAttribute("data-bubble-type");P==="reasoning"?(Un.has(H)?Un.delete(H):Un.add(H),Zi(H,A)):P==="tool"&&(qn.has(H)?qn.delete(H):qn.add(H),Qi(H,A,e))};Ue.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),tt(l))}),Ue.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),tt(l))});let Yt=new Map;Ue.addEventListener("click",l=>{var q;let f=l.target.closest(".tvw-message-action-btn[data-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let A=f.closest("[data-actions-for]");if(!A)return;let H=A.getAttribute("data-actions-for");if(!H)return;let P=f.getAttribute("data-action");if(P==="copy"){let me=M.getMessages().find(fe=>fe.id===H);if(me&&dt.onCopy){let fe=me.content||"";navigator.clipboard.writeText(fe).then(()=>{f.classList.add("tvw-message-action-success");let xe=ie("check",14,"currentColor",2);xe&&(f.innerHTML="",f.appendChild(xe)),setTimeout(()=>{f.classList.remove("tvw-message-action-success");let Te=ie("copy",14,"currentColor",2);Te&&(f.innerHTML="",f.appendChild(Te))},2e3)}).catch(xe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",xe)}),dt.onCopy(me)}}else if(P==="upvote"||P==="downvote")if(((q=Yt.get(H))!=null?q:null)===P)Yt.delete(H),f.classList.remove("tvw-message-action-active");else{let fe=P==="upvote"?"downvote":"upvote",xe=A.querySelector(`[data-action="${fe}"]`);xe&&xe.classList.remove("tvw-message-action-active"),Yt.set(H,P),f.classList.add("tvw-message-action-active");let te=M.getMessages().find(W=>W.id===H);te&&dt.onFeedback&&dt.onFeedback({type:P,messageId:te.id,message:te})}}),Ue.addEventListener("click",l=>{let f=l.target.closest("button[data-approval-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let A=f.closest(".vanilla-approval-bubble");if(!A)return;let H=A.getAttribute("data-message-id");if(!H)return;let P=f.getAttribute("data-approval-action");if(!P)return;let q=P==="approve"?"approved":"denied",me=M.getMessages().find(xe=>xe.id===H);if(!(me!=null&&me.approval))return;let fe=A.querySelector("[data-approval-buttons]");fe&&fe.querySelectorAll("button").forEach(Te=>{Te.disabled=!0,Te.style.opacity="0.5",Te.style.cursor="not-allowed"}),M.resolveApproval(me.approval,q)}),ne.appendChild(Re),n.appendChild(Ne);let Gt=()=>{var he,we,st,Pe,ft,Pt,Z,je,rn,jt,tn,Mn,Os,ir,ar,pt;let l=(we=(he=e.launcher)==null?void 0:he.sidebarMode)!=null?we:!1,p=l||((Pe=(st=e.launcher)==null?void 0:st.fullHeight)!=null?Pe:!1),f=(ft=e.theme)!=null?ft:{},A=(Z=(Pt=e.launcher)==null?void 0:Pt.position)!=null?Z:"bottom-left",H=A==="bottom-left"||A==="top-left",P=l?"none":"1px solid var(--tvw-cw-border)",q=l?H?"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)",ge=l?"0":"16px",me=(je=f.panelBorder)!=null?je:P,fe=(rn=f.panelShadow)!=null?rn:q,xe=(jt=f.panelBorderRadius)!=null?jt:ge;n.style.cssText="",Ne.style.cssText="",ne.style.cssText="",Re.style.cssText="",Fe.style.cssText="",qe.style.cssText="";let Te=(Mn=(tn=e==null?void 0:e.launcher)==null?void 0:tn.width)!=null?Mn:e==null?void 0:e.launcherWidth,te=Te!=null?Te:"min(400px, calc(100vw - 24px))";l||(ne.style.width=te,ne.style.maxWidth=te),ne.style.boxShadow=fe,ne.style.borderRadius=xe,Re.style.border=me,Re.style.borderRadius=xe;let W=((Os=e.launcher)==null?void 0:Os.enabled)===!1;if(p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",Ne.style.display="flex",Ne.style.flexDirection="column",Ne.style.flex="1 1 0%",Ne.style.minHeight="0",Ne.style.maxHeight="100%",Ne.style.height="100%",W&&(Ne.style.overflow="hidden"),ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.height="100%",ne.style.overflow="hidden",Re.style.display="flex",Re.style.flexDirection="column",Re.style.flex="1 1 0%",Re.style.minHeight="0",Re.style.maxHeight="100%",Re.style.overflow="hidden",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.overflowY="auto",qe.style.flexShrink="0"),Ne.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&&!W&&((ir=nn[A])!=null?ir:nn["bottom-right"]).split(" ").forEach($n=>Ne.classList.add($n)),l){let Fn=(pt=(ar=e.launcher)==null?void 0:ar.sidebarWidth)!=null?pt:"420px";Ne.style.cssText=`
20
+ `,F.addEventListener("click",()=>{p=L,x.forEach((ue,z)=>{let V=z<L;ue.classList.toggle("selected",V),ue.setAttribute("aria-checked",z===L-1?"true":"false")})}),x.push(F),A.appendChild(F)}m.appendChild(A);let H=null;if(d){let L=document.createElement("div");L.className="tvw-feedback-comment-container",H=document.createElement("textarea"),H.className="tvw-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),L.appendChild(H),m.appendChild(L)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let k=document.createElement("button");k.type="button",k.className="tvw-feedback-btn tvw-feedback-btn-skip",k.textContent=a,k.addEventListener("click",()=>{r==null||r(),v.remove()});let P=document.createElement("button");return P.type="button",P.className="tvw-feedback-btn tvw-feedback-btn-submit",P.textContent=i,P.addEventListener("click",async()=>{if(p===null){A.classList.add("tvw-feedback-shake"),setTimeout(()=>A.classList.remove("tvw-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let L=(H==null?void 0:H.value.trim())||void 0;await t(p,L),v.remove()}catch(L){P.disabled=!1,P.textContent=i,console.error("[CSAT Feedback] Failed to submit:",L)}}),Y.appendChild(k),Y.appendChild(P),m.appendChild(Y),v.appendChild(m),v}function $r(n){let{onSubmit:t,onDismiss:r,title:e="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:c="Not likely",highLabel:v="Very likely"}=n,p=document.createElement("div");p.className="tvw-feedback-container tvw-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let y=document.createElement("h3");y.className="tvw-feedback-title",y.textContent=e,C.appendChild(y);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 H=document.createElement("div");H.className="tvw-feedback-labels";let Y=document.createElement("span");Y.className="tvw-feedback-label-low",Y.textContent=c;let k=document.createElement("span");k.className="tvw-feedback-label-high",k.textContent=v,H.appendChild(Y),H.appendChild(k);let P=document.createElement("div");P.className="tvw-feedback-numbers";let L=[];for(let X=0;X<=10;X++){let _=document.createElement("button");_.type="button",_.className="tvw-feedback-rating-btn tvw-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${X} out of 10`),_.textContent=String(X),_.dataset.rating=String(X),X<=6?_.classList.add("tvw-feedback-detractor"):X<=8?_.classList.add("tvw-feedback-passive"):_.classList.add("tvw-feedback-promoter"),_.addEventListener("click",()=>{m=X,L.forEach((Ce,se)=>{Ce.classList.toggle("selected",se===X),Ce.setAttribute("aria-checked",se===X?"true":"false")})}),L.push(_),P.appendChild(_)}x.appendChild(H),x.appendChild(P),w.appendChild(x);let F=null;if(d){let X=document.createElement("div");X.className="tvw-feedback-comment-container",F=document.createElement("textarea"),F.className="tvw-feedback-comment",F.placeholder=s,F.rows=3,F.setAttribute("aria-label","Additional comments"),X.appendChild(F),w.appendChild(X)}let ue=document.createElement("div");ue.className="tvw-feedback-actions";let z=document.createElement("button");z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-skip",z.textContent=a,z.addEventListener("click",()=>{r==null||r(),p.remove()});let V=document.createElement("button");return V.type="button",V.className="tvw-feedback-btn tvw-feedback-btn-submit",V.textContent=i,V.addEventListener("click",async()=>{if(m===null){P.classList.add("tvw-feedback-shake"),setTimeout(()=>P.classList.remove("tvw-feedback-shake"),500);return}V.disabled=!0,V.textContent="Submitting...";try{let X=(F==null?void 0:F.value.trim())||void 0;await t(m,X),p.remove()}catch(X){V.disabled=!1,V.textContent=i,console.error("[NPS Feedback] Failed to submit:",X)}}),ue.appendChild(z),ue.appendChild(V),w.appendChild(ue),p.appendChild(w),p}var Gn="persona-chat-history",Wl=30*1e3,Pl={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Rl(n){var e,o,s;if(!n)return[];let t=[],r=Array.from((e=n.items)!=null?e:[]);for(let i of r){if(i.kind!=="file"||!i.type.startsWith("image/"))continue;let a=i.getAsFile();if(!a)continue;if(a.name){t.push(a);continue}let d=(o=Pl[a.type])!=null?o:"png";t.push(new File([a],`clipboard-image-${Date.now()}.${d}`,{type:a.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let i of Array.from((s=n.files)!=null?s:[]))i.type.startsWith("image/")&&t.push(i);return t}function Hl(n){var t,r,e,o,s,i,a,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=n.storage)!=null?t:"session",keyPrefix:(r=n.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(e=n.persist)==null?void 0:e.openState)!=null?o:!0,voiceState:(i=(s=n.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=n.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function Bl(n){try{let t=n==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Nr=n=>!n||typeof n!="object"?{}:{...n},ha=n=>n.map(t=>({...t,streaming:!1})),ma=(n,t,r)=>{let e=n!=null&&n.markdown?js(n.markdown):null;return o=>{var a,d,c;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(t){let v=t.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 n!=null&&n.postprocessMessage?n.postprocessMessage({...o,text:s,raw:(c=i!=null?i:o.text)!=null?c:""}):e?e(s):ur(s)}},Or=(n,t,r)=>{var q,We,_e,dt,vt,Tt,it,f,Re,$,b,R,ae,Te,Ke,Wt,at,St,wt,De,qe,ht,Ve,At,jt,Zt,_r,Ur,qr,Vr,zr,Jr,Kr,Yr,Xr;n.id&&n.id!=="persona-root"&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.id="persona-root";let e=kr(t),o=Gs.getForInstance(e.plugins);e.components&&As.registerAll(e.components);let s=pa(),i=(q=e.storageAdapter)!=null?q:Lr(),a={},d=null,c=l=>{if(e.onStateLoaded)try{return e.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 h=u!=null?u:{messages:[],metadata:{}};return c(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=c(u);h.metadata&&(a=Nr(h.metadata)),(We=h.messages)!=null&&We.length&&(e={...e,initialMessages:h.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(e.onStateLoaded)try{let l=c({messages:[],metadata:{}});(_e=l.messages)!=null&&_e.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,p=l=>{var h;a=(h=l({...a}))!=null?h:{},ns()},m=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Zs],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xn.message,Xn.messageAndClick],C=Qs({parsers:m,handlers:w,getSessionMetadata:v,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let y=(vt=(dt=e.launcher)==null?void 0:dt.enabled)!=null?vt:!0,A=(it=(Tt=e.launcher)==null?void 0:Tt.autoExpand)!=null?it:!1,x=(f=e.autoFocusInput)!=null?f:!1,H=A,Y=y,k=($=(Re=e.layout)==null?void 0:Re.header)==null?void 0:$.layout,P=y?A:!0,L=!1,F=null,ue=()=>{L=!0,F&&clearTimeout(F),F=setTimeout(()=>{L&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),L=!1)},1e4)},z=ma(e,C,ue),V=(R=(b=e.features)==null?void 0:b.showReasoning)!=null?R:!0,X=(Te=(ae=e.features)==null?void 0:ae.showToolCalls)!=null?Te:!0,_=(Wt=(Ke=e.features)==null?void 0:Ke.showEventStreamToggle)!=null?Wt:!1,se=`${(St=typeof e.persistState=="object"?(at=e.persistState)==null?void 0:at.keyPrefix:void 0)!=null?St:"persona-"}event-stream`,G=_?new Ss(se):null,U=(qe=(De=(wt=e.features)==null?void 0:wt.eventStream)==null?void 0:De.maxEvents)!=null?qe:2e3,N=_?new xs(U,G):null,ee=null,fe=!1,Fe=null,Mt=0;G==null||G.open().then(()=>N==null?void 0:N.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let gt={onCopy:l=>{var u,h;s.emit("message:copy",l),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(l.id,"copy").catch(S=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(h=(u=e.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;s.emit("message:feedback",l),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(l.messageId,l.type).catch(S=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(h=(u=e.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},ft=(ht=e.statusIndicator)!=null?ht:{},Ht=l=>{var u,h,S,W;return l==="idle"?(u=ft.idleText)!=null?u:Rt.idle:l==="connecting"?(h=ft.connectingText)!=null?h:Rt.connecting:l==="connected"?(S=ft.connectedText)!=null?S:Rt.connected:l==="error"?(W=ft.errorText)!=null?W:Rt.error:Rt[l]},{wrapper:je,panel:ne}=ea(e),xe=ta(e,y),{container:He,body:$e,messagesWrapper:ze,suggestions:Ot,textarea:he,sendButton:Z,sendButtonWrapper:ct,composerForm:bt,statusText:kt,introTitle:Ct,introSubtitle:Kt,closeButton:te,iconHolder:Pe,headerTitle:xt,headerSubtitle:ve,header:Se,footer:Je,actionsRow:Bt,leftActions:It,rightActions:qt}=xe,I=xe.micButton,nt=xe.micButtonWrapper,O=xe.attachmentButton,Q=xe.attachmentButtonWrapper,re=xe.attachmentInput,Ne=xe.attachmentPreviewsContainer,oe=null;(Ve=e.attachments)!=null&&Ve.enabled&&re&&Ne&&(oe=qn.fromConfig(e.attachments),oe.setPreviewsContainer(Ne),re.addEventListener("change",l=>{let u=l.target;oe==null||oe.handleFileSelect(u.files),u.value=""}));let Xe=o.find(l=>l.renderHeader);if(Xe!=null&&Xe.renderHeader){let l=Xe.renderHeader({config:e,defaultRenderer:()=>{let u=Cn({config:e,showClose:y});return Vn(He,u,e),u.header},onClose:()=>ot(!1,"user")});if(l){let u=He.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),Se=l)}}let Ge=()=>{var u,h,S,W;if(!N)return;if(fe=!0,!ee&&N&&(ee=la({buffer:N,getFullHistory:()=>N.getAllFromStore(),onClose:()=>pe(),config:e,plugins:o})),ee&&($e.style.display="none",(u=Je.parentNode)==null||u.insertBefore(ee.element,Je),ee.update()),D){D.classList.remove("tvw-text-cw-muted"),D.classList.add("tvw-text-cw-accent"),D.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let M=(W=(S=(h=e.features)==null?void 0:h.eventStream)==null?void 0:S.classNames)==null?void 0:W.toggleButtonActive;M&&M.split(/\s+/).forEach(j=>j&&D.classList.add(j))}let l=()=>{if(!fe)return;let M=Date.now();M-Mt>=200&&(ee==null||ee.update(),Mt=M),Fe=requestAnimationFrame(l)};Mt=0,Fe=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},pe=()=>{var l,u,h;if(fe){if(fe=!1,ee&&ee.element.remove(),$e.style.display="",D){D.classList.remove("tvw-text-cw-accent"),D.classList.add("tvw-text-cw-muted"),D.style.boxShadow="";let S=(h=(u=(l=e.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;S&&S.split(/\s+/).forEach(W=>W&&D.classList.remove(W))}Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},D=null;if(_){let l=(jt=(At=e.features)==null?void 0:At.eventStream)==null?void 0:jt.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:"");D=g("button",u),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let h=ie("activity","18px","currentColor",1.5);h&&D.appendChild(h);let S=xe.clearChatButtonWrapper,W=xe.closeButtonWrapper,M=S||W;M&&M.parentNode===Se?Se.insertBefore(D,M):Se.appendChild(D),D.addEventListener("click",()=>{fe?pe():Ge()})}let Ee=o.find(l=>l.renderComposer);if(Ee!=null&&Ee.renderComposer){let l=Ee.renderComposer({config:e,defaultRenderer:()=>bs({config:e}).footer,onSubmit:u=>{T&&!T.isStreaming()&&T.sendMessage(u)},disabled:!1});l&&(Je.replaceWith(l),Je=l)}(()=>{var S,W;let l=(W=(S=e.layout)==null?void 0:S.slots)!=null?W:{},u=M=>{switch(M){case"body-top":return He.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return ze;case"footer-top":return Ot;case"composer":return bt;case"footer-bottom":return kt;default:return null}},h=(M,j)=>{var le;switch(M){case"header-left":case"header-center":case"header-right":if(M==="header-left")Se.insertBefore(j,Se.firstChild);else if(M==="header-right")Se.appendChild(j);else{let de=Se.querySelector(".tvw-flex-col");de?(le=de.parentNode)==null||le.insertBefore(j,de.nextSibling):Se.appendChild(j)}break;case"body-top":{let de=$e.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");de?de.replaceWith(j):$e.insertBefore(j,$e.firstChild);break}case"body-bottom":$e.appendChild(j);break;case"footer-top":Ot.replaceWith(j);break;case"footer-bottom":kt.replaceWith(j);break;default:break}};for(let[M,j]of Object.entries(l))if(j)try{let le=j({config:e,defaultContent:()=>u(M)});le&&h(M,le)}catch(le){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${M}":`,le)}})();let rt=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let S=h.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!S)return;let W=S.getAttribute("data-message-id");if(!W)return;let M=h.getAttribute("data-bubble-type");M==="reasoning"?(Jn.has(W)?Jn.delete(W):Jn.add(W),oa(W,S)):M==="tool"&&(Kn.has(W)?Kn.delete(W):Kn.add(W),ia(W,S,e))};ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),rt(l))}),ze.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),rt(l))});let Yt=new Map;ze.addEventListener("click",l=>{var j;let h=l.target.closest(".tvw-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let S=h.closest("[data-actions-for]");if(!S)return;let W=S.getAttribute("data-actions-for");if(!W)return;let M=h.getAttribute("data-action");if(M==="copy"){let de=T.getMessages().find(ye=>ye.id===W);if(de&&gt.onCopy){let ye=de.content||"";navigator.clipboard.writeText(ye).then(()=>{h.classList.add("tvw-message-action-success");let we=ie("check",14,"currentColor",2);we&&(h.innerHTML="",h.appendChild(we)),setTimeout(()=>{h.classList.remove("tvw-message-action-success");let Me=ie("copy",14,"currentColor",2);Me&&(h.innerHTML="",h.appendChild(Me))},2e3)}).catch(we=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",we)}),gt.onCopy(de)}}else if(M==="upvote"||M==="downvote")if(((j=Yt.get(W))!=null?j:null)===M)Yt.delete(W),h.classList.remove("tvw-message-action-active");else{let ye=M==="upvote"?"downvote":"upvote",we=S.querySelector(`[data-action="${ye}"]`);we&&we.classList.remove("tvw-message-action-active"),Yt.set(W,M),h.classList.add("tvw-message-action-active");let J=T.getMessages().find(E=>E.id===W);J&&gt.onFeedback&&gt.onFeedback({type:M,messageId:J.id,message:J})}}),ze.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let S=h.closest(".vanilla-approval-bubble");if(!S)return;let W=S.getAttribute("data-message-id");if(!W)return;let M=h.getAttribute("data-approval-action");if(!M)return;let j=M==="approve"?"approved":"denied",de=T.getMessages().find(we=>we.id===W);if(!(de!=null&&de.approval))return;let ye=S.querySelector("[data-approval-buttons]");ye&&ye.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),T.resolveApproval(de.approval,j)}),ne.appendChild(He),n.appendChild(je);let Qt=()=>{var ce,ge,Oe,me,Ye,ut,K,Ue,on,_t,nn,kn,Ns,lr,cr,mt;let l=(ge=(ce=e.launcher)==null?void 0:ce.sidebarMode)!=null?ge:!1,u=l||((me=(Oe=e.launcher)==null?void 0:Oe.fullHeight)!=null?me:!1),h=(Ye=e.theme)!=null?Ye:{},S=(K=(ut=e.launcher)==null?void 0:ut.position)!=null?K:"bottom-left",W=S==="bottom-left"||S==="top-left",M=l?"none":"1px solid var(--tvw-cw-border)",j=l?W?"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",de=(Ue=h.panelBorder)!=null?Ue:M,ye=(on=h.panelShadow)!=null?on:j,we=(_t=h.panelBorderRadius)!=null?_t:le;n.style.cssText="",je.style.cssText="",ne.style.cssText="",He.style.cssText="",$e.style.cssText="",Je.style.cssText="";let Me=(kn=(nn=e==null?void 0:e.launcher)==null?void 0:nn.width)!=null?kn:e==null?void 0:e.launcherWidth,J=Me!=null?Me:"min(400px, calc(100vw - 24px))";l||(ne.style.width=J,ne.style.maxWidth=J),ne.style.boxShadow=ye,ne.style.borderRadius=we,He.style.border=de,He.style.borderRadius=we;let E=((Ns=e.launcher)==null?void 0:Ns.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",je.style.display="flex",je.style.flexDirection="column",je.style.flex="1 1 0%",je.style.minHeight="0",je.style.maxHeight="100%",je.style.height="100%",E&&(je.style.overflow="hidden"),ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.height="100%",ne.style.overflow="hidden",He.style.display="flex",He.style.flexDirection="column",He.style.flex="1 1 0%",He.style.minHeight="0",He.style.maxHeight="100%",He.style.overflow="hidden",$e.style.flex="1 1 0%",$e.style.minHeight="0",$e.style.overflowY="auto",Je.style.flexShrink="0"),je.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&&!E&&((lr=sn[S])!=null?lr:sn["bottom-right"]).split(" ").forEach(Dn=>je.classList.add(Dn)),l){let On=(mt=(cr=e.launcher)==null?void 0:cr.sidebarWidth)!=null?mt:"420px";je.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
24
- width: ${Fn} !important;
24
+ width: ${On} !important;
25
25
  height: 100vh !important;
26
26
  max-height: 100vh !important;
27
27
  margin: 0 !important;
28
28
  padding: 0 !important;
29
29
  display: flex !important;
30
30
  flex-direction: column !important;
31
- ${H?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
31
+ ${W?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
32
  `,ne.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
@@ -40,9 +40,9 @@ import{Marked as ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=
40
40
  min-height: 0 !important;
41
41
  margin: 0 !important;
42
42
  padding: 0 !important;
43
- box-shadow: ${fe} !important;
44
- border-radius: ${xe} !important;
45
- `,ne.style.setProperty("width","100%","important"),ne.style.setProperty("max-width","100%","important"),Re.style.cssText=`
43
+ box-shadow: ${ye} !important;
44
+ border-radius: ${we} !important;
45
+ `,ne.style.setProperty("width","100%","important"),ne.style.setProperty("max-width","100%","important"),He.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 ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=
51
51
  min-height: 0 !important;
52
52
  max-height: 100% !important;
53
53
  overflow: hidden !important;
54
- border-radius: ${xe} !important;
55
- border: ${me} !important;
56
- `,qe.style.cssText=`
54
+ border-radius: ${we} !important;
55
+ border: ${de} !important;
56
+ `,Je.style.cssText=`
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!W){let Fn="max-height: -moz-available !important; max-height: stretch !important;",$n=l?"":"padding-top: 1.25em !important;";Ne.style.cssText+=Fn+$n}};Gt(),Ks(n,e);let Ye=[];j&&Ye.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),Q==null||Q.destroy(),Q=null,O==null||O.destroy(),O=null,Y=null});let Zt=null,mn=()=>{Zt&&(Zt(),Zt=null),e.colorScheme==="auto"&&(Zt=ji(()=>{Ks(n,e)}))};mn(),Ye.push(()=>{Zt&&(Zt(),Zt=null)});let hn=ea(Nt),sn=null,M,fn=!1,an=!0,bn=0,Xn=0,ln=null,cn=!1,Ln=0,Wn=!1,Ms=125,ks=2e3,Is=5,Gn=50,Pn=new Map,Ee={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Zn=(ut=(_e=e.voiceRecognition)==null?void 0:_e.autoResume)!=null?ut:!1,Qt=l=>{s.emit("voice:state",{active:Ee.active,source:l,timestamp:Date.now()})},Ut=()=>{d(l=>({...l,voiceState:{active:Ee.active,timestamp:Date.now(),manuallyDeactivated:Ee.manuallyDeactivated}}))},Ls=()=>{var A,H;if(((A=e.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Fr(a.voiceState),p=!!l.active,f=Number((H=l.timestamp)!=null?H:0);Ee.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-f<Al&&setTimeout(()=>{var P,q;Ee.active||(Ee.manuallyDeactivated=!1,((q=(P=e.voiceRecognition)==null?void 0:P.provider)==null?void 0:q.type)==="runtype"?M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("restore"),M.isVoiceActive()&&En()}):An("restore"))},1e3)},Ws=()=>M?aa(M.getMessages()).filter(l=>!l.__skipPersist):[];function Qn(l){if(!(i!=null&&i.save))return;let f={messages:l?aa(l):M?Ws():[],metadata:a};try{let A=i.save(f);A instanceof Promise&&A.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let Cn=(l=!1)=>{if(!an)return;let p=Date.now();cn&&p<Ln&&!l||(cn&&p>=Ln&&(cn=!1),!(!l&&!fn)&&(p-Xn<Ms||(Xn=p,ln&&cancelAnimationFrame(ln),ln=requestAnimationFrame(()=>{cn||!an||(Wn=!0,Fe.scrollTop=Fe.scrollHeight,bn=Fe.scrollTop,requestAnimationFrame(()=>{Wn=!1}),ln=null)}))))},dn=null,Ps=()=>Ne.querySelector("#persona-scroll-container")||Fe,Rs=(l,p=500)=>{let f=l.scrollTop,A=l.clientHeight,H=l.scrollHeight,P=H-f;if(f+A>=H-2||Math.abs(P)<5)return;dn!==null&&(cancelAnimationFrame(dn),dn=null);let ge=performance.now(),me=xe=>1-Math.pow(1-xe,3),fe=xe=>{let Te=l.scrollHeight;Te!==H&&(H=Te,P=H-f);let te=xe-ge,W=Math.min(te/p,1),he=me(W),we=f+P*he;l.scrollTop=we,W<1?dn=requestAnimationFrame(fe):(l.scrollTop=l.scrollHeight,dn=null)};dn=requestAnimationFrame(fe)},Hs=l=>{let p=new Map;l.forEach(f=>{let A=Pn.get(f.id);p.set(f.id,{streaming:f.streaming,role:f.role}),!A&&f.role==="assistant"&&s.emit("assistant:message",f),f.role==="assistant"&&(A!=null&&A.streaming)&&f.streaming===!1&&s.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(A?f.approval.status!=="pending"&&s.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):s.emit("approval:requested",{approval:f.approval,message:f}))}),Pn.clear(),p.forEach((f,A)=>{Pn.set(A,f)})},xn=(l,p,f)=>{var fe,xe,Te,te;let A=document.createElement("div"),P=(()=>{var he;let W=o.find(we=>we.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((he=e.loadingIndicator)!=null&&he.render)return e.loadingIndicator.render})();p.forEach(W=>{var ft,Pt;let he=null,we=o.find(Z=>!!(W.variant==="reasoning"&&Z.renderReasoning||W.variant==="tool"&&Z.renderToolCall||W.variant==="approval"&&Z.renderApproval||!W.variant&&Z.renderMessage)),st=(ft=e.layout)==null?void 0:ft.messages;if(we)if(W.variant==="reasoning"&&W.reasoning&&we.renderReasoning){if(!U)return;he=we.renderReasoning({message:W,defaultRenderer:()=>br(W),config:e})}else if(W.variant==="tool"&&W.toolCall&&we.renderToolCall){if(!K)return;he=we.renderToolCall({message:W,defaultRenderer:()=>Cr(W,e),config:e})}else if(W.variant==="approval"&&W.approval&&we.renderApproval){if(e.approval===!1)return;he=we.renderApproval({message:W,defaultRenderer:()=>xr(W,e),config:e})}else we.renderMessage&&(he=we.renderMessage({message:W,defaultRenderer:()=>{let Z=Ss(W,f,st,e.messageActions,dt,{loadingIndicatorRenderer:P,widgetConfig:e});return W.role!=="user"&&Ar(Z,W,e,M),Z},config:e}));if(!he&&W.role==="assistant"&&!W.variant&&e.enableComponentStreaming!==!1&&Pr(W)){let je=Rr(W);if(je){let rn=Wr(je,{config:e,message:W,transform:f});if(rn){let jt=document.createElement("div");if(jt.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(" "),jt.id=`bubble-${W.id}`,jt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let tn=document.createElement("div");tn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",tn.innerHTML=f({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),jt.appendChild(tn)}jt.appendChild(rn),he=jt}}}if(!he)if(W.variant==="reasoning"&&W.reasoning){if(!U)return;he=br(W)}else if(W.variant==="tool"&&W.toolCall){if(!K)return;he=Cr(W,e)}else if(W.variant==="approval"&&W.approval){if(e.approval===!1)return;he=xr(W,e)}else{let Z=(Pt=e.layout)==null?void 0:Pt.messages;Z!=null&&Z.renderUserMessage&&W.role==="user"?he=Z.renderUserMessage({message:W,config:e,streaming:!!W.streaming}):Z!=null&&Z.renderAssistantMessage&&W.role==="assistant"?he=Z.renderAssistantMessage({message:W,config:e,streaming:!!W.streaming}):he=Ss(W,f,Z,e.messageActions,dt,{loadingIndicatorRenderer:P,widgetConfig:e}),W.role!=="user"&&he&&Ar(he,W,e,M)}let Pe=document.createElement("div");Pe.className="tvw-flex",Pe.id=`wrapper-${W.id}`,Pe.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Pe.classList.add("tvw-justify-end"),Pe.appendChild(he),A.appendChild(Pe)});let q=p.some(W=>W.role==="assistant"&&W.streaming),ge=p[p.length-1],me=(ge==null?void 0:ge.role)==="assistant"&&!ge.streaming&&ge.variant!=="approval";if(fn&&p.some(W=>W.role==="user")&&!q&&!me){let W={config:e,streaming:!0,location:"standalone",defaultRenderer:Vn},he=o.find(st=>st.renderLoadingIndicator),we=null;if(he!=null&&he.renderLoadingIndicator&&(we=he.renderLoadingIndicator(W)),we===null&&((fe=e.loadingIndicator)!=null&&fe.render)&&(we=e.loadingIndicator.render(W)),we===null&&(we=Vn()),we){let st=document.createElement("div"),Pe=((xe=e.loadingIndicator)==null?void 0:xe.showBubble)!==!1;st.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(" "),st.setAttribute("data-typing-indicator","true"),st.appendChild(we);let ft=document.createElement("div");ft.className="tvw-flex",ft.id="wrapper-typing-indicator",ft.setAttribute("data-wrapper-id","typing-indicator"),ft.appendChild(st),A.appendChild(ft)}}if(!fn&&p.length>0){let W=p[p.length-1],he={config:e,lastMessage:W,messageCount:p.length},we=o.find(Pe=>Pe.renderIdleIndicator),st=null;if(we!=null&&we.renderIdleIndicator&&(st=we.renderIdleIndicator(he)),st===null&&((Te=e.loadingIndicator)!=null&&Te.renderIdle)&&(st=e.loadingIndicator.renderIdle(he)),st){let Pe=document.createElement("div"),ft=((te=e.loadingIndicator)==null?void 0:te.showBubble)!==!1;Pe.className=ft?["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(st);let Pt=document.createElement("div");Pt.className="tvw-flex",Pt.id="wrapper-idle-indicator",Pt.setAttribute("data-wrapper-id","idle-indicator"),Pt.appendChild(Pe),A.appendChild(Pt)}}_i(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let W=Ps();Rs(W)})})},Sn=()=>{y&&(I?(Ne.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-95","tvw-opacity-0"),ne.classList.add("tvw-scale-100","tvw-opacity-100"),Xe?Xe.element.style.display="none":Ge&&(Ge.style.display="none")):(Ne.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-100","tvw-opacity-100"),ne.classList.add("tvw-scale-95","tvw-opacity-0"),Xe?Xe.element.style.display="":Ge&&(Ge.style.display="")))},nt=(l,p="user")=>{if(!y||I===l)return;let f=I;I=l,Sn(),I&&(wn(),Cn(!0));let A={open:I,source:p,timestamp:Date.now()};I&&!f?s.emit("widget:opened",A):!I&&f&&s.emit("widget:closed",A),s.emit("widget:state",{open:I,launcherEnabled:y,voiceActive:Ee.active,streaming:M.isStreaming()})},Rn=l=>{X.disabled=l,F&&(F.disabled=l),hn.buttons.forEach(p=>{p.disabled=l})},Hn=()=>{Ee.active||de&&de.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>Hn(),200)});let es=()=>{var H,P,q,ge,me,fe,xe,Te,te,W,he,we,st,Pe;yt.textContent=(P=(H=e.copy)==null?void 0:H.welcomeTitle)!=null?P:"Hello \u{1F44B}",Kt.textContent=(ge=(q=e.copy)==null?void 0:q.welcomeSubtitle)!=null?ge:"Ask anything about your account or products.",de.placeholder=(fe=(me=e.copy)==null?void 0:me.inputPlaceholder)!=null?fe:"How can I help...",(Te=(xe=e.sendButton)==null?void 0:xe.useIcon)!=null&&Te||(X.textContent=(W=(te=e.copy)==null?void 0:te.sendButtonLabel)!=null?W:"Send");let p=(we=(he=e.theme)==null?void 0:he.inputFontFamily)!=null?we:"sans-serif",f=(Pe=(st=e.theme)==null?void 0:st.inputFontWeight)!=null?Pe:"400",A=ft=>{switch(ft){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};de.style.fontFamily=A(p),de.style.fontWeight=f};if(e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{d(p=>({...p,sessionId:l}))}}),M=new ys(e,{onMessagesChanged(l){xn(Ue,l,z),M&&(l.some(H=>H.role==="user")?hn.render([],M,de,l):hn.render(e.suggestionChips,M,de,l,e.suggestionChipsConfig)),Cn(!fn),Hs(l);let p=[...l].reverse().find(A=>A.role==="user"),f=Ee.lastUserMessageId;p&&p.id!==f&&(Ee.lastUserMessageId=p.id,s.emit("user:message",p)),Ee.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Qn(l)},onStatusChanged(l){var A;let p=(A=e.statusIndicator)!=null?A:{},f=H=>{var P,q,ge,me;return H==="idle"?(P=p.idleText)!=null?P:Rt.idle:H==="connecting"?(q=p.connectingText)!=null?q:Rt.connecting:H==="connected"?(ge=p.connectedText)!=null?ge:Rt.connected:H==="error"?(me=p.errorText)!=null?me:Rt.error:Rt[H]};Tt.textContent=f(l)},onStreamingChanged(l){fn=l,Rn(l),M&&xn(Ue,M.getMessages(),z),l||Cn(!0)},onVoiceStatusChanged(l){var p,f;((f=(p=e.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"&&l!=="listening"&&(Ee.active=!1,Tn(),Qt("system"),Ut())}}),((xt=(Ve=e.voiceRecognition)==null?void 0:Ve.provider)==null?void 0:xt.type)==="runtype")try{M.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}e.clientToken&&M.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),O&&M.setSSEEventCallback((l,p)=>{O==null||O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),u&&u.then(l=>{var p;l&&(l.metadata&&(a=Fr(l.metadata),b.syncFromMetadata()),(p=l.messages)!=null&&p.length&&M.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ts=l=>{var H;l.preventDefault();let p=de.value.trim(),f=(H=oe==null?void 0:oe.hasAttachments())!=null?H:!1;if(!p&&!f)return;let A;f&&(A=[],A.push(...oe.getContentParts()),p&&A.push(fr(p))),de.value="",de.style.height="auto",M.sendMessage(p,{contentParts:A}),f&&oe.clearAttachments()},ns=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},ss=async l=>{var f;if(((f=e.attachments)==null?void 0:f.enabled)!==!0||!oe)return;let p=Tl(l.clipboardData);p.length!==0&&(l.preventDefault(),await oe.handleFiles(p))},Ft=null,qt=!1,un=null,kt=null,rs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,An=(l="user")=>{var P,q,ge,me;if(qt||M.isStreaming())return;let p=rs();if(!p)return;Ft=new p;let A=(q=((P=e.voiceRecognition)!=null?P:{}).pauseDuration)!=null?q:2e3;Ft.continuous=!0,Ft.interimResults=!0,Ft.lang="en-US";let H=de.value;Ft.onresult=fe=>{let xe="",Te="";for(let W=0;W<fe.results.length;W++){let he=fe.results[W],we=he[0].transcript;he.isFinal?xe+=we+" ":Te=we}let te=H+xe+Te;de.value=te,un&&clearTimeout(un),(xe||Te)&&(un=window.setTimeout(()=>{let W=de.value.trim();W&&Ft&&qt&&(en(),de.value="",de.style.height="auto",M.sendMessage(W,{viaVoice:!0}))},A))},Ft.onerror=fe=>{fe.error!=="no-speech"&&en()},Ft.onend=()=>{if(qt){let fe=de.value.trim();fe&&fe!==H.trim()&&(de.value="",de.style.height="auto",M.sendMessage(fe,{viaVoice:!0})),en()}};try{if(Ft.start(),qt=!0,Ee.active=!0,l!=="system"&&(Ee.manuallyDeactivated=!1),Qt(l),Ut(),F){kt={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let fe=(ge=e.voiceRecognition)!=null?ge:{},xe=(me=fe.recordingBackgroundColor)!=null?me:"#ef4444",Te=fe.recordingIconColor,te=fe.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=xe,Te){F.style.color=Te;let W=F.querySelector("svg");W&&W.setAttribute("stroke",Te)}te&&(F.style.borderColor=te),F.setAttribute("aria-label","Stop voice recognition")}}catch{en("system")}},en=(l="user")=>{if(qt){if(qt=!1,un&&(clearTimeout(un),un=null),Ft){try{Ft.stop()}catch{}Ft=null}if(Ee.active=!1,Qt(l),Ut(),F){if(F.classList.remove("tvw-voice-recording"),kt){F.style.backgroundColor=kt.backgroundColor,F.style.color=kt.color,F.style.borderColor=kt.borderColor;let p=F.querySelector("svg");p&&p.setAttribute("stroke",kt.color||"currentColor"),kt=null}F.setAttribute("aria-label","Start voice recognition")}}},Bs=(l,p)=>{var Pe,ft,Pt,Z,je,rn,jt,tn;let f=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((Pe=l==null?void 0:l.provider)==null?void 0:Pe.type)==="runtype";if(!(f||A))return null;let P=g("div","tvw-send-button-wrapper"),q=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");q.type="button",q.setAttribute("aria-label","Start voice recognition");let ge=(ft=l==null?void 0:l.iconName)!=null?ft:"mic",me=(Pt=p==null?void 0:p.size)!=null?Pt:"40px",fe=(Z=l==null?void 0:l.iconSize)!=null?Z:me,xe=parseFloat(fe)||24,Te=(je=l==null?void 0:l.backgroundColor)!=null?je:p==null?void 0:p.backgroundColor,te=(rn=l==null?void 0:l.iconColor)!=null?rn:p==null?void 0:p.textColor;q.style.width=fe,q.style.height=fe,q.style.minWidth=fe,q.style.minHeight=fe,q.style.fontSize="18px",q.style.lineHeight="1";let W=te||"currentColor",he=ie(ge,xe,W,1.5);he?(q.appendChild(he),q.style.color=W):(q.textContent="\u{1F3A4}",q.style.color=W),Te?q.style.backgroundColor=Te:q.classList.add("tvw-bg-cw-primary"),te?q.style.color=te:!te&&!(p!=null&&p.textColor)&&q.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(q.style.borderWidth=l.borderWidth,q.style.borderStyle="solid"),l!=null&&l.borderColor&&(q.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(q.style.paddingLeft=l.paddingX,q.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(q.style.paddingTop=l.paddingY,q.style.paddingBottom=l.paddingY),P.appendChild(q);let we=(jt=l==null?void 0:l.tooltipText)!=null?jt:"Start voice recognition";if(((tn=l==null?void 0:l.showTooltip)!=null?tn:!1)&&we){let Mn=g("div","tvw-send-button-tooltip");Mn.textContent=we,P.appendChild(Mn)}return{micButton:q,micButtonWrapper:P}},En=()=>{var H,P;if(!F)return;kt={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let l=(H=e.voiceRecognition)!=null?H:{},p=(P=l.recordingBackgroundColor)!=null?P:"#ef4444",f=l.recordingIconColor,A=l.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=p,f){F.style.color=f;let q=F.querySelector("svg");q&&q.setAttribute("stroke",f)}A&&(F.style.borderColor=A),F.setAttribute("aria-label","Stop voice recognition")},Tn=()=>{var l,p,f;if(F){if(F.classList.remove("tvw-voice-recording"),kt){F.style.backgroundColor=(l=kt.backgroundColor)!=null?l:"",F.style.color=(p=kt.color)!=null?p:"",F.style.borderColor=(f=kt.borderColor)!=null?f:"";let A=F.querySelector("svg");A&&A.setAttribute("stroke",kt.color||"currentColor"),kt=null}F.setAttribute("aria-label","Start voice recognition")}},Bn=()=>{var l,p;if(((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Ee.manuallyDeactivated=!M.isVoiceActive(),Ut(),Qt("user"),M.isVoiceActive()?En():Tn()});return}if(qt){let f=de.value.trim();Ee.manuallyDeactivated=!0,Ut(),en("user"),f&&(de.value="",de.style.height="auto",M.sendMessage(f))}else Ee.manuallyDeactivated=!1,Ut(),An("user")};F&&(F.addEventListener("click",Bn),Ye.push(()=>{var l,p;((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(M.isVoiceActive()&&M.toggleVoice(),Tn()):en("system"),F&&F.removeEventListener("click",Bn)}));let Fs=s.on("assistant:complete",()=>{Zn&&(Ee.active||Ee.manuallyDeactivated||Zn==="assistant"&&!Ee.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!Ee.active&&!Ee.manuallyDeactivated&&(((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("auto"),M.isVoiceActive()&&En()}):An("auto"))},600))});Ye.push(Fs);let $s=s.on("action:resubmit",()=>{setTimeout(()=>{M&&!M.isStreaming()&&M.continueConversation()},100)});Ye.push($s);let pn=()=>{nt(!I,"user")},Xe=null,Ge=null;if(y){let l=o.find(p=>p.renderLauncher);if(l!=null&&l.renderLauncher){let p=l.renderLauncher({config:e,defaultRenderer:()=>bs(e,pn).element,onToggle:pn});p&&(Ge=p)}Ge||(Xe=bs(e,pn))}Xe?n.appendChild(Xe.element):Ge&&n.appendChild(Ge),Sn(),hn.render(e.suggestionChips,M,de,void 0,e.suggestionChipsConfig),es(),Rn(M.isStreaming()),Cn(!0),Ls(),x&&(y?I&&setTimeout(()=>Hn(),200):setTimeout(()=>Hn(),0));let wn=()=>{var f,A,H,P,q,ge,me,fe;let l=(A=(f=e.launcher)==null?void 0:f.sidebarMode)!=null?A:!1,p=l||((P=(H=e.launcher)==null?void 0:H.fullHeight)!=null?P:!1);if(!y){ne.style.height="",ne.style.width="";return}if(!l){let xe=(ge=(q=e==null?void 0:e.launcher)==null?void 0:q.width)!=null?ge:e==null?void 0:e.launcherWidth,Te=xe!=null?xe:"min(400px, calc(100vw - 24px))";ne.style.width=Te,ne.style.maxWidth=Te}if(!p){let xe=window.innerHeight,Te=64,te=(fe=(me=e.launcher)==null?void 0:me.heightOffset)!=null?fe:0,W=Math.max(200,xe-Te),he=Math.min(640,W),we=Math.max(200,he-te);ne.style.height=`${we}px`}};wn(),window.addEventListener("resize",wn),Ye.push(()=>window.removeEventListener("resize",wn)),bn=Fe.scrollTop;let os=()=>{let l=Fe.scrollTop,p=Fe.scrollHeight,f=Fe.clientHeight,A=p-l-f,H=Math.abs(l-bn);if(bn=l,!Wn&&!(H<=Is)){if(!an&&A<Gn){cn=!1,an=!0;return}an&&A>Gn&&(cn=!0,Ln=Date.now()+ks,an=!1)}};Fe.addEventListener("scroll",os,{passive:!0}),Ye.push(()=>Fe.removeEventListener("scroll",os)),Ye.push(()=>{ln&&cancelAnimationFrame(ln)});let is=()=>{ee&&(sn&&(ee.removeEventListener("click",sn),sn=null),y?(ee.style.display="",sn=()=>{I=!1,Sn()},ee.addEventListener("click",sn)):ee.style.display="none")};is(),(()=>{let{clearChatButton:l}=be;l&&l.addEventListener("click",()=>{M.clearMessages();try{localStorage.removeItem(Kn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Kn}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Kn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}a={},b.syncFromMetadata(),O==null||O.clear(),Q==null||Q.update()})})(),vt.addEventListener("submit",ts),de.addEventListener("keydown",ns),de.addEventListener("paste",ss),Ye.push(()=>{vt.removeEventListener("submit",ts),de.removeEventListener("keydown",ns),de.removeEventListener("paste",ss)}),Ye.push(()=>{M.cancel()}),Xe?Ye.push(()=>{Xe==null||Xe.destroy()}):Ge&&Ye.push(()=>{Ge==null||Ge.remove()});let It={update(l){var qr,zr,Jr,Kr,Yr,Xr,Gr,Zr,Qr,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,Io,Lo,Wo,Po,Ro,Ho,Bo,Fo,$o,Oo,No,Do,jo,_o,Vo,Uo,qo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ei,ti,ni,si,ri,oi,ii,ai,li,ci,di,ui,pi,gi,mi,hi,fi,wi,vi,yi,bi,Ci,xi,Si,Ai,Ei,Ti,Mi;let p=e.toolCall,f=e.colorScheme;e={...e,...l},Gt(),Ks(n,e),e.colorScheme!==f&&mn();let A=Ys.getForInstance(e.plugins);o.length=0,o.push(...A),y=(zr=(qr=e.launcher)==null?void 0:qr.enabled)!=null?zr:!0,S=(Kr=(Jr=e.launcher)==null?void 0:Jr.autoExpand)!=null?Kr:!1,U=(Xr=(Yr=e.features)==null?void 0:Yr.showReasoning)!=null?Xr:!0,K=(Zr=(Gr=e.features)==null?void 0:Gr.showToolCalls)!=null?Zr:!0;let H=j;if(j=(eo=(Qr=e.features)==null?void 0:Qr.showEventStreamToggle)!=null?eo:!1,j&&!H){if(O||(Y=new Es(se),O=new As(_,Y),Y.open().then(()=>O==null?void 0:O.restore()).catch(()=>{}),M.setSSEEventCallback((R,Me)=>{O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:R,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!D&&Ce){let R=(no=(to=e.features)==null?void 0:to.eventStream)==null?void 0:no.classNames,Me="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(R!=null&&R.toggleButton?" "+R.toggleButton:"");D=g("button",Me),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let Ze=ie("activity","18px","currentColor",1.5);Ze&&D.appendChild(Ze);let ve=be.clearChatButtonWrapper,He=be.closeButtonWrapper,wt=ve||He;wt&&wt.parentNode===Ce?Ce.insertBefore(D,wt):Ce.appendChild(D),D.addEventListener("click",()=>{ue?ce():Ke()})}}else!j&&H&&(ce(),D&&(D.remove(),D=null),O==null||O.clear(),Y==null||Y.destroy(),O=null,Y=null);if(((so=e.launcher)==null?void 0:so.enabled)===!1&&Xe&&(Xe.destroy(),Xe=null),((ro=e.launcher)==null?void 0:ro.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((oo=e.launcher)==null?void 0:oo.enabled)!==!1&&!Xe&&!Ge){let R=o.find(Me=>Me.renderLauncher);if(R!=null&&R.renderLauncher){let Me=R.renderLauncher({config:e,defaultRenderer:()=>bs(e,pn).element,onToggle:pn});Me&&(Ge=Me,n.appendChild(Ge))}Ge||(Xe=bs(e,pn),n.appendChild(Xe.element))}Xe&&Xe.update(e),bt&&((io=e.launcher)==null?void 0:io.title)!==void 0&&(bt.textContent=e.launcher.title),pe&&((ao=e.launcher)==null?void 0:ao.subtitle)!==void 0&&(pe.textContent=e.launcher.subtitle);let P=(lo=e.layout)==null?void 0:lo.header;if((P==null?void 0:P.layout)!==E&&Ce){let R=P?Cs(e,P,{showClose:y,onClose:()=>nt(!1,"user")}):yn({config:e,showClose:y,onClose:()=>nt(!1,"user")});Ce.replaceWith(R.header),Ce=R.header,Le=R.iconHolder,bt=R.headerTitle,pe=R.headerSubtitle,ee=R.closeButton,E=P==null?void 0:P.layout}else if(P&&(Le&&(Le.style.display=P.showIcon===!1?"none":""),bt&&(bt.style.display=P.showTitle===!1?"none":""),pe&&(pe.style.display=P.showSubtitle===!1?"none":""),ee&&(ee.style.display=P.showCloseButton===!1?"none":""),be.clearChatButtonWrapper)){let R=P.showClearChat;if(R!==void 0){be.clearChatButtonWrapper.style.display=R?"":"none";let{closeButtonWrapper:Me}=be;Me&&!Me.classList.contains("tvw-absolute")&&(R?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let ge=((co=e.layout)==null?void 0:co.showHeader)!==!1;Ce&&(Ce.style.display=ge?"":"none");let me=((uo=e.layout)==null?void 0:uo.showFooter)!==!1;qe&&(qe.style.display=me?"":"none"),y!==J?y?nt(S,"auto"):(I=!0,Sn()):S!==k&&nt(S,"auto"),k=S,J=y,wn(),is(),JSON.stringify(l.toolCall)!==JSON.stringify(p)&&M&&xn(Ue,M.getMessages(),z);let te=(po=e.launcher)!=null?po:{},W=(go=te.headerIconHidden)!=null?go:!1,he=(ho=(mo=e.layout)==null?void 0:mo.header)==null?void 0:ho.showIcon,we=W||he===!1,st=te.headerIconName,Pe=(fo=te.headerIconSize)!=null?fo:"48px";if(Le){let R=Re.querySelector(".tvw-border-b-cw-divider"),Me=R==null?void 0:R.querySelector(".tvw-flex-col");if(we)Le.style.display="none",R&&Me&&!R.contains(Me)&&R.insertBefore(Me,R.firstChild);else{if(Le.style.display="",Le.style.height=Pe,Le.style.width=Pe,R&&Me&&(R.contains(Le)?Le.nextSibling!==Me&&(Le.remove(),R.insertBefore(Le,Me)):R.insertBefore(Le,Me)),st){let ve=parseFloat(Pe)||24,He=ie(st,ve*.6,"#ffffff",2);He?Le.replaceChildren(He):Le.textContent=(wo=te.agentIconText)!=null?wo:"\u{1F4AC}"}else if(te.iconUrl){let ve=Le.querySelector("img");if(ve)ve.src=te.iconUrl,ve.style.height=Pe,ve.style.width=Pe;else{let He=document.createElement("img");He.src=te.iconUrl,He.alt="",He.className="tvw-rounded-xl tvw-object-cover",He.style.height=Pe,He.style.width=Pe,Le.replaceChildren(He)}}else{let ve=Le.querySelector("svg"),He=Le.querySelector("img");(ve||He)&&Le.replaceChildren(),Le.textContent=(vo=te.agentIconText)!=null?vo:"\u{1F4AC}"}let Ze=Le.querySelector("img");Ze&&(Ze.style.height=Pe,Ze.style.width=Pe)}}let ft=(bo=(yo=e.layout)==null?void 0:yo.header)==null?void 0:bo.showTitle,Pt=(xo=(Co=e.layout)==null?void 0:Co.header)==null?void 0:xo.showSubtitle;if(bt&&(bt.style.display=ft===!1?"none":""),pe&&(pe.style.display=Pt===!1?"none":""),ee){((Ao=(So=e.layout)==null?void 0:So.header)==null?void 0:Ao.showCloseButton)===!1?ee.style.display="none":ee.style.display="";let Me=(Eo=te.closeButtonSize)!=null?Eo:"32px",Ze=(To=te.closeButtonPlacement)!=null?To:"inline";ee.style.height=Me,ee.style.width=Me;let{closeButtonWrapper:ve}=be,He=Ze==="top-right",wt=ve==null?void 0:ve.classList.contains("tvw-absolute");if(ve&&He!==wt)if(ve.remove(),He)ve.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Re.style.position="relative",Re.appendChild(ve);else{let ke=(ko=(Mo=te.clearChat)==null?void 0:Mo.placement)!=null?ko:"inline",St=(Lo=(Io=te.clearChat)==null?void 0:Io.enabled)!=null?Lo:!0;ve.className=St&&ke==="inline"?"":"tvw-ml-auto";let _t=Re.querySelector(".tvw-border-b-cw-divider");_t&&_t.appendChild(ve)}if(te.closeButtonColor?(ee.style.color=te.closeButtonColor,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),te.closeButtonBackgroundColor?(ee.style.backgroundColor=te.closeButtonBackgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),te.closeButtonBorderWidth||te.closeButtonBorderColor){let ke=te.closeButtonBorderWidth||"0px",St=te.closeButtonBorderColor||"transparent";ee.style.border=`${ke} solid ${St}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");te.closeButtonBorderRadius?(ee.style.borderRadius=te.closeButtonBorderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),te.closeButtonPaddingX?(ee.style.paddingLeft=te.closeButtonPaddingX,ee.style.paddingRight=te.closeButtonPaddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),te.closeButtonPaddingY?(ee.style.paddingTop=te.closeButtonPaddingY,ee.style.paddingBottom=te.closeButtonPaddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let Wt=(Wo=te.closeButtonIconName)!=null?Wo:"x",zt=(Po=te.closeButtonIconText)!=null?Po:"\xD7";ee.innerHTML="";let Ot=ie(Wt,"20px",te.closeButtonColor||"",2);Ot?ee.appendChild(Ot):ee.textContent=zt;let ct=(Ro=te.closeButtonTooltipText)!=null?Ro:"Close chat",Jt=(Ho=te.closeButtonShowTooltip)!=null?Ho:!0;if(ee.setAttribute("aria-label",ct),ve&&(ve._cleanupTooltip&&(ve._cleanupTooltip(),delete ve._cleanupTooltip),Jt&&ct)){let ke=null,St=()=>{if(ke||!ee)return;ke=g("div","tvw-clear-chat-tooltip"),ke.textContent=ct;let hs=g("div");hs.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(hs);let kn=ee.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${kn.left+kn.width/2}px`,ke.style.top=`${kn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},_t=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};ve.addEventListener("mouseenter",St),ve.addEventListener("mouseleave",_t),ee.addEventListener("focus",St),ee.addEventListener("blur",_t),ve._cleanupTooltip=()=>{_t(),ve&&(ve.removeEventListener("mouseenter",St),ve.removeEventListener("mouseleave",_t)),ee&&(ee.removeEventListener("focus",St),ee.removeEventListener("blur",_t))}}}let{clearChatButton:Z,clearChatButtonWrapper:je}=be;if(Z){let R=(Bo=te.clearChat)!=null?Bo:{},Me=(Fo=R.enabled)!=null?Fo:!0,Ze=(Oo=($o=e.layout)==null?void 0:$o.header)==null?void 0:Oo.showClearChat,ve=Ze!==void 0?Ze:Me,He=(No=R.placement)!=null?No:"inline";if(je){je.style.display=ve?"":"none";let{closeButtonWrapper:wt}=be;wt&&!wt.classList.contains("tvw-absolute")&&(ve?wt.classList.remove("tvw-ml-auto"):wt.classList.add("tvw-ml-auto"));let Wt=He==="top-right",zt=je.classList.contains("tvw-absolute");if(Wt!==zt&&ve){if(je.remove(),Wt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",Re.style.position="relative",Re.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ct=Re.querySelector(".tvw-border-b-cw-divider"),Jt=be.closeButtonWrapper;ct&&Jt&&Jt.parentElement===ct?ct.insertBefore(je,Jt):ct&&ct.appendChild(je)}let Ot=be.closeButtonWrapper;Ot&&!Ot.classList.contains("tvw-absolute")&&(Wt?Ot.classList.add("tvw-ml-auto"):Ot.classList.remove("tvw-ml-auto"))}}if(ve){let wt=(Do=R.size)!=null?Do:"32px";Z.style.height=wt,Z.style.width=wt;let Wt=(jo=R.iconName)!=null?jo:"refresh-cw",zt=(_o=R.iconColor)!=null?_o:"";Z.innerHTML="";let Ot=ie(Wt,"20px",zt||"",2);if(Ot&&Z.appendChild(Ot),zt?(Z.style.color=zt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),R.backgroundColor?(Z.style.backgroundColor=R.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),R.borderWidth||R.borderColor){let ke=R.borderWidth||"0px",St=R.borderColor||"transparent";Z.style.border=`${ke} solid ${St}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");R.borderRadius?(Z.style.borderRadius=R.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),R.paddingX?(Z.style.paddingLeft=R.paddingX,Z.style.paddingRight=R.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),R.paddingY?(Z.style.paddingTop=R.paddingY,Z.style.paddingBottom=R.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let ct=(Vo=R.tooltipText)!=null?Vo:"Clear chat",Jt=(Uo=R.showTooltip)!=null?Uo:!0;if(Z.setAttribute("aria-label",ct),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),Jt&&ct)){let ke=null,St=()=>{if(ke||!Z)return;ke=g("div","tvw-clear-chat-tooltip"),ke.textContent=ct;let hs=g("div");hs.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(hs);let kn=Z.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${kn.left+kn.width/2}px`,ke.style.top=`${kn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},_t=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};je.addEventListener("mouseenter",St),je.addEventListener("mouseleave",_t),Z.addEventListener("focus",St),Z.addEventListener("blur",_t),je._cleanupTooltip=()=>{_t(),je&&(je.removeEventListener("mouseenter",St),je.removeEventListener("mouseleave",_t)),Z&&(Z.removeEventListener("focus",St),Z.removeEventListener("blur",_t))}}}}let rn=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Xs],jt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Jn.message,Jn.messageAndClick];b=Gs({parsers:rn,handlers:jt,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),z=la(e,b,le),M.updateConfig(e),xn(Ue,M.getMessages(),z),hn.render(e.suggestionChips,M,de,void 0,e.suggestionChipsConfig),es(),Rn(M.isStreaming());let tn=((qo=e.voiceRecognition)==null?void 0:qo.enabled)===!0,Mn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Os=((Jo=(zo=e.voiceRecognition)==null?void 0:zo.provider)==null?void 0:Jo.type)==="runtype";if(tn&&(Mn||Os))if(!F||!Qe){let R=Bs(e.voiceRecognition,e.sendButton);R&&(F=R.micButton,Qe=R.micButtonWrapper,Vt.insertBefore(Qe,at),F.addEventListener("click",Bn),F.disabled=M.isStreaming())}else{let R=(Ko=e.voiceRecognition)!=null?Ko:{},Me=(Yo=e.sendButton)!=null?Yo:{},Ze=(Xo=R.iconName)!=null?Xo:"mic",ve=(Go=Me.size)!=null?Go:"40px",He=(Zo=R.iconSize)!=null?Zo:ve,wt=parseFloat(He)||24;F.style.width=He,F.style.height=He,F.style.minWidth=He,F.style.minHeight=He;let Wt=(ei=(Qo=R.iconColor)!=null?Qo:Me.textColor)!=null?ei:"currentColor";F.innerHTML="";let zt=ie(Ze,wt,Wt,2);zt?F.appendChild(zt):F.textContent="\u{1F3A4}";let Ot=(ti=R.backgroundColor)!=null?ti:Me.backgroundColor;Ot?(F.style.backgroundColor=Ot,F.classList.remove("tvw-bg-cw-primary")):(F.style.backgroundColor="",F.classList.add("tvw-bg-cw-primary")),Wt?(F.style.color=Wt,F.classList.remove("tvw-text-white")):!Wt&&!Me.textColor&&(F.style.color="",F.classList.add("tvw-text-white")),R.borderWidth?(F.style.borderWidth=R.borderWidth,F.style.borderStyle="solid"):(F.style.borderWidth="",F.style.borderStyle=""),R.borderColor?F.style.borderColor=R.borderColor:F.style.borderColor="",R.paddingX?(F.style.paddingLeft=R.paddingX,F.style.paddingRight=R.paddingX):(F.style.paddingLeft="",F.style.paddingRight=""),R.paddingY?(F.style.paddingTop=R.paddingY,F.style.paddingBottom=R.paddingY):(F.style.paddingTop="",F.style.paddingBottom="");let ct=Qe==null?void 0:Qe.querySelector(".tvw-send-button-tooltip"),Jt=(ni=R.tooltipText)!=null?ni:"Start voice recognition";if(((si=R.showTooltip)!=null?si:!1)&&Jt)if(ct)ct.textContent=Jt,ct.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=Jt,Qe==null||Qe.insertBefore(St,F)}else ct&&(ct.style.display="none");Qe.style.display="",F.disabled=M.isStreaming()}else F&&Qe&&(Qe.style.display="none",((oi=(ri=e.voiceRecognition)==null?void 0:ri.provider)==null?void 0:oi.type)==="runtype"?M.isVoiceActive()&&M.toggleVoice():qt&&en());if(((ii=e.attachments)==null?void 0:ii.enabled)===!0)if(!G||!N){let R=(ai=e.attachments)!=null?ai:{},Ze=(ci=((li=e.sendButton)!=null?li:{}).size)!=null?ci:"40px";$e||($e=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),$e.style.display="none",vt.insertBefore($e,de)),re||(re=document.createElement("input"),re.type="file",re.accept=((di=R.allowedTypes)!=null?di:vn).join(","),re.multiple=((ui=R.maxFiles)!=null?ui:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),vt.insertBefore(re,de)),G=g("div","tvw-send-button-wrapper"),N=g("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",(pi=R.buttonTooltipText)!=null?pi:"Attach file");let ve=(gi=R.buttonIconName)!=null?gi:"paperclip",He=Ze,wt=parseFloat(He)||40,Wt=Math.round(wt*.6);N.style.width=He,N.style.height=He,N.style.minWidth=He,N.style.minHeight=He,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 zt=ie(ve,Wt,"currentColor",1.5);zt?N.appendChild(zt):N.textContent="\u{1F4CE}",N.addEventListener("click",Jt=>{Jt.preventDefault(),re==null||re.click()}),G.appendChild(N);let Ot=(mi=R.buttonTooltipText)!=null?mi:"Attach file",ct=g("div","tvw-send-button-tooltip");ct.textContent=Ot,G.appendChild(ct),Mt.append(G),!oe&&re&&$e&&(oe=jn.fromConfig(R),oe.setPreviewsContainer($e),re.addEventListener("change",async()=>{oe&&(re!=null&&re.files)&&(await oe.handleFileSelect(re.files),re.value="")}))}else{G.style.display="";let R=(hi=e.attachments)!=null?hi:{};re&&(re.accept=((fi=R.allowedTypes)!=null?fi:vn).join(","),re.multiple=((wi=R.maxFiles)!=null?wi:4)>1),oe&&oe.updateConfig({allowedTypes:R.allowedTypes,maxFileSize:R.maxFileSize,maxFiles:R.maxFiles})}else G&&(G.style.display="none"),oe&&oe.clearAttachments();let pt=(vi=e.sendButton)!=null?vi:{},Fn=(yi=pt.useIcon)!=null?yi:!1,$n=(bi=pt.iconText)!=null?bi:"\u2191",Ur=pt.iconName,lr=(Ci=pt.tooltipText)!=null?Ci:"Send message",wa=(xi=pt.showTooltip)!=null?xi:!1,ps=(Si=pt.size)!=null?Si:"40px",Ns=pt.backgroundColor,on=pt.textColor;if(Fn){if(X.style.width=ps,X.style.height=ps,X.style.minWidth=ps,X.style.minHeight=ps,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Ur){let R=parseFloat(ps)||24,Me=on&&typeof on=="string"&&on.trim()?on.trim():"currentColor",Ze=ie(Ur,R,Me,2);Ze?(X.appendChild(Ze),X.style.color=Me):(X.textContent=$n,on?X.style.color=on:X.classList.add("tvw-text-white"))}else X.textContent=$n,on?X.style.color=on:X.classList.add("tvw-text-white");X.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Ns?(X.style.backgroundColor=Ns,X.classList.remove("tvw-bg-cw-primary")):X.classList.add("tvw-bg-cw-primary")}else X.textContent=(Ei=(Ai=e.copy)==null?void 0:Ai.sendButtonLabel)!=null?Ei:"Send",X.style.width="",X.style.height="",X.style.minWidth="",X.style.minHeight="",X.style.fontSize="",X.style.lineHeight="",X.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",Ns?(X.style.backgroundColor=Ns,X.classList.remove("tvw-bg-cw-accent")):X.classList.add("tvw-bg-cw-accent"),on?X.style.color=on:X.classList.add("tvw-text-white");pt.borderWidth?(X.style.borderWidth=pt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),pt.borderColor?X.style.borderColor=pt.borderColor:X.style.borderColor="",pt.paddingX?(X.style.paddingLeft=pt.paddingX,X.style.paddingRight=pt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),pt.paddingY?(X.style.paddingTop=pt.paddingY,X.style.paddingBottom=pt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let gs=at==null?void 0:at.querySelector(".tvw-send-button-tooltip");if(wa&&lr)if(gs)gs.textContent=lr,gs.style.display="";else{let R=document.createElement("div");R.className="tvw-send-button-tooltip",R.textContent=lr,at==null||at.insertBefore(R,X)}else gs&&(gs.style.display="none");let ms=(Ti=e.statusIndicator)!=null?Ti:{},va=(Mi=ms.visible)!=null?Mi:!0;if(Tt.style.display=va?"":"none",M){let R=M.getStatus(),Me=Ze=>{var ve,He,wt,Wt;return Ze==="idle"?(ve=ms.idleText)!=null?ve:Rt.idle:Ze==="connecting"?(He=ms.connectingText)!=null?He:Rt.connecting:Ze==="connected"?(wt=ms.connectedText)!=null?wt:Rt.connected:Ze==="error"?(Wt=ms.errorText)!=null?Wt:Rt.error:Rt[Ze]};Tt.textContent=Me(R)}},open(){y&&nt(!0,"api")},close(){y&&nt(!1,"api")},toggle(){y&&nt(!I,"api")},clearChat(){M.clearMessages();try{localStorage.removeItem(Kn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Kn}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Kn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(f=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}a={},b.syncFromMetadata(),O==null||O.clear(),Q==null||Q.update()},setMessage(l){return!de||M.isStreaming()?!1:(!I&&y&&nt(!0,"system"),de.value=l,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(M.isStreaming())return!1;let p=(l==null?void 0:l.trim())||de.value.trim();return p?(!I&&y&&nt(!0,"system"),de.value="",de.style.height="auto",M.sendMessage(p),!0):!1},startVoiceRecognition(){var p,f;return M.isStreaming()?!1:((f=(p=e.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"?(M.isVoiceActive()||(!I&&y&&nt(!0,"system"),Ee.manuallyDeactivated=!1,Ut(),M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("user"),M.isVoiceActive()&&En()})),!0):qt?!0:rs()?(!I&&y&&nt(!0,"system"),Ee.manuallyDeactivated=!1,Ut(),An("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?M.isVoiceActive()?(M.toggleVoice().then(()=>{Ee.active=!1,Ee.manuallyDeactivated=!0,Ut(),Qt("user"),Tn()}),!0):!1:qt?(Ee.manuallyDeactivated=!0,Ut(),en("user"),!0):!1},injectMessage(l){return!I&&y&&nt(!0,"system"),M.injectMessage(l)},injectAssistantMessage(l){!I&&y&&nt(!0,"system");let p=M.injectAssistantMessage(l);return T&&(T=!1,B&&(clearTimeout(B),B=null),setTimeout(()=>{M&&!M.isStreaming()&&M.continueConversation()},100)),p},injectUserMessage(l){return!I&&y&&nt(!0,"system"),M.injectUserMessage(l)},injectSystemMessage(l){return!I&&y&&nt(!0,"system"),M.injectSystemMessage(l)},injectMessageBatch(l){return!I&&y&&nt(!0,"system"),M.injectMessageBatch(l)},injectTestMessage(l){!I&&y&&nt(!0,"system"),M.injectTestEvent(l)},async connectStream(l,p){return M.connectStream(l,p)},__pushEventStreamEvent(l){O&&O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!j||!O||Ke()},hideEventStream(){ue&&ce()},isEventStreamVisible(){return ue},focusInput(){return y&&!I||!de?!1:(de.focus(),!0)},async resolveApproval(l,p){let A=M.getMessages().find(H=>{var P;return H.variant==="approval"&&((P=H.approval)==null?void 0:P.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return M.resolveApproval(A.approval,p)},getMessages(){return M.getMessages()},getStatus(){return M.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){d(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return y&&I},isVoiceActive(){return Ee.active},getState(){return{open:y&&I,launcherEnabled:y,voiceActive:Ee.active,streaming:M.isStreaming()}},showCSATFeedback(l){!I&&y&&nt(!0,"system");let p=Ue.querySelector(".tvw-feedback-container");p&&p.remove();let f=Hr({onSubmit:async(A,H)=>{var P;M.isClientTokenMode()&&await M.submitCSATFeedback(A,H),(P=l==null?void 0:l.onSubmit)==null||P.call(l,A,H)},onDismiss:l==null?void 0:l.onDismiss,...l});Ue.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&y&&nt(!0,"system");let p=Ue.querySelector(".tvw-feedback-container");p&&p.remove();let f=Br({onSubmit:async(A,H)=>{var P;M.isClientTokenMode()&&await M.submitNPSFeedback(A,H),(P=l==null?void 0:l.onSubmit)==null||P.call(l,A,H)},onDismiss:l==null?void 0:l.onDismiss,...l});Ue.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return M.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return M.submitNPSFeedback(l,p)},destroy(){Ye.forEach(l=>l()),Ne.remove(),Xe==null||Xe.destroy(),Ge==null||Ge.remove(),sn&&ee.removeEventListener("click",sn)}};if((((Dt=r==null?void 0:r.debugTools)!=null?Dt:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:f=>f?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Ye.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=f=>{let A=f.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&It.focusInput()};if(window.addEventListener("persona:focusInput",p),Ye.push(()=>{window.removeEventListener("persona:focusInput",p)}),j){let f=H=>{let P=H.detail;(!(P!=null&&P.instanceId)||P.instanceId===l)&&It.showEventStream()},A=H=>{let P=H.detail;(!(P!=null&&P.instanceId)||P.instanceId===l)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",f),window.addEventListener("persona:hideEventStream",A),Ye.push(()=>{window.removeEventListener("persona:showEventStream",f),window.removeEventListener("persona:hideEventStream",A)})}}let $t=Ml(e.persistState);if($t&&y){let l=kl($t.storage),p=`${$t.keyPrefix}widget-open`,f=`${$t.keyPrefix}widget-voice`,A=`${$t.keyPrefix}widget-voice-mode`;if(l){let H=((Xt=$t.persist)==null?void 0:Xt.openState)&&l.getItem(p)==="true",P=((Dr=$t.persist)==null?void 0:Dr.voiceState)&&l.getItem(f)==="true",q=((jr=$t.persist)==null?void 0:jr.voiceState)&&l.getItem(A)==="true";if(H&&setTimeout(()=>{It.open(),setTimeout(()=>{var ge;if(P||q)It.startVoiceRecognition();else if((ge=$t.persist)!=null&&ge.focusInput){let me=n.querySelector("textarea");me&&me.focus()}},100)},0),(_r=$t.persist)!=null&&_r.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Vr=$t.persist)!=null&&Vr.voiceState&&(s.on("voice:state",ge=>{l.setItem(f,ge.active?"true":"false")}),s.on("user:message",ge=>{l.setItem(A,ge.viaVoice?"true":"false")})),$t.clearOnChatClear){let ge=()=>{l.removeItem(p),l.removeItem(f),l.removeItem(A)},me=()=>ge();window.addEventListener("persona:clear-chat",me),Ye.push(()=>{window.removeEventListener("persona:clear-chat",me)})}}}return It};var Or={},Il=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},Ll=()=>{try{if(typeof Or!="undefined"&&Or.url)return new URL("../widget.css",Or.url).href}catch{}return null},ca=n=>{let t=Ll(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-persona","true"),n.insertBefore(e,n.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&t){let o=document.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},da=n=>{var c,v,d,m;let t=Il(n.target),r=document.createElement("div");r.className="persona-host";let e=(d=(v=(c=n.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?d:!0;e||(r.style.height="100%"),t.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let w=r.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),ca(w)}else i=r,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),ca(r);t.id&&s.setAttribute("data-persona-instance",t.id);let a=$r(s,n.config,{debugTools:n.debugTools});(m=n.onReady)==null||m.call(n);let u={...a,host:r,destroy(){a.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=u),u};var ua={name:"@runtypelabs/persona",version:"1.47.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var Yn=ua.version;function gn(n){if(n!==void 0)return typeof n=="string"?n:Array.isArray(n)?`[${n.map(t=>t.toString()).join(", ")}]`:n.toString()}function Pl(n){if(n)return{getHeaders:gn(n.getHeaders),onFeedback:gn(n.onFeedback),onCopy:gn(n.onCopy),requestMiddleware:gn(n.requestMiddleware),actionHandlers:gn(n.actionHandlers),actionParsers:gn(n.actionParsers),postprocessMessage:gn(n.postprocessMessage),contextProviders:gn(n.contextProviders),streamParser:gn(n.streamParser)}}var pa=`({ text, message }: any) => {
60
+ `}if(!E){let On="max-height: -moz-available !important; max-height: stretch !important;",Dn=l?"":"padding-top: 1.25em !important;";je.style.cssText+=On+Dn}};Qt(),Xs(n,e);let Ze=[];_&&Ze.push(()=>{Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),ee==null||ee.destroy(),ee=null,N==null||N.destroy(),N=null,G=null});let en=null,mn=()=>{en&&(en(),en=null),e.colorScheme==="auto"&&(en=Ki(()=>{Xs(n,e)}))};mn(),Ze.push(()=>{en&&(en(),en=null)});let fn=aa(Ot),rn=null,T,vn=!1,ln=!0,xn=0,Qn=0,cn=null,dn=!1,Wn=0,Pn=!1,Es=125,Ts=2e3,Ms=5,es=50,Rn=new Map,Ae={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ts=(_r=(Zt=e.voiceRecognition)==null?void 0:Zt.autoResume)!=null?_r:!1,Xt=l=>{s.emit("voice:state",{active:Ae.active,source:l,timestamp:Date.now()})},Dt=()=>{p(l=>({...l,voiceState:{active:Ae.active,timestamp:Date.now(),manuallyDeactivated:Ae.manuallyDeactivated}}))},ks=()=>{var S,W;if(((S=e.voiceRecognition)==null?void 0:S.enabled)===!1)return;let l=Nr(a.voiceState),u=!!l.active,h=Number((W=l.timestamp)!=null?W:0);Ae.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Wl&&setTimeout(()=>{var M,j;Ae.active||(Ae.manuallyDeactivated=!1,((j=(M=e.voiceRecognition)==null?void 0:M.provider)==null?void 0:j.type)==="runtype"?T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("restore"),T.isVoiceActive()&&wn()}):Tn("restore"))},1e3)},Is=()=>T?ha(T.getMessages()).filter(l=>!l.__skipPersist):[];function ns(l){if(!(i!=null&&i.save))return;let h={messages:l?ha(l):T?Is():[],metadata:a};try{let S=i.save(h);S instanceof Promise&&S.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",W)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let Sn=(l=!1)=>{if(!ln)return;let u=Date.now();dn&&u<Wn&&!l||(dn&&u>=Wn&&(dn=!1),!(!l&&!vn)&&(u-Qn<Es||(Qn=u,cn&&cancelAnimationFrame(cn),cn=requestAnimationFrame(()=>{dn||!ln||(Pn=!0,$e.scrollTop=$e.scrollHeight,xn=$e.scrollTop,requestAnimationFrame(()=>{Pn=!1}),cn=null)}))))},un=null,Ls=()=>je.querySelector("#persona-scroll-container")||$e,Ws=(l,u=500)=>{let h=l.scrollTop,S=l.clientHeight,W=l.scrollHeight,M=W-h;if(h+S>=W-2||Math.abs(M)<5)return;un!==null&&(cancelAnimationFrame(un),un=null);let le=performance.now(),de=we=>1-Math.pow(1-we,3),ye=we=>{let Me=l.scrollHeight;Me!==W&&(W=Me,M=W-h);let J=we-le,E=Math.min(J/u,1),ce=de(E),ge=h+M*ce;l.scrollTop=ge,E<1?un=requestAnimationFrame(ye):(l.scrollTop=l.scrollHeight,un=null)};un=requestAnimationFrame(ye)},Ps=l=>{let u=new Map;l.forEach(h=>{let S=Rn.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!S&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(S!=null&&S.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(S?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Rn.clear(),u.forEach((h,S)=>{Rn.set(S,h)})},An=(l,u,h)=>{var ye,we,Me,J;let S=document.createElement("div"),M=(()=>{var ce;let E=o.find(ge=>ge.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((ce=e.loadingIndicator)!=null&&ce.render)return e.loadingIndicator.render})();u.forEach(E=>{var Ye,ut;let ce=null,ge=o.find(K=>!!(E.variant==="reasoning"&&K.renderReasoning||E.variant==="tool"&&K.renderToolCall||E.variant==="approval"&&K.renderApproval||!E.variant&&K.renderMessage)),Oe=(Ye=e.layout)==null?void 0:Ye.messages;if(ge)if(E.variant==="reasoning"&&E.reasoning&&ge.renderReasoning){if(!V)return;ce=ge.renderReasoning({message:E,defaultRenderer:()=>xr(E),config:e})}else if(E.variant==="tool"&&E.toolCall&&ge.renderToolCall){if(!X)return;ce=ge.renderToolCall({message:E,defaultRenderer:()=>Sr(E,e),config:e})}else if(E.variant==="approval"&&E.approval&&ge.renderApproval){if(e.approval===!1)return;ce=ge.renderApproval({message:E,defaultRenderer:()=>Ar(E,e),config:e})}else ge.renderMessage&&(ce=ge.renderMessage({message:E,defaultRenderer:()=>{let K=Cs(E,h,Oe,e.messageActions,gt,{loadingIndicatorRenderer:M,widgetConfig:e});return E.role!=="user"&&Tr(K,E,e,T),K},config:e}));if(!ce&&E.role==="assistant"&&!E.variant&&e.enableComponentStreaming!==!1&&Hr(E)){let Ue=Br(E);if(Ue){let on=Rr(Ue,{config:e,message:E,transform:h});if(on){let _t=document.createElement("div");if(_t.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(" "),_t.id=`bubble-${E.id}`,_t.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let nn=document.createElement("div");nn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",nn.innerHTML=h({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),_t.appendChild(nn)}_t.appendChild(on),ce=_t}}}if(!ce)if(E.variant==="reasoning"&&E.reasoning){if(!V)return;ce=xr(E)}else if(E.variant==="tool"&&E.toolCall){if(!X)return;ce=Sr(E,e)}else if(E.variant==="approval"&&E.approval){if(e.approval===!1)return;ce=Ar(E,e)}else{let K=(ut=e.layout)==null?void 0:ut.messages;K!=null&&K.renderUserMessage&&E.role==="user"?ce=K.renderUserMessage({message:E,config:e,streaming:!!E.streaming}):K!=null&&K.renderAssistantMessage&&E.role==="assistant"?ce=K.renderAssistantMessage({message:E,config:e,streaming:!!E.streaming}):ce=Cs(E,h,K,e.messageActions,gt,{loadingIndicatorRenderer:M,widgetConfig:e}),E.role!=="user"&&ce&&Tr(ce,E,e,T)}let me=document.createElement("div");me.className="tvw-flex",me.id=`wrapper-${E.id}`,me.setAttribute("data-wrapper-id",E.id),E.role==="user"&&me.classList.add("tvw-justify-end"),me.appendChild(ce),S.appendChild(me)});let j=u.some(E=>E.role==="assistant"&&E.streaming),le=u[u.length-1],de=(le==null?void 0:le.role)==="assistant"&&!le.streaming&&le.variant!=="approval";if(vn&&u.some(E=>E.role==="user")&&!j&&!de){let E={config:e,streaming:!0,location:"standalone",defaultRenderer:zn},ce=o.find(Oe=>Oe.renderLoadingIndicator),ge=null;if(ce!=null&&ce.renderLoadingIndicator&&(ge=ce.renderLoadingIndicator(E)),ge===null&&((ye=e.loadingIndicator)!=null&&ye.render)&&(ge=e.loadingIndicator.render(E)),ge===null&&(ge=zn()),ge){let Oe=document.createElement("div"),me=((we=e.loadingIndicator)==null?void 0:we.showBubble)!==!1;Oe.className=me?["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(" "),Oe.setAttribute("data-typing-indicator","true"),Oe.appendChild(ge);let Ye=document.createElement("div");Ye.className="tvw-flex",Ye.id="wrapper-typing-indicator",Ye.setAttribute("data-wrapper-id","typing-indicator"),Ye.appendChild(Oe),S.appendChild(Ye)}}if(!vn&&u.length>0){let E=u[u.length-1],ce={config:e,lastMessage:E,messageCount:u.length},ge=o.find(me=>me.renderIdleIndicator),Oe=null;if(ge!=null&&ge.renderIdleIndicator&&(Oe=ge.renderIdleIndicator(ce)),Oe===null&&((Me=e.loadingIndicator)!=null&&Me.renderIdle)&&(Oe=e.loadingIndicator.renderIdle(ce)),Oe){let me=document.createElement("div"),Ye=((J=e.loadingIndicator)==null?void 0:J.showBubble)!==!1;me.className=Ye?["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(" "),me.setAttribute("data-idle-indicator","true"),me.appendChild(Oe);let ut=document.createElement("div");ut.className="tvw-flex",ut.id="wrapper-idle-indicator",ut.setAttribute("data-wrapper-id","idle-indicator"),ut.appendChild(me),S.appendChild(ut)}}Yi(l,S),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let E=Ls();Ws(E)})})},En=()=>{y&&(P?(je.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-95","tvw-opacity-0"),ne.classList.add("tvw-scale-100","tvw-opacity-100"),Qe?Qe.element.style.display="none":et&&(et.style.display="none")):(je.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-100","tvw-opacity-100"),ne.classList.add("tvw-scale-95","tvw-opacity-0"),Qe?Qe.element.style.display="":et&&(et.style.display="")))},ot=(l,u="user")=>{if(!y||P===l)return;let h=P;P=l,En(),P&&(yn(),Sn(!0));let S={open:P,source:u,timestamp:Date.now()};P&&!h?s.emit("widget:opened",S):!P&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:P,launcherEnabled:y,voiceActive:Ae.active,streaming:T.isStreaming()})},Hn=l=>{Z.disabled=l,I&&(I.disabled=l),fn.buttons.forEach(u=>{u.disabled=l})},Bn=()=>{Ae.active||he&&he.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>Bn(),200)});let ss=()=>{var W,M,j,le,de,ye,we,Me,J,E,ce,ge,Oe,me;Ct.textContent=(M=(W=e.copy)==null?void 0:W.welcomeTitle)!=null?M:"Hello \u{1F44B}",Kt.textContent=(le=(j=e.copy)==null?void 0:j.welcomeSubtitle)!=null?le:"Ask anything about your account or products.",he.placeholder=(ye=(de=e.copy)==null?void 0:de.inputPlaceholder)!=null?ye:"How can I help...",(Me=(we=e.sendButton)==null?void 0:we.useIcon)!=null&&Me||(Z.textContent=(E=(J=e.copy)==null?void 0:J.sendButtonLabel)!=null?E:"Send");let u=(ge=(ce=e.theme)==null?void 0:ce.inputFontFamily)!=null?ge:"sans-serif",h=(me=(Oe=e.theme)==null?void 0:Oe.inputFontWeight)!=null?me:"400",S=Ye=>{switch(Ye){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};he.style.fontFamily=S(u),he.style.fontWeight=h};if(e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(u=>({...u,sessionId:l}))}}),T=new vs(e,{onMessagesChanged(l){An(ze,l,z),T&&(l.some(W=>W.role==="user")?fn.render([],T,he,l):fn.render(e.suggestionChips,T,he,l,e.suggestionChipsConfig)),Sn(!vn),Ps(l);let u=[...l].reverse().find(S=>S.role==="user"),h=Ae.lastUserMessageId;u&&u.id!==h&&(Ae.lastUserMessageId=u.id,s.emit("user:message",u)),Ae.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),ns(l)},onStatusChanged(l){var S;let u=(S=e.statusIndicator)!=null?S:{},h=W=>{var M,j,le,de;return W==="idle"?(M=u.idleText)!=null?M:Rt.idle:W==="connecting"?(j=u.connectingText)!=null?j:Rt.connecting:W==="connected"?(le=u.connectedText)!=null?le:Rt.connected:W==="error"?(de=u.errorText)!=null?de:Rt.error:Rt[W]};kt.textContent=h(l)},onStreamingChanged(l){vn=l,Hn(l),T&&An(ze,T.getMessages(),z),l||Sn(!0)},onVoiceStatusChanged(l){var u,h;if(((h=(u=e.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":break;case"processing":Gt(),Hs();break;case"speaking":Gt(),Bs();break;default:l==="idle"&&T.isBargeInActive()?(Gt(),wn(),I==null||I.setAttribute("aria-label","End voice session")):(Ae.active=!1,Gt(),Xt("system"),Dt());break}}}),((qr=(Ur=e.voiceRecognition)==null?void 0:Ur.provider)==null?void 0:qr.type)==="runtype")try{T.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}e.clientToken&&T.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),N&&T.setSSEEventCallback((l,u)=>{N==null||N.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=Nr(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&T.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let rs=l=>{var W;l.preventDefault();let u=he.value.trim(),h=(W=oe==null?void 0:oe.hasAttachments())!=null?W:!1;if(!u&&!h)return;let S;h&&(S=[],S.push(...oe.getContentParts()),u&&S.push(wr(u))),he.value="",he.style.height="auto",T.sendMessage(u,{contentParts:S}),h&&oe.clearAttachments()},os=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Z.click())},is=async l=>{var h;if(((h=e.attachments)==null?void 0:h.enabled)!==!0||!oe)return;let u=Rl(l.clipboardData);u.length!==0&&(l.preventDefault(),await oe.handleFiles(u))},Ft=null,Vt=!1,pn=null,ke=null,as=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Tn=(l="user")=>{var M,j,le,de,ye,we,Me,J;if(Vt||T.isStreaming())return;let u=as();if(!u)return;Ft=new u;let S=(j=((M=e.voiceRecognition)!=null?M:{}).pauseDuration)!=null?j:2e3;Ft.continuous=!0,Ft.interimResults=!0,Ft.lang="en-US";let W=he.value;Ft.onresult=E=>{let ce="",ge="";for(let me=0;me<E.results.length;me++){let Ye=E.results[me],ut=Ye[0].transcript;Ye.isFinal?ce+=ut+" ":ge=ut}let Oe=W+ce+ge;he.value=Oe,pn&&clearTimeout(pn),(ce||ge)&&(pn=window.setTimeout(()=>{let me=he.value.trim();me&&Ft&&Vt&&(tn(),he.value="",he.style.height="auto",T.sendMessage(me,{viaVoice:!0}))},S))},Ft.onerror=E=>{E.error!=="no-speech"&&tn()},Ft.onend=()=>{if(Vt){let E=he.value.trim();E&&E!==W.trim()&&(he.value="",he.style.height="auto",T.sendMessage(E,{viaVoice:!0})),tn()}};try{if(Ft.start(),Vt=!0,Ae.active=!0,l!=="system"&&(Ae.manuallyDeactivated=!1),Xt(l),Dt(),I){let E=(le=e.voiceRecognition)!=null?le:{};ke={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(de=E.iconName)!=null?de:"mic",iconSize:parseFloat((Me=(we=E.iconSize)!=null?we:(ye=e.sendButton)==null?void 0:ye.size)!=null?Me:"40")||24};let ce=(J=E.recordingBackgroundColor)!=null?J:"#ef4444",ge=E.recordingIconColor,Oe=E.recordingBorderColor;if(I.classList.add("tvw-voice-recording"),I.style.backgroundColor=ce,ge){I.style.color=ge;let me=I.querySelector("svg");me&&me.setAttribute("stroke",ge)}Oe&&(I.style.borderColor=Oe),I.setAttribute("aria-label","Stop voice recognition")}}catch{tn("system")}},tn=(l="user")=>{if(Vt){if(Vt=!1,pn&&(clearTimeout(pn),pn=null),Ft){try{Ft.stop()}catch{}Ft=null}Ae.active=!1,Xt(l),Dt(),I&&Gt()}},Rs=(l,u)=>{var me,Ye,ut,K,Ue,on,_t,nn;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((me=l==null?void 0:l.provider)==null?void 0:me.type)==="runtype";if(!(h||S))return null;let M=g("div","tvw-send-button-wrapper"),j=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");j.type="button",j.setAttribute("aria-label","Start voice recognition");let le=(Ye=l==null?void 0:l.iconName)!=null?Ye:"mic",de=(ut=u==null?void 0:u.size)!=null?ut:"40px",ye=(K=l==null?void 0:l.iconSize)!=null?K:de,we=parseFloat(ye)||24,Me=(Ue=l==null?void 0:l.backgroundColor)!=null?Ue:u==null?void 0:u.backgroundColor,J=(on=l==null?void 0:l.iconColor)!=null?on:u==null?void 0:u.textColor;j.style.width=ye,j.style.height=ye,j.style.minWidth=ye,j.style.minHeight=ye,j.style.fontSize="18px",j.style.lineHeight="1";let E=J||"currentColor",ce=ie(le,we,E,1.5);ce?(j.appendChild(ce),j.style.color=E):(j.textContent="\u{1F3A4}",j.style.color=E),Me?j.style.backgroundColor=Me:j.classList.add("tvw-bg-cw-primary"),J?j.style.color=J:!J&&!(u!=null&&u.textColor)&&j.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(j.style.borderWidth=l.borderWidth,j.style.borderStyle="solid"),l!=null&&l.borderColor&&(j.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(j.style.paddingLeft=l.paddingX,j.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(j.style.paddingTop=l.paddingY,j.style.paddingBottom=l.paddingY),M.appendChild(j);let ge=(_t=l==null?void 0:l.tooltipText)!=null?_t:"Start voice recognition";if(((nn=l==null?void 0:l.showTooltip)!=null?nn:!1)&&ge){let kn=g("div","tvw-send-button-tooltip");kn.textContent=ge,M.appendChild(kn)}return{micButton:j,micButtonWrapper:M}},Fn=()=>{var u,h,S,W,M;if(!I||ke)return;let l=(u=e.voiceRecognition)!=null?u:{};ke={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((M=(W=l.iconSize)!=null?W:(S=e.sendButton)==null?void 0:S.size)!=null?M:"40")||24}},$n=(l,u)=>{var M,j,le,de,ye;if(!I)return;let h=I.querySelector("svg");h&&h.remove();let S=(ye=ke==null?void 0:ke.iconSize)!=null?ye:parseFloat((de=(le=(M=e.voiceRecognition)==null?void 0:M.iconSize)!=null?le:(j=e.sendButton)==null?void 0:j.size)!=null?de:"40")||24,W=ie(l,S,u,1.5);W&&I.appendChild(W)},Mn=()=>{I&&I.classList.remove("tvw-voice-recording","tvw-voice-processing","tvw-voice-speaking")},wn=()=>{var W,M;if(!I)return;Fn();let l=(W=e.voiceRecognition)!=null?W:{},u=(M=l.recordingBackgroundColor)!=null?M:"#ef4444",h=l.recordingIconColor,S=l.recordingBorderColor;if(Mn(),I.classList.add("tvw-voice-recording"),I.style.backgroundColor=u,h){I.style.color=h;let j=I.querySelector("svg");j&&j.setAttribute("stroke",h)}S&&(I.style.borderColor=S),I.setAttribute("aria-label","Stop voice recognition")},Hs=()=>{var le,de,ye,we,Me,J,E,ce;if(!I)return;Fn();let l=(le=e.voiceRecognition)!=null?le:{},u=T.getVoiceInterruptionMode(),h=(de=l.processingIconName)!=null?de:"loader",S=(we=(ye=l.processingIconColor)!=null?ye:ke==null?void 0:ke.color)!=null?we:"",W=(J=(Me=l.processingBackgroundColor)!=null?Me:ke==null?void 0:ke.backgroundColor)!=null?J:"",M=(ce=(E=l.processingBorderColor)!=null?E:ke==null?void 0:ke.borderColor)!=null?ce:"";Mn(),I.classList.add("tvw-voice-processing"),I.style.backgroundColor=W,I.style.borderColor=M;let j=S||"currentColor";I.style.color=j,$n(h,j),I.setAttribute("aria-label","Processing voice input"),u==="none"&&(I.style.cursor="default")},Bs=()=>{var ye,we,Me,J,E,ce,ge,Oe,me,Ye,ut,K;if(!I)return;Fn();let l=(ye=e.voiceRecognition)!=null?ye:{},u=T.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",S=(we=l.speakingIconName)!=null?we:h,W=(ce=l.speakingIconColor)!=null?ce:u==="barge-in"?(J=(Me=l.recordingIconColor)!=null?Me:ke==null?void 0:ke.color)!=null?J:"":(E=ke==null?void 0:ke.color)!=null?E:"",M=(me=l.speakingBackgroundColor)!=null?me:u==="barge-in"?(ge=l.recordingBackgroundColor)!=null?ge:"#ef4444":(Oe=ke==null?void 0:ke.backgroundColor)!=null?Oe:"",j=(K=l.speakingBorderColor)!=null?K:u==="barge-in"?(Ye=l.recordingBorderColor)!=null?Ye:"":(ut=ke==null?void 0:ke.borderColor)!=null?ut:"";Mn(),I.classList.add("tvw-voice-speaking"),I.style.backgroundColor=M,I.style.borderColor=j;let le=W||"currentColor";I.style.color=le,$n(S,le);let de=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";I.setAttribute("aria-label",de),u==="none"&&(I.style.cursor="default"),u==="barge-in"&&I.classList.add("tvw-voice-recording")},Gt=()=>{var l,u,h;I&&(Mn(),ke&&(I.style.backgroundColor=(l=ke.backgroundColor)!=null?l:"",I.style.color=(u=ke.color)!=null?u:"",I.style.borderColor=(h=ke.borderColor)!=null?h:"",$n(ke.iconName,ke.color||"currentColor"),ke=null),I.style.cursor="",I.setAttribute("aria-label","Start voice recognition"))},Nn=()=>{var l,u;if(((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=T.getVoiceStatus(),S=T.getVoiceInterruptionMode();if(S==="none"&&(h==="processing"||h==="speaking"))return;if(S==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{Ae.active=!1,Ae.manuallyDeactivated=!0,Dt(),Xt("user"),Gt()});return}T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Ae.manuallyDeactivated=!T.isVoiceActive(),Dt(),Xt("user"),T.isVoiceActive()?wn():Gt()});return}if(Vt){let h=he.value.trim();Ae.manuallyDeactivated=!0,Dt(),tn("user"),h&&(he.value="",he.style.height="auto",T.sendMessage(h))}else Ae.manuallyDeactivated=!1,Dt(),Tn("user")};I&&(I.addEventListener("click",Nn),Ze.push(()=>{var l,u;((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),Gt()):tn("system"),I&&I.removeEventListener("click",Nn)}));let Fs=s.on("assistant:complete",()=>{ts&&(Ae.active||Ae.manuallyDeactivated||ts==="assistant"&&!Ae.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!Ae.active&&!Ae.manuallyDeactivated&&(((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("auto"),T.isVoiceActive()&&wn()}):Tn("auto"))},600))});Ze.push(Fs);let $s=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});Ze.push($s);let gn=()=>{ot(!P,"user")},Qe=null,et=null;if(y){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:e,defaultRenderer:()=>ws(e,gn).element,onToggle:gn});u&&(et=u)}et||(Qe=ws(e,gn))}Qe?n.appendChild(Qe.element):et&&n.appendChild(et),En(),fn.render(e.suggestionChips,T,he,void 0,e.suggestionChipsConfig),ss(),Hn(T.isStreaming()),Sn(!0),ks(),x&&(y?P&&setTimeout(()=>Bn(),200):setTimeout(()=>Bn(),0));let yn=()=>{var h,S,W,M,j,le,de,ye;let l=(S=(h=e.launcher)==null?void 0:h.sidebarMode)!=null?S:!1,u=l||((M=(W=e.launcher)==null?void 0:W.fullHeight)!=null?M:!1);if(!y){ne.style.height="",ne.style.width="";return}if(!l){let we=(le=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?le:e==null?void 0:e.launcherWidth,Me=we!=null?we:"min(400px, calc(100vw - 24px))";ne.style.width=Me,ne.style.maxWidth=Me}if(!u){let we=window.innerHeight,Me=64,J=(ye=(de=e.launcher)==null?void 0:de.heightOffset)!=null?ye:0,E=Math.max(200,we-Me),ce=Math.min(640,E),ge=Math.max(200,ce-J);ne.style.height=`${ge}px`}};yn(),window.addEventListener("resize",yn),Ze.push(()=>window.removeEventListener("resize",yn)),xn=$e.scrollTop;let ls=()=>{let l=$e.scrollTop,u=$e.scrollHeight,h=$e.clientHeight,S=u-l-h,W=Math.abs(l-xn);if(xn=l,!Pn&&!(W<=Ms)){if(!ln&&S<es){dn=!1,ln=!0;return}ln&&S>es&&(dn=!0,Wn=Date.now()+Ts,ln=!1)}};$e.addEventListener("scroll",ls,{passive:!0}),Ze.push(()=>$e.removeEventListener("scroll",ls)),Ze.push(()=>{cn&&cancelAnimationFrame(cn)});let cs=()=>{te&&(rn&&(te.removeEventListener("click",rn),rn=null),y?(te.style.display="",rn=()=>{P=!1,En()},te.addEventListener("click",rn)):te.style.display="none")};cs(),(()=>{let{clearChatButton:l}=xe;l&&l.addEventListener("click",()=>{T.clearMessages();try{localStorage.removeItem(Gn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gn}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}a={},C.syncFromMetadata(),N==null||N.clear(),ee==null||ee.update()})})(),bt.addEventListener("submit",rs),he.addEventListener("keydown",os),he.addEventListener("paste",is),Ze.push(()=>{bt.removeEventListener("submit",rs),he.removeEventListener("keydown",os),he.removeEventListener("paste",is)}),Ze.push(()=>{T.cancel()}),Qe?Ze.push(()=>{Qe==null||Qe.destroy()}):et&&Ze.push(()=>{et==null||et.remove()});let Lt={update(l){var Zr,Qr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,ho,mo,fo,vo,wo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,ko,Io,Lo,Wo,Po,Ro,Ho,Bo,Fo,$o,No,Oo,Do,jo,_o,Uo,qo,Vo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ei,ti,ni,si,ri,oi,ii,ai,li,ci,di,ui,pi,gi,hi,mi,fi,vi,wi,yi,bi,Ci,xi,Si,Ai,Ei,Ti,Mi,ki,Ii,Li,Wi,Pi,Ri,Hi;let u=e.toolCall,h=e.colorScheme;e={...e,...l},Qt(),Xs(n,e),e.colorScheme!==h&&mn();let S=Gs.getForInstance(e.plugins);o.length=0,o.push(...S),y=(Qr=(Zr=e.launcher)==null?void 0:Zr.enabled)!=null?Qr:!0,A=(to=(eo=e.launcher)==null?void 0:eo.autoExpand)!=null?to:!1,V=(so=(no=e.features)==null?void 0:no.showReasoning)!=null?so:!0,X=(oo=(ro=e.features)==null?void 0:ro.showToolCalls)!=null?oo:!0;let W=_;if(_=(ao=(io=e.features)==null?void 0:io.showEventStreamToggle)!=null?ao:!1,_&&!W){if(N||(G=new Ss(se),N=new xs(U,G),G.open().then(()=>N==null?void 0:N.restore()).catch(()=>{}),T.setSSEEventCallback((B,Ie)=>{N.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:B,timestamp:Date.now(),payload:JSON.stringify(Ie)})})),!D&&Se){let B=(co=(lo=e.features)==null?void 0:lo.eventStream)==null?void 0:co.classNames,Ie="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"+(B!=null&&B.toggleButton?" "+B.toggleButton:"");D=g("button",Ie),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let tt=ie("activity","18px","currentColor",1.5);tt&&D.appendChild(tt);let be=xe.clearChatButtonWrapper,Be=xe.closeButtonWrapper,yt=be||Be;yt&&yt.parentNode===Se?Se.insertBefore(D,yt):Se.appendChild(D),D.addEventListener("click",()=>{fe?pe():Ge()})}}else!_&&W&&(pe(),D&&(D.remove(),D=null),N==null||N.clear(),G==null||G.destroy(),N=null,G=null);if(((uo=e.launcher)==null?void 0:uo.enabled)===!1&&Qe&&(Qe.destroy(),Qe=null),((po=e.launcher)==null?void 0:po.enabled)===!1&&et&&(et.remove(),et=null),((go=e.launcher)==null?void 0:go.enabled)!==!1&&!Qe&&!et){let B=o.find(Ie=>Ie.renderLauncher);if(B!=null&&B.renderLauncher){let Ie=B.renderLauncher({config:e,defaultRenderer:()=>ws(e,gn).element,onToggle:gn});Ie&&(et=Ie,n.appendChild(et))}et||(Qe=ws(e,gn),n.appendChild(Qe.element))}Qe&&Qe.update(e),xt&&((ho=e.launcher)==null?void 0:ho.title)!==void 0&&(xt.textContent=e.launcher.title),ve&&((mo=e.launcher)==null?void 0:mo.subtitle)!==void 0&&(ve.textContent=e.launcher.subtitle);let M=(fo=e.layout)==null?void 0:fo.header;if((M==null?void 0:M.layout)!==k&&Se){let B=M?ys(e,M,{showClose:y,onClose:()=>ot(!1,"user")}):Cn({config:e,showClose:y,onClose:()=>ot(!1,"user")});Se.replaceWith(B.header),Se=B.header,Pe=B.iconHolder,xt=B.headerTitle,ve=B.headerSubtitle,te=B.closeButton,k=M==null?void 0:M.layout}else if(M&&(Pe&&(Pe.style.display=M.showIcon===!1?"none":""),xt&&(xt.style.display=M.showTitle===!1?"none":""),ve&&(ve.style.display=M.showSubtitle===!1?"none":""),te&&(te.style.display=M.showCloseButton===!1?"none":""),xe.clearChatButtonWrapper)){let B=M.showClearChat;if(B!==void 0){xe.clearChatButtonWrapper.style.display=B?"":"none";let{closeButtonWrapper:Ie}=xe;Ie&&!Ie.classList.contains("tvw-absolute")&&(B?Ie.classList.remove("tvw-ml-auto"):Ie.classList.add("tvw-ml-auto"))}}let le=((vo=e.layout)==null?void 0:vo.showHeader)!==!1;Se&&(Se.style.display=le?"":"none");let de=((wo=e.layout)==null?void 0:wo.showFooter)!==!1;Je&&(Je.style.display=de?"":"none"),y!==Y?y?ot(A,"auto"):(P=!0,En()):A!==H&&ot(A,"auto"),H=A,Y=y,yn(),cs(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&T&&An(ze,T.getMessages(),z);let J=(yo=e.launcher)!=null?yo:{},E=(bo=J.headerIconHidden)!=null?bo:!1,ce=(xo=(Co=e.layout)==null?void 0:Co.header)==null?void 0:xo.showIcon,ge=E||ce===!1,Oe=J.headerIconName,me=(So=J.headerIconSize)!=null?So:"48px";if(Pe){let B=He.querySelector(".tvw-border-b-cw-divider"),Ie=B==null?void 0:B.querySelector(".tvw-flex-col");if(ge)Pe.style.display="none",B&&Ie&&!B.contains(Ie)&&B.insertBefore(Ie,B.firstChild);else{if(Pe.style.display="",Pe.style.height=me,Pe.style.width=me,B&&Ie&&(B.contains(Pe)?Pe.nextSibling!==Ie&&(Pe.remove(),B.insertBefore(Pe,Ie)):B.insertBefore(Pe,Ie)),Oe){let be=parseFloat(me)||24,Be=ie(Oe,be*.6,"#ffffff",2);Be?Pe.replaceChildren(Be):Pe.textContent=(Ao=J.agentIconText)!=null?Ao:"\u{1F4AC}"}else if(J.iconUrl){let be=Pe.querySelector("img");if(be)be.src=J.iconUrl,be.style.height=me,be.style.width=me;else{let Be=document.createElement("img");Be.src=J.iconUrl,Be.alt="",Be.className="tvw-rounded-xl tvw-object-cover",Be.style.height=me,Be.style.width=me,Pe.replaceChildren(Be)}}else{let be=Pe.querySelector("svg"),Be=Pe.querySelector("img");(be||Be)&&Pe.replaceChildren(),Pe.textContent=(Eo=J.agentIconText)!=null?Eo:"\u{1F4AC}"}let tt=Pe.querySelector("img");tt&&(tt.style.height=me,tt.style.width=me)}}let Ye=(Mo=(To=e.layout)==null?void 0:To.header)==null?void 0:Mo.showTitle,ut=(Io=(ko=e.layout)==null?void 0:ko.header)==null?void 0:Io.showSubtitle;if(xt&&(xt.style.display=Ye===!1?"none":""),ve&&(ve.style.display=ut===!1?"none":""),te){((Wo=(Lo=e.layout)==null?void 0:Lo.header)==null?void 0:Wo.showCloseButton)===!1?te.style.display="none":te.style.display="";let Ie=(Po=J.closeButtonSize)!=null?Po:"32px",tt=(Ro=J.closeButtonPlacement)!=null?Ro:"inline";te.style.height=Ie,te.style.width=Ie;let{closeButtonWrapper:be}=xe,Be=tt==="top-right",yt=be==null?void 0:be.classList.contains("tvw-absolute");if(be&&Be!==yt)if(be.remove(),Be)be.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",He.style.position="relative",He.appendChild(be);else{let Le=(Bo=(Ho=J.clearChat)==null?void 0:Ho.placement)!=null?Bo:"inline",Et=($o=(Fo=J.clearChat)==null?void 0:Fo.enabled)!=null?$o:!0;be.className=Et&&Le==="inline"?"":"tvw-ml-auto";let Ut=He.querySelector(".tvw-border-b-cw-divider");Ut&&Ut.appendChild(be)}if(J.closeButtonColor?(te.style.color=J.closeButtonColor,te.classList.remove("tvw-text-cw-muted")):(te.style.color="",te.classList.add("tvw-text-cw-muted")),J.closeButtonBackgroundColor?(te.style.backgroundColor=J.closeButtonBackgroundColor,te.classList.remove("hover:tvw-bg-gray-100")):(te.style.backgroundColor="",te.classList.add("hover:tvw-bg-gray-100")),J.closeButtonBorderWidth||J.closeButtonBorderColor){let Le=J.closeButtonBorderWidth||"0px",Et=J.closeButtonBorderColor||"transparent";te.style.border=`${Le} solid ${Et}`,te.classList.remove("tvw-border-none")}else te.style.border="",te.classList.add("tvw-border-none");J.closeButtonBorderRadius?(te.style.borderRadius=J.closeButtonBorderRadius,te.classList.remove("tvw-rounded-full")):(te.style.borderRadius="",te.classList.add("tvw-rounded-full")),J.closeButtonPaddingX?(te.style.paddingLeft=J.closeButtonPaddingX,te.style.paddingRight=J.closeButtonPaddingX):(te.style.paddingLeft="",te.style.paddingRight=""),J.closeButtonPaddingY?(te.style.paddingTop=J.closeButtonPaddingY,te.style.paddingBottom=J.closeButtonPaddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Pt=(No=J.closeButtonIconName)!=null?No:"x",zt=(Oo=J.closeButtonIconText)!=null?Oo:"\xD7";te.innerHTML="";let Nt=ie(Pt,"20px",J.closeButtonColor||"",2);Nt?te.appendChild(Nt):te.textContent=zt;let pt=(Do=J.closeButtonTooltipText)!=null?Do:"Close chat",Jt=(jo=J.closeButtonShowTooltip)!=null?jo:!0;if(te.setAttribute("aria-label",pt),be&&(be._cleanupTooltip&&(be._cleanupTooltip(),delete be._cleanupTooltip),Jt&&pt)){let Le=null,Et=()=>{if(Le||!te)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=pt;let gs=g("div");gs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(gs);let In=te.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${In.left+In.width/2}px`,Le.style.top=`${In.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ut=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};be.addEventListener("mouseenter",Et),be.addEventListener("mouseleave",Ut),te.addEventListener("focus",Et),te.addEventListener("blur",Ut),be._cleanupTooltip=()=>{Ut(),be&&(be.removeEventListener("mouseenter",Et),be.removeEventListener("mouseleave",Ut)),te&&(te.removeEventListener("focus",Et),te.removeEventListener("blur",Ut))}}}let{clearChatButton:K,clearChatButtonWrapper:Ue}=xe;if(K){let B=(_o=J.clearChat)!=null?_o:{},Ie=(Uo=B.enabled)!=null?Uo:!0,tt=(Vo=(qo=e.layout)==null?void 0:qo.header)==null?void 0:Vo.showClearChat,be=tt!==void 0?tt:Ie,Be=(zo=B.placement)!=null?zo:"inline";if(Ue){Ue.style.display=be?"":"none";let{closeButtonWrapper:yt}=xe;yt&&!yt.classList.contains("tvw-absolute")&&(be?yt.classList.remove("tvw-ml-auto"):yt.classList.add("tvw-ml-auto"));let Pt=Be==="top-right",zt=Ue.classList.contains("tvw-absolute");if(Pt!==zt&&be){if(Ue.remove(),Pt)Ue.className="tvw-absolute tvw-top-4 tvw-z-50",Ue.style.right="48px",He.style.position="relative",He.appendChild(Ue);else{Ue.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Ue.style.right="";let pt=He.querySelector(".tvw-border-b-cw-divider"),Jt=xe.closeButtonWrapper;pt&&Jt&&Jt.parentElement===pt?pt.insertBefore(Ue,Jt):pt&&pt.appendChild(Ue)}let Nt=xe.closeButtonWrapper;Nt&&!Nt.classList.contains("tvw-absolute")&&(Pt?Nt.classList.add("tvw-ml-auto"):Nt.classList.remove("tvw-ml-auto"))}}if(be){let yt=(Jo=B.size)!=null?Jo:"32px";K.style.height=yt,K.style.width=yt;let Pt=(Ko=B.iconName)!=null?Ko:"refresh-cw",zt=(Yo=B.iconColor)!=null?Yo:"";K.innerHTML="";let Nt=ie(Pt,"20px",zt||"",2);if(Nt&&K.appendChild(Nt),zt?(K.style.color=zt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),B.backgroundColor?(K.style.backgroundColor=B.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),B.borderWidth||B.borderColor){let Le=B.borderWidth||"0px",Et=B.borderColor||"transparent";K.style.border=`${Le} solid ${Et}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");B.borderRadius?(K.style.borderRadius=B.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),B.paddingX?(K.style.paddingLeft=B.paddingX,K.style.paddingRight=B.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),B.paddingY?(K.style.paddingTop=B.paddingY,K.style.paddingBottom=B.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let pt=(Xo=B.tooltipText)!=null?Xo:"Clear chat",Jt=(Go=B.showTooltip)!=null?Go:!0;if(K.setAttribute("aria-label",pt),Ue&&(Ue._cleanupTooltip&&(Ue._cleanupTooltip(),delete Ue._cleanupTooltip),Jt&&pt)){let Le=null,Et=()=>{if(Le||!K)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=pt;let gs=g("div");gs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(gs);let In=K.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${In.left+In.width/2}px`,Le.style.top=`${In.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ut=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};Ue.addEventListener("mouseenter",Et),Ue.addEventListener("mouseleave",Ut),K.addEventListener("focus",Et),K.addEventListener("blur",Ut),Ue._cleanupTooltip=()=>{Ut(),Ue&&(Ue.removeEventListener("mouseenter",Et),Ue.removeEventListener("mouseleave",Ut)),K&&(K.removeEventListener("focus",Et),K.removeEventListener("blur",Ut))}}}}let on=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Zs],_t=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xn.message,Xn.messageAndClick];C=Qs({parsers:on,handlers:_t,getSessionMetadata:v,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),z=ma(e,C,ue),T.updateConfig(e),An(ze,T.getMessages(),z),fn.render(e.suggestionChips,T,he,void 0,e.suggestionChipsConfig),ss(),Hn(T.isStreaming());let nn=((Zo=e.voiceRecognition)==null?void 0:Zo.enabled)===!0,kn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ns=((ei=(Qo=e.voiceRecognition)==null?void 0:Qo.provider)==null?void 0:ei.type)==="runtype";if(nn&&(kn||Ns))if(!I||!nt){let B=Rs(e.voiceRecognition,e.sendButton);B&&(I=B.micButton,nt=B.micButtonWrapper,qt.insertBefore(nt,ct),I.addEventListener("click",Nn),I.disabled=T.isStreaming())}else{let B=(ti=e.voiceRecognition)!=null?ti:{},Ie=(ni=e.sendButton)!=null?ni:{},tt=(si=B.iconName)!=null?si:"mic",be=(ri=Ie.size)!=null?ri:"40px",Be=(oi=B.iconSize)!=null?oi:be,yt=parseFloat(Be)||24;I.style.width=Be,I.style.height=Be,I.style.minWidth=Be,I.style.minHeight=Be;let Pt=(ai=(ii=B.iconColor)!=null?ii:Ie.textColor)!=null?ai:"currentColor";I.innerHTML="";let zt=ie(tt,yt,Pt,2);zt?I.appendChild(zt):I.textContent="\u{1F3A4}";let Nt=(li=B.backgroundColor)!=null?li:Ie.backgroundColor;Nt?(I.style.backgroundColor=Nt,I.classList.remove("tvw-bg-cw-primary")):(I.style.backgroundColor="",I.classList.add("tvw-bg-cw-primary")),Pt?(I.style.color=Pt,I.classList.remove("tvw-text-white")):!Pt&&!Ie.textColor&&(I.style.color="",I.classList.add("tvw-text-white")),B.borderWidth?(I.style.borderWidth=B.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),B.borderColor?I.style.borderColor=B.borderColor:I.style.borderColor="",B.paddingX?(I.style.paddingLeft=B.paddingX,I.style.paddingRight=B.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),B.paddingY?(I.style.paddingTop=B.paddingY,I.style.paddingBottom=B.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let pt=nt==null?void 0:nt.querySelector(".tvw-send-button-tooltip"),Jt=(ci=B.tooltipText)!=null?ci:"Start voice recognition";if(((di=B.showTooltip)!=null?di:!1)&&Jt)if(pt)pt.textContent=Jt,pt.style.display="";else{let Et=document.createElement("div");Et.className="tvw-send-button-tooltip",Et.textContent=Jt,nt==null||nt.insertBefore(Et,I)}else pt&&(pt.style.display="none");nt.style.display="",I.disabled=T.isStreaming()}else I&&nt&&(nt.style.display="none",((pi=(ui=e.voiceRecognition)==null?void 0:ui.provider)==null?void 0:pi.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Vt&&tn());if(((gi=e.attachments)==null?void 0:gi.enabled)===!0)if(!Q||!O){let B=(hi=e.attachments)!=null?hi:{},tt=(fi=((mi=e.sendButton)!=null?mi:{}).size)!=null?fi:"40px";Ne||(Ne=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),Ne.style.display="none",bt.insertBefore(Ne,he)),re||(re=document.createElement("input"),re.type="file",re.accept=((vi=B.allowedTypes)!=null?vi:bn).join(","),re.multiple=((wi=B.maxFiles)!=null?wi:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),bt.insertBefore(re,he)),Q=g("div","tvw-send-button-wrapper"),O=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),O.type="button",O.setAttribute("aria-label",(yi=B.buttonTooltipText)!=null?yi:"Attach file");let be=(bi=B.buttonIconName)!=null?bi:"paperclip",Be=tt,yt=parseFloat(Be)||40,Pt=Math.round(yt*.6);O.style.width=Be,O.style.height=Be,O.style.minWidth=Be,O.style.minHeight=Be,O.style.fontSize="18px",O.style.lineHeight="1",O.style.backgroundColor="transparent",O.style.color="var(--cw-primary, #111827)",O.style.border="none",O.style.borderRadius="6px",O.style.transition="background-color 0.15s ease",O.addEventListener("mouseenter",()=>{O.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),O.addEventListener("mouseleave",()=>{O.style.backgroundColor="transparent"});let zt=ie(be,Pt,"currentColor",1.5);zt?O.appendChild(zt):O.textContent="\u{1F4CE}",O.addEventListener("click",Jt=>{Jt.preventDefault(),re==null||re.click()}),Q.appendChild(O);let Nt=(Ci=B.buttonTooltipText)!=null?Ci:"Attach file",pt=g("div","tvw-send-button-tooltip");pt.textContent=Nt,Q.appendChild(pt),It.append(Q),!oe&&re&&Ne&&(oe=qn.fromConfig(B),oe.setPreviewsContainer(Ne),re.addEventListener("change",async()=>{oe&&(re!=null&&re.files)&&(await oe.handleFileSelect(re.files),re.value="")}))}else{Q.style.display="";let B=(xi=e.attachments)!=null?xi:{};re&&(re.accept=((Si=B.allowedTypes)!=null?Si:bn).join(","),re.multiple=((Ai=B.maxFiles)!=null?Ai:4)>1),oe&&oe.updateConfig({allowedTypes:B.allowedTypes,maxFileSize:B.maxFileSize,maxFiles:B.maxFiles})}else Q&&(Q.style.display="none"),oe&&oe.clearAttachments();let mt=(Ei=e.sendButton)!=null?Ei:{},On=(Ti=mt.useIcon)!=null?Ti:!1,Dn=(Mi=mt.iconText)!=null?Mi:"\u2191",Gr=mt.iconName,dr=(ki=mt.tooltipText)!=null?ki:"Send message",Aa=(Ii=mt.showTooltip)!=null?Ii:!1,ds=(Li=mt.size)!=null?Li:"40px",Os=mt.backgroundColor,an=mt.textColor;if(On){if(Z.style.width=ds,Z.style.height=ds,Z.style.minWidth=ds,Z.style.minHeight=ds,Z.style.fontSize="18px",Z.style.lineHeight="1",Z.innerHTML="",Gr){let B=parseFloat(ds)||24,Ie=an&&typeof an=="string"&&an.trim()?an.trim():"currentColor",tt=ie(Gr,B,Ie,2);tt?(Z.appendChild(tt),Z.style.color=Ie):(Z.textContent=Dn,an?Z.style.color=an:Z.classList.add("tvw-text-white"))}else Z.textContent=Dn,an?Z.style.color=an:Z.classList.add("tvw-text-white");Z.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Os?(Z.style.backgroundColor=Os,Z.classList.remove("tvw-bg-cw-primary")):Z.classList.add("tvw-bg-cw-primary")}else Z.textContent=(Pi=(Wi=e.copy)==null?void 0:Wi.sendButtonLabel)!=null?Pi:"Send",Z.style.width="",Z.style.height="",Z.style.minWidth="",Z.style.minHeight="",Z.style.fontSize="",Z.style.lineHeight="",Z.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",Os?(Z.style.backgroundColor=Os,Z.classList.remove("tvw-bg-cw-accent")):Z.classList.add("tvw-bg-cw-accent"),an?Z.style.color=an:Z.classList.add("tvw-text-white");mt.borderWidth?(Z.style.borderWidth=mt.borderWidth,Z.style.borderStyle="solid"):(Z.style.borderWidth="",Z.style.borderStyle=""),mt.borderColor?Z.style.borderColor=mt.borderColor:Z.style.borderColor="",mt.paddingX?(Z.style.paddingLeft=mt.paddingX,Z.style.paddingRight=mt.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),mt.paddingY?(Z.style.paddingTop=mt.paddingY,Z.style.paddingBottom=mt.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let us=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(Aa&&dr)if(us)us.textContent=dr,us.style.display="";else{let B=document.createElement("div");B.className="tvw-send-button-tooltip",B.textContent=dr,ct==null||ct.insertBefore(B,Z)}else us&&(us.style.display="none");let ps=(Ri=e.statusIndicator)!=null?Ri:{},Ea=(Hi=ps.visible)!=null?Hi:!0;if(kt.style.display=Ea?"":"none",T){let B=T.getStatus(),Ie=tt=>{var be,Be,yt,Pt;return tt==="idle"?(be=ps.idleText)!=null?be:Rt.idle:tt==="connecting"?(Be=ps.connectingText)!=null?Be:Rt.connecting:tt==="connected"?(yt=ps.connectedText)!=null?yt:Rt.connected:tt==="error"?(Pt=ps.errorText)!=null?Pt:Rt.error:Rt[tt]};kt.textContent=Ie(B)}},open(){y&&ot(!0,"api")},close(){y&&ot(!1,"api")},toggle(){y&&ot(!P,"api")},clearChat(){T.clearMessages();try{localStorage.removeItem(Gn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gn}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.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(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},C.syncFromMetadata(),N==null||N.clear(),ee==null||ee.update()},setMessage(l){return!he||T.isStreaming()?!1:(!P&&y&&ot(!0,"system"),he.value=l,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(T.isStreaming())return!1;let u=(l==null?void 0:l.trim())||he.value.trim();return u?(!P&&y&&ot(!0,"system"),he.value="",he.style.height="auto",T.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return T.isStreaming()?!1:((h=(u=e.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!P&&y&&ot(!0,"system"),Ae.manuallyDeactivated=!1,Dt(),T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("user"),T.isVoiceActive()&&wn()})),!0):Vt?!0:as()?(!P&&y&&ot(!0,"system"),Ae.manuallyDeactivated=!1,Dt(),Tn("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{Ae.active=!1,Ae.manuallyDeactivated=!0,Dt(),Xt("user"),Gt()}),!0):!1:Vt?(Ae.manuallyDeactivated=!0,Dt(),tn("user"),!0):!1},injectMessage(l){return!P&&y&&ot(!0,"system"),T.injectMessage(l)},injectAssistantMessage(l){!P&&y&&ot(!0,"system");let u=T.injectAssistantMessage(l);return L&&(L=!1,F&&(clearTimeout(F),F=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),u},injectUserMessage(l){return!P&&y&&ot(!0,"system"),T.injectUserMessage(l)},injectSystemMessage(l){return!P&&y&&ot(!0,"system"),T.injectSystemMessage(l)},injectMessageBatch(l){return!P&&y&&ot(!0,"system"),T.injectMessageBatch(l)},injectTestMessage(l){!P&&y&&ot(!0,"system"),T.injectTestEvent(l)},async connectStream(l,u){return T.connectStream(l,u)},__pushEventStreamEvent(l){N&&N.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!_||!N||Ge()},hideEventStream(){fe&&pe()},isEventStreamVisible(){return fe},focusInput(){return y&&!P||!he?!1:(he.focus(),!0)},async resolveApproval(l,u){let S=T.getMessages().find(W=>{var M;return W.variant==="approval"&&((M=W.approval)==null?void 0:M.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);return T.resolveApproval(S.approval,u)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){p(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return y&&P},isVoiceActive(){return Ae.active},getState(){return{open:y&&P,launcherEnabled:y,voiceActive:Ae.active,streaming:T.isStreaming()}},showCSATFeedback(l){!P&&y&&ot(!0,"system");let u=ze.querySelector(".tvw-feedback-container");u&&u.remove();let h=Fr({onSubmit:async(S,W)=>{var M;T.isClientTokenMode()&&await T.submitCSATFeedback(S,W),(M=l==null?void 0:l.onSubmit)==null||M.call(l,S,W)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!P&&y&&ot(!0,"system");let u=ze.querySelector(".tvw-feedback-container");u&&u.remove();let h=$r({onSubmit:async(S,W)=>{var M;T.isClientTokenMode()&&await T.submitNPSFeedback(S,W),(M=l==null?void 0:l.onSubmit)==null||M.call(l,S,W)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return T.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return T.submitNPSFeedback(l,u)},destroy(){Ze.forEach(l=>l()),je.remove(),Qe==null||Qe.destroy(),et==null||et.remove(),rn&&te.removeEventListener("click",rn)}};if((((Vr=r==null?void 0:r.debugTools)!=null?Vr:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:h=>h?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ze.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),u=h=>{let S=h.detail;(!(S!=null&&S.instanceId)||S.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",u),Ze.push(()=>{window.removeEventListener("persona:focusInput",u)}),_){let h=W=>{let M=W.detail;(!(M!=null&&M.instanceId)||M.instanceId===l)&&Lt.showEventStream()},S=W=>{let M=W.detail;(!(M!=null&&M.instanceId)||M.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",h),window.addEventListener("persona:hideEventStream",S),Ze.push(()=>{window.removeEventListener("persona:showEventStream",h),window.removeEventListener("persona:hideEventStream",S)})}}let $t=Hl(e.persistState);if($t&&y){let l=Bl($t.storage),u=`${$t.keyPrefix}widget-open`,h=`${$t.keyPrefix}widget-voice`,S=`${$t.keyPrefix}widget-voice-mode`;if(l){let W=((zr=$t.persist)==null?void 0:zr.openState)&&l.getItem(u)==="true",M=((Jr=$t.persist)==null?void 0:Jr.voiceState)&&l.getItem(h)==="true",j=((Kr=$t.persist)==null?void 0:Kr.voiceState)&&l.getItem(S)==="true";if(W&&setTimeout(()=>{Lt.open(),setTimeout(()=>{var le;if(M||j)Lt.startVoiceRecognition();else if((le=$t.persist)!=null&&le.focusInput){let de=n.querySelector("textarea");de&&de.focus()}},100)},0),(Yr=$t.persist)!=null&&Yr.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Xr=$t.persist)!=null&&Xr.voiceState&&(s.on("voice:state",le=>{l.setItem(h,le.active?"true":"false")}),s.on("user:message",le=>{l.setItem(S,le.viaVoice?"true":"false")})),$t.clearOnChatClear){let le=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(S)},de=()=>le();window.addEventListener("persona:clear-chat",de),Ze.push(()=>{window.removeEventListener("persona:clear-chat",de)})}}}return Lt};var Dr={},Fl=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},$l=()=>{try{if(typeof Dr!="undefined"&&Dr.url)return new URL("../widget.css",Dr.url).href}catch{}return null},fa=n=>{let t=$l(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-persona","true"),n.insertBefore(e,n.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&t){let o=document.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},va=n=>{var c,v,p,m;let t=Fl(n.target),r=document.createElement("div");r.className="persona-host";let e=(p=(v=(c=n.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?p:!0;e||(r.style.height="100%"),t.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let w=r.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),fa(w)}else i=r,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),fa(r);t.id&&s.setAttribute("data-persona-instance",t.id);let a=Or(s,n.config,{debugTools:n.debugTools});(m=n.onReady)==null||m.call(n);let d={...a,host:r,destroy(){a.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=d),d};var wa={name:"@runtypelabs/persona",version:"1.48.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var Zn=wa.version;function hn(n){if(n!==void 0)return typeof n=="string"?n:Array.isArray(n)?`[${n.map(t=>t.toString()).join(", ")}]`:n.toString()}function Ol(n){if(n)return{getHeaders:hn(n.getHeaders),onFeedback:hn(n.onFeedback),onCopy:hn(n.onCopy),requestMiddleware:hn(n.requestMiddleware),actionHandlers:hn(n.actionHandlers),actionParsers:hn(n.actionParsers),postprocessMessage:hn(n.postprocessMessage),contextProviders:hn(n.contextProviders),streamParser:hn(n.streamParser)}}var ya=`({ 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 ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=
70
70
  if (parsed.action) return { type: parsed.action, payload: parsed };
71
71
  } catch (e) { return null; }
72
72
  return null;
73
- }`,ga=`function(ctx) {
73
+ }`,ba=`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 ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=
83
83
  if (parsed.action) return { type: parsed.action, payload: parsed };
84
84
  } catch (e) { return null; }
85
85
  return null;
86
- }`,ma=`(action: any, context: any) => {
86
+ }`,Ca=`(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 ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=
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
- }`,ha=`function(action, context) {
103
+ }`,xa=`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 ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=
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
- }`,Rl=`(parsed: any) => {
120
+ }`,Dl=`(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
- }`,Hl=`function(parsed) {
126
+ }`,jl=`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 Bl(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Zs(n){var t,r;return(r=(t=n.parserType)!=null?t:Bl(n.streamParser))!=null?r:"plain"}function Qs(n,t){let r=[];return n.toolCall&&(r.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,o])=>{typeof o=="string"&&r.push(`${t} ${e}: "${o}",`)}),r.push(`${t}},`)),r}function er(n,t,r){let e=[],o=n.messageActions&&Object.entries(n.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)&&(e.push(`${t}messageActions: {`),n.messageActions&&Object.entries(n.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?e.push(`${t} ${i}: "${a}",`):typeof a=="boolean"&&e.push(`${t} ${i}: ${a},`))}),r!=null&&r.onFeedback&&e.push(`${t} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&e.push(`${t} onCopy: ${r.onCopy},`),e.push(`${t}},`)),e}function tr(n,t){let r=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,o=n.markdown.disableDefaultStyles!==void 0;(e||o)&&(r.push(`${t}markdown: {`),e&&(r.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`)}),r.push(`${t} },`)),o&&r.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),r.push(`${t}},`))}return r}function nr(n,t){let r=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(s=>s!=="render"),o=n.layout.messages&&Object.keys(n.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||o)&&(r.push(`${t}layout: {`),e&&(r.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),o&&(r.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${t} avatar: {`),Object.entries(i).forEach(([a,u])=>{typeof u=="string"?r.push(`${t} ${a}: "${u}",`):typeof u=="boolean"&&r.push(`${t} ${a}: ${u},`)}),r.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([u])=>u!=="format")&&(r.push(`${t} timestamp: {`),Object.entries(i).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?r.push(`${t} ${u}: "${c}",`):typeof c=="boolean"&&r.push(`${t} ${u}: ${c},`))}),r.push(`${t} },`)):typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),r.push(`${t}},`))}return r}function Nr(n,t){let r=[];return n&&(n.getHeaders&&r.push(`${t}getHeaders: ${n.getHeaders},`),n.requestMiddleware&&r.push(`${t}requestMiddleware: ${n.requestMiddleware},`),n.actionParsers&&r.push(`${t}actionParsers: ${n.actionParsers},`),n.actionHandlers&&r.push(`${t}actionHandlers: ${n.actionHandlers},`),n.contextProviders&&r.push(`${t}contextProviders: ${n.contextProviders},`),n.streamParser&&r.push(`${t}streamParser: ${n.streamParser},`)),r}function Fl(n,t="esm",r){let e={...n};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:Pl(r.hooks)}:void 0;return t==="esm"?$l(e,o):t==="script-installer"?Dl(e):t==="script-advanced"?_l(e,o):t==="react-component"?Ol(e,o):t==="react-advanced"?Nl(e,o):jl(e,o)}function $l(n,t){let r=t==null?void 0:t.hooks,e=Zs(n),o=e!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Qs(n," ")),s.push(...er(n," ",r)),s.push(...tr(n," ")),s.push(...nr(n," ")),s.push(...Nr(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
- `)}function Ol(n,t){let r=t==null?void 0:t.hooks,e=Zs(n),o=e!=="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 n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Qs(n," ")),s.push(...er(n," ",r)),s.push(...tr(n," ")),s.push(...nr(n," ")),s.push(...Nr(r," ")),n.debug&&s.push(` debug: ${n.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 Nl(n,t){let r=t==null?void 0:t.hooks,e=["// 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 n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&e.push(` clientToken: "${n.clientToken}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"?e.push(` ${o}: ${s},`):typeof s=="number"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{e.push(` ${o}: ${s},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...Qs(n," ")),e.push(...er(n," ",r)),e.push(...tr(n," ")),e.push(...nr(n," ")),r!=null&&r.getHeaders&&e.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&e.push(` contextProviders: ${r.contextProviders},`),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?e.push(` streamParser: ${r.streamParser},`):(e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(` streamParser: () => createFlexibleJsonStreamParser(${Rl}),`)),r!=null&&r.actionParsers?(e.push(" // Action parsers (custom merged with defaults)"),e.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),e.push(" // Built-in parser for markdown-wrapped JSON"),e.push(` ${pa}`),e.push(" ],")):(e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Parser for markdown-wrapped JSON"),e.push(` ${pa}`),e.push(" ],")),r!=null&&r.actionHandlers?(e.push(" // Action handlers (custom merged with defaults)"),e.push(` actionHandlers: [...(${r.actionHandlers}),`),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Built-in handler for nav_then_click action"),e.push(` ${ma}`),e.push(" ],")):(e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(` ${ma}`),e.push(" ],")),r!=null&&r.postprocessMessage?e.push(` postprocessMessage: ${r.postprocessMessage},`):e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(e.push(" // Request middleware (custom merged with DOM context)"),e.push(" requestMiddleware: ({ payload, config }) => {"),e.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),e.push(" const merged = customResult || payload;"),e.push(" return {"),e.push(" ...merged,"),e.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),e.push(" };"),e.push(" }")):(e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }")),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('persona:message', handleMessage);"),e.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('persona:message', handleMessage);"),e.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
135
- `)}function fa(n){var o;let t=Zs(n),r=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.clientToken&&(e.clientToken=n.clientToken),n.flowId&&(e.flowId=n.flowId),r&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((o=n.suggestionChips)==null?void 0:o.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let s={};Object.entries(n.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(e.toolCall=s)}if(n.messageActions){let s={};Object.entries(n.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&&(e.messageActions=s)}if(n.markdown){let s={};n.markdown.options&&(s.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(n.layout){let s={};if(n.layout.header){let i={};Object.entries(n.layout.header).forEach(([a,u])=>{a!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(i[a]=u)}),Object.keys(i).length>0&&(s.header=i)}if(n.layout.messages){let i={};Object.entries(n.layout.messages).forEach(([a,u])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof u=="object"&&u!==null)i.avatar=u;else if(a==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([v,d])=>{v!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[v]=d)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(i[a]=u)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function Dl(n){let t=fa(n),r=JSON.stringify(t,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Yn}/dist/install.global.js" data-config='${r}'></script>`}function jl(n,t){let r=t==null?void 0:t.hooks,e=Zs(n),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Yn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Yn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Qs(n," ")),s.push(...er(n," ",r)),s.push(...tr(n," ")),s.push(...nr(n," ")),s.push(...Nr(r," ")),n.debug&&s.push(` debug: ${n.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 _l(n,t){let r=t==null?void 0:t.hooks,e=fa(n),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(e,null,2).split(`
132
+ }`;function _l(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function er(n){var t,r;return(r=(t=n.parserType)!=null?t:_l(n.streamParser))!=null?r:"plain"}function tr(n,t){let r=[];return n.toolCall&&(r.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,o])=>{typeof o=="string"&&r.push(`${t} ${e}: "${o}",`)}),r.push(`${t}},`)),r}function nr(n,t,r){let e=[],o=n.messageActions&&Object.entries(n.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)&&(e.push(`${t}messageActions: {`),n.messageActions&&Object.entries(n.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?e.push(`${t} ${i}: "${a}",`):typeof a=="boolean"&&e.push(`${t} ${i}: ${a},`))}),r!=null&&r.onFeedback&&e.push(`${t} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&e.push(`${t} onCopy: ${r.onCopy},`),e.push(`${t}},`)),e}function sr(n,t){let r=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,o=n.markdown.disableDefaultStyles!==void 0;(e||o)&&(r.push(`${t}markdown: {`),e&&(r.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`)}),r.push(`${t} },`)),o&&r.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),r.push(`${t}},`))}return r}function rr(n,t){let r=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(s=>s!=="render"),o=n.layout.messages&&Object.keys(n.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||o)&&(r.push(`${t}layout: {`),e&&(r.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),o&&(r.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${t} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?r.push(`${t} ${a}: "${d}",`):typeof d=="boolean"&&r.push(`${t} ${a}: ${d},`)}),r.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(r.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?r.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&r.push(`${t} ${d}: ${c},`))}),r.push(`${t} },`)):typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),r.push(`${t}},`))}return r}function jr(n,t){let r=[];return n&&(n.getHeaders&&r.push(`${t}getHeaders: ${n.getHeaders},`),n.requestMiddleware&&r.push(`${t}requestMiddleware: ${n.requestMiddleware},`),n.actionParsers&&r.push(`${t}actionParsers: ${n.actionParsers},`),n.actionHandlers&&r.push(`${t}actionHandlers: ${n.actionHandlers},`),n.contextProviders&&r.push(`${t}contextProviders: ${n.contextProviders},`),n.streamParser&&r.push(`${t}streamParser: ${n.streamParser},`)),r}function Ul(n,t="esm",r){let e={...n};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:Ol(r.hooks)}:void 0;return t==="esm"?ql(e,o):t==="script-installer"?Jl(e):t==="script-advanced"?Yl(e,o):t==="react-component"?Vl(e,o):t==="react-advanced"?zl(e,o):Kl(e,o)}function ql(n,t){let r=t==null?void 0:t.hooks,e=er(n),o=e!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...tr(n," ")),s.push(...nr(n," ",r)),s.push(...sr(n," ")),s.push(...rr(n," ")),s.push(...jr(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
+ `)}function Vl(n,t){let r=t==null?void 0:t.hooks,e=er(n),o=e!=="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 n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...tr(n," ")),s.push(...nr(n," ",r)),s.push(...sr(n," ")),s.push(...rr(n," ")),s.push(...jr(r," ")),n.debug&&s.push(` debug: ${n.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 zl(n,t){let r=t==null?void 0:t.hooks,e=["// 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 n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&e.push(` clientToken: "${n.clientToken}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"?e.push(` ${o}: ${s},`):typeof s=="number"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{e.push(` ${o}: ${s},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...tr(n," ")),e.push(...nr(n," ",r)),e.push(...sr(n," ")),e.push(...rr(n," ")),r!=null&&r.getHeaders&&e.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&e.push(` contextProviders: ${r.contextProviders},`),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?e.push(` streamParser: ${r.streamParser},`):(e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(` streamParser: () => createFlexibleJsonStreamParser(${Dl}),`)),r!=null&&r.actionParsers?(e.push(" // Action parsers (custom merged with defaults)"),e.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),e.push(" // Built-in parser for markdown-wrapped JSON"),e.push(` ${ya}`),e.push(" ],")):(e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Parser for markdown-wrapped JSON"),e.push(` ${ya}`),e.push(" ],")),r!=null&&r.actionHandlers?(e.push(" // Action handlers (custom merged with defaults)"),e.push(` actionHandlers: [...(${r.actionHandlers}),`),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Built-in handler for nav_then_click action"),e.push(` ${Ca}`),e.push(" ],")):(e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(` ${Ca}`),e.push(" ],")),r!=null&&r.postprocessMessage?e.push(` postprocessMessage: ${r.postprocessMessage},`):e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(e.push(" // Request middleware (custom merged with DOM context)"),e.push(" requestMiddleware: ({ payload, config }) => {"),e.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),e.push(" const merged = customResult || payload;"),e.push(" return {"),e.push(" ...merged,"),e.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),e.push(" };"),e.push(" }")):(e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }")),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('persona:message', handleMessage);"),e.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('persona:message', handleMessage);"),e.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
135
+ `)}function Sa(n){var o;let t=er(n),r=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.clientToken&&(e.clientToken=n.clientToken),n.flowId&&(e.flowId=n.flowId),r&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((o=n.suggestionChips)==null?void 0:o.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let s={};Object.entries(n.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(e.toolCall=s)}if(n.messageActions){let s={};Object.entries(n.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&&(e.messageActions=s)}if(n.markdown){let s={};n.markdown.options&&(s.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(n.layout){let s={};if(n.layout.header){let i={};Object.entries(n.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(n.layout.messages){let i={};Object.entries(n.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 c={};Object.entries(d).forEach(([v,p])=>{v!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[v]=p)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function Jl(n){let t=Sa(n),r=JSON.stringify(t,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Zn}/dist/install.global.js" data-config='${r}'></script>`}function Kl(n,t){let r=t==null?void 0:t.hooks,e=er(n),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Zn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Zn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...tr(n," ")),s.push(...nr(n," ",r)),s.push(...sr(n," ")),s.push(...rr(n," ")),s.push(...jr(r," ")),n.debug&&s.push(` debug: ${n.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 Yl(n,t){let r=t==null?void 0:t.hooks,e=Sa(n),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(e,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@${Yn}/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(${Hl});`),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(` ${ga}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${ga}`),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(` ${ha}`),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(` ${ha}`),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 bu=da;export{On as AgentWidgetClient,ys as AgentWidgetSession,jn as AttachmentManager,ra as DEFAULT_DARK_THEME,sa as DEFAULT_LIGHT_THEME,it as DEFAULT_WIDGET_CONFIG,Yn as VERSION,_n as attachHeaderToContainer,xs as buildComposer,Vi as buildDefaultHeader,qi as buildExpandedHeader,yn as buildHeader,Cs as buildHeaderWithLayout,Ui as buildMinimalHeader,Ts as componentRegistry,Gs as createActionManager,$r as createAgentExperience,wr as createBestAvailableVoiceProvider,el as createBubbleWithLayout,Hr as createCSATFeedback,xl as createComponentMiddleware,Lr as createComponentStreamParser,xa as createDirectivePostprocessor,Ma as createFlexibleJsonStreamParser,Ba as createImagePart,pr as createJsonStreamParser,kr as createLocalStorageAdapter,Ds as createMarkdownProcessor,js as createMarkdownProcessorFromConfig,Gi as createMessageActions,Br as createNPSFeedback,dr as createPlainTextParser,ur as createRegexJsonParser,Ss as createStandardBubble,fr as createTextPart,Vn as createTypingIndicator,Dn as createVoiceProvider,gr as createXmlParser,bu as default,Jn as defaultActionHandlers,Xs as defaultJsonActionParser,Sa as directivePostprocessor,cr as escapeHtml,Rr as extractComponentDirectiveFromMessage,Fa as fileToImagePart,Nn as generateAssistantMessageId,Fl as generateCodeSnippet,La as generateMessageId,ws as generateUserMessageId,Pa as getDisplayText,zi as getHeaderLayout,Ha as getImageParts,Pr as hasComponentDirective,Ra as hasImages,yr as headerLayouts,da as initAgentWidget,Cl as isComponentDirectiveType,zs as isVoiceSupported,Ii as markdownPostprocessor,Tr as mergeWithDefaults,Wa as normalizeContent,Ys as pluginRegistry,Wr as renderComponentDirective,Xi as renderLoadingIndicatorWithFallback,$a as validateImageFile};
138
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Zn}/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(${jl});`),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(` ${ba}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${ba}`),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(` ${xa}`),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(` ${xa}`),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 Lu=va;export{jn as AgentWidgetClient,vs as AgentWidgetSession,qn as AttachmentManager,ua as DEFAULT_DARK_THEME,da as DEFAULT_LIGHT_THEME,lt as DEFAULT_WIDGET_CONFIG,Zn as VERSION,Vn as attachHeaderToContainer,bs as buildComposer,Xi as buildDefaultHeader,Zi as buildExpandedHeader,Cn as buildHeader,ys as buildHeaderWithLayout,Gi as buildMinimalHeader,As as componentRegistry,Qs as createActionManager,Or as createAgentExperience,yr as createBestAvailableVoiceProvider,al as createBubbleWithLayout,Fr as createCSATFeedback,Il as createComponentMiddleware,Pr as createComponentStreamParser,Ia as createDirectivePostprocessor,Ha as createFlexibleJsonStreamParser,_a as createImagePart,hr as createJsonStreamParser,Lr as createLocalStorageAdapter,Ds as createMarkdownProcessor,js as createMarkdownProcessorFromConfig,ra as createMessageActions,$r as createNPSFeedback,pr as createPlainTextParser,gr as createRegexJsonParser,Cs as createStandardBubble,wr as createTextPart,zn as createTypingIndicator,Un as createVoiceProvider,mr as createXmlParser,Lu as default,Xn as defaultActionHandlers,Zs as defaultJsonActionParser,La as directivePostprocessor,ur as escapeHtml,Br as extractComponentDirectiveFromMessage,Ua as fileToImagePart,_n as generateAssistantMessageId,Ul as generateCodeSnippet,$a as generateMessageId,ms as generateUserMessageId,Oa as getDisplayText,Qi as getHeaderLayout,ja as getImageParts,Hr as hasComponentDirective,Da as hasImages,Cr as headerLayouts,va as initAgentWidget,kl as isComponentDirectiveType,Ks as isVoiceSupported,Fi as markdownPostprocessor,kr as mergeWithDefaults,Na as normalizeContent,Gs as pluginRegistry,Rr as renderComponentDirective,sa as renderLoadingIndicatorWithFallback,qa as validateImageFile};
140
140
  //# sourceMappingURL=index.js.map