@runtypelabs/persona 1.44.1 → 1.44.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +29 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.global.js +51 -51
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +29 -29
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/message-bubble.ts +123 -2
- package/src/session.ts +2 -1
- package/src/ui.ts +66 -0
- package/src/utils/attachment-manager.ts +8 -2
- package/src/utils/content.ts +5 -0
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{Marked as
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")
|
|
1
|
+
import{Marked as ea}from"marked";var ta=e=>{if(e)return e},ys=e=>{var o,s;let n=e==null?void 0:e.markedOptions,r=new ea({gfm:(o=n==null?void 0:n.gfm)!=null?o:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),t=ta(e==null?void 0:e.renderer);return t&&r.use({renderer:t}),i=>r.parse(i)},bs=e=>e?ys({markedOptions:e.options,renderer:e.renderer}):ys(),na=ys(),di=e=>na(e),$s=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ci=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),li=e=>`%%FORM_PLACEHOLDER_${e}%%`,ui=(e,n)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=li(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=li(n.length);return n.push({token:s,type:o}),s}),r},sa=e=>{let n=bs(e);return r=>{let t=[],o=ui(r,t),s=n(o);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${ci(a)}"></div>`;s=s.replace(d,v)}),s}},ra=e=>{let n=[],r=ui(e,n),t=di(r);return n.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${ci(s)}"></div>`;t=t.replace(i,d)}),t};import{parse as pi,STR as gi,OBJ as mi}from"partial-json";var Cs=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Os=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},oa=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),r=(a=e.startedAt)!=null?a:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},fi=e=>e.status==="complete"?oa(e):e.status==="pending"?"Waiting":"",ia=e=>{var o,s,i;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((i=(s=e.startedAt)!=null?s:e.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var hi=e=>e.status==="complete"?ia(e):"Using tool...",aa=()=>{let e=null,n=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=t.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},xs=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Os=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ns=()=>{var n;let e=oa();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Ds=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=ci(r,ui|pi);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Cs(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Cs(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},ia=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Cs(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Cs(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let a=ci(s,ui|pi),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},js=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var aa="https://api.runtype.com/v1/dispatch",hi="https://api.runtype.com",_s=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function la(e){switch(e){case"json":return Ds;case"regex-json":return Ns;case"xml":return js;case"plain":default:return Os}}var An=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,t,o;this.apiUrl=(r=n.apiUrl)!=null?r:aa,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:la(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var t;let r=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||hi;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(r=(n=this.config).onSessionInit)==null||r.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||hi}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"nps",rating:n,comment:r})}async dispatch(n,r){return this.isAgentMode()?this.dispatchAgent(n,r):this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let f=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:f}),f}let g=await this.buildPayload(n.messages),w=g.metadata?Object.fromEntries(Object.entries(g.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,c={sessionId:d.sessionId,messages:n.messages.filter(_s).map(f=>{var x,C,E;return{id:f.id,role:f.role,content:(E=(C=(x=f.contentParts)!=null?x:f.llmContent)!=null?C:f.rawContent)!=null?E:f.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...w&&Object.keys(w).length>0&&{metadata:w},...g.context&&{context:g.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c);let h=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c),signal:t.signal});if(!h.ok){let f=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let C=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:C}),C}if(h.status===429){let C=new Error(f.hint||"Message limit reached for this session.");throw r({type:"error",error:C}),C}let x=new Error(f.error||"Failed to send message");throw r({type:"error",error:x}),x}if(!h.body){let f=new Error("No response body received");throw r({type:"error",error:f}),f}r({type:"status",status:"connected"});try{await this.streamResponse(h.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let g=d instanceof Error?d:new Error(String(d));throw!g.message.includes("Session expired")&&!g.message.includes("Message limit")&&r({type:"error",error:g}),g}}async dispatchProxy(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(_s).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),t={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}return t}async buildPayload(n){let t={messages:n.slice().filter(_s).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(n,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,t){var pe,Ue,it,Tt,$t,Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt,Q,Oe,bt,Wt,Mt,j,Ze,We,z,R,he,ue,te,Le,Ne,q,de,Be,Je,st,vn,rt,Jt,Rn,rn,Kt,F,on,Gt,cn,Fn,Qt,Zt,yn,bn,os,is,as,$n,Cn,Ke,On,Nn,en,ls,ds,Dn,un,tn,cs,us,ps,Bs,pn,gn,et,xn,jn,_n,qn,Ht,Nt,nn,Yt,zn,mn,qt,gs,Sn,ms,hs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,g=()=>a+d++,w=B=>{let ne=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,ae=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Xe=B.tools?B.tools.map(pt=>({...pt,chunks:pt.chunks?[...pt.chunks]:void 0})):void 0;return{...B,reasoning:ne,toolCall:ae,tools:Xe}},c=B=>{r({type:"message",message:w(B)})},h=null,f={current:null},x=new Map,C=new Map,E={lastId:null,byStep:new Map},S={lastId:null,byCall:new Map},k=B=>{if(B==null)return null;try{return String(B)}catch{return null}},V=B=>{var ne,ae,Xe,pt,Et;return k((Et=(pt=(Xe=(ae=(ne=B.stepId)!=null?ne:B.step_id)!=null?ae:B.step)!=null?Xe:B.parentId)!=null?pt:B.flowStepId)!=null?Et:B.flow_step_id)},y=B=>{var ne,ae,Xe,pt,Et,at,m;return k((m=(at=(Et=(pt=(Xe=(ae=(ne=B.callId)!=null?ne:B.call_id)!=null?ae:B.requestId)!=null?Xe:B.request_id)!=null?pt:B.toolCallId)!=null?Et:B.tool_call_id)!=null?at:B.stepId)!=null?m:B.step_id)},O=()=>h||(h={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g()},c(h),h),W=(B,ne)=>{E.lastId=ne,B&&E.byStep.set(B,ne)},H=(B,ne)=>{var Et;let ae=(Et=B.reasoningId)!=null?Et:B.id,Xe=V(B);if(ae){let at=String(ae);return W(Xe,at),at}if(Xe){let at=E.byStep.get(Xe);if(at)return E.lastId=at,at}if(E.lastId&&!ne)return E.lastId;if(!ne)return null;let pt=`reason-${g()}`;return W(Xe,pt),pt},oe=B=>{let ne=x.get(B);if(ne)return ne;let ae={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:B,status:"streaming",chunks:[]}};return x.set(B,ae),c(ae),ae},_=(B,ne)=>{S.lastId=ne,B&&S.byCall.set(B,ne)},le=(B,ne)=>{var Et;let ae=(Et=B.toolId)!=null?Et:B.id,Xe=y(B);if(ae){let at=String(ae);return _(Xe,at),at}if(Xe){let at=S.byCall.get(Xe);if(at)return S.lastId=at,at}if(S.lastId&&!ne)return S.lastId;if(!ne)return null;let pt=`tool-${g()}`;return _(Xe,pt),pt},X=B=>{let ne=C.get(B);if(ne)return ne;let ae={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:B,status:"pending"}};return C.set(B,ae),c(ae),ae},U=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let ne=Number(B);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let ae=Date.parse(B);if(!Number.isNaN(ae))return ae}return Date.now()},Se=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},N=new Map,re=new Map,D=null,Z=new Map,ve=(pe=this.config.iterationDisplay)!=null?pe:"separate";for(;;){let{done:B,value:ne}=await o.read();if(B)break;i+=s.decode(ne,{stream:!0});let ae=i.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},xs=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ns=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ds=()=>{var n;let e=aa();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},_s=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=pi(r,gi|mi);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Cs(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Cs(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},la=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Cs(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Cs(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let a=pi(s,gi|mi),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},js=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var da="https://api.runtype.com/v1/dispatch",wi="https://api.runtype.com",qs=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ca(e){switch(e){case"json":return _s;case"regex-json":return Ds;case"xml":return js;case"plain":default:return Ns}}var An=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,t,o;this.apiUrl=(r=n.apiUrl)!=null?r:da,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:ca(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var t;let r=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||wi;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(r=(n=this.config).onSessionInit)==null||r.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||wi}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"nps",rating:n,comment:r})}async dispatch(n,r){return this.isAgentMode()?this.dispatchAgent(n,r):this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let h=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:h}),h}let c=await this.buildPayload(n.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,u={sessionId:d.sessionId,messages:n.messages.filter(qs).map(h=>{var S,C,E;return{id:h.id,role:h.role,content:(E=(C=(S=h.contentParts)!=null?S:h.llmContent)!=null?C:h.rawContent)!=null?E:h.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:t.signal});if(!m.ok){let h=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let C=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:C}),C}if(m.status===429){let C=new Error(h.hint||"Message limit reached for this session.");throw r({type:"error",error:C}),C}let S=new Error(h.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!m.body){let h=new Error("No response body received");throw r({type:"error",error:h}),h}r({type:"status",status:"connected"});try{await this.streamResponse(m.body,r,n.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(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(qs).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),t={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}return t}async buildPayload(n){let t={messages:n.slice().filter(qs).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(n,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,t){var ge,Je,lt,Tt,$t,Oe,Ee,te,me,Ne,Qe,At,ue,Y,ut,pt,ht,Ot,wt,X,He,vt,yt,Q,De,bt,Wt,Mt,_,Ze,Pe,z,B,fe,ce,ne,We,_e,j,le,Fe,Ke,ot,vn,it,Jt,Rn,rn,Kt,F,on,Gt,cn,Fn,Qt,Zt,yn,bn,is,as,ls,$n,Cn,Ye,On,Nn,en,ds,cs,Dn,un,tn,us,ps,gs,Rs,pn,gn,et,xn,_n,jn,qn,zn,Ht,Nt,nn,Yt,Un,mn,qt,ms,Sn,fs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,c=()=>a+d++,v=D=>{let Te=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,ae=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,he=D.tools?D.tools.map(tt=>({...tt,chunks:tt.chunks?[...tt.chunks]:void 0})):void 0;return{...D,reasoning:Te,toolCall:ae,tools:he}},u=D=>{r({type:"message",message:v(D)})},m=null,h={current:null},S=new Map,C=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=D=>{if(D==null)return null;try{return String(D)}catch{return null}},K=D=>{var Te,ae,he,tt,Et;return k((Et=(tt=(he=(ae=(Te=D.stepId)!=null?Te:D.step_id)!=null?ae:D.step)!=null?he:D.parentId)!=null?tt:D.flowStepId)!=null?Et:D.flow_step_id)},y=D=>{var Te,ae,he,tt,Et,nt,f;return k((f=(nt=(Et=(tt=(he=(ae=(Te=D.callId)!=null?Te:D.call_id)!=null?ae:D.requestId)!=null?he:D.request_id)!=null?tt:D.toolCallId)!=null?Et:D.tool_call_id)!=null?nt:D.stepId)!=null?f:D.step_id)},R=()=>m||(m={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(m),m),W=(D,Te)=>{E.lastId=Te,D&&E.byStep.set(D,Te)},H=(D,Te)=>{var Et;let ae=(Et=D.reasoningId)!=null?Et:D.id,he=K(D);if(ae){let nt=String(ae);return W(he,nt),nt}if(he){let nt=E.byStep.get(he);if(nt)return E.lastId=nt,nt}if(E.lastId&&!Te)return E.lastId;if(!Te)return null;let tt=`reason-${c()}`;return W(he,tt),tt},oe=D=>{let Te=S.get(D);if(Te)return Te;let ae={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:D,status:"streaming",chunks:[]}};return S.set(D,ae),u(ae),ae},U=(D,Te)=>{x.lastId=Te,D&&x.byCall.set(D,Te)},re=(D,Te)=>{var Et;let ae=(Et=D.toolId)!=null?Et:D.id,he=y(D);if(ae){let nt=String(ae);return U(he,nt),nt}if(he){let nt=x.byCall.get(he);if(nt)return x.lastId=nt,nt}if(x.lastId&&!Te)return x.lastId;if(!Te)return null;let tt=`tool-${c()}`;return U(he,tt),tt},J=D=>{let Te=C.get(D);if(Te)return Te;let ae={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:D,status:"pending"}};return C.set(D,ae),u(ae),ae},q=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let Te=Number(D);if(!Number.isNaN(Te)&&Number.isFinite(Te))return Te;let ae=Date.parse(D);if(!Number.isNaN(ae))return ae}return Date.now()},pe=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},$=new Map,Z=new Map,P=null,ee=new Map,be=(ge=this.config.iterationDisplay)!=null?ge:"separate";for(;;){let{done:D,value:Te}=await o.read();if(D)break;i+=s.decode(Te,{stream:!0});let ae=i.split(`
|
|
5
5
|
|
|
6
|
-
`);i=(
|
|
7
|
-
`),Et="message",at="";for(let P of pt)P.startsWith("event:")?Et=P.replace("event:","").trim():P.startsWith("data:")&&(at+=P.replace("data:","").trim());if(!at)continue;let m;try{m=JSON.parse(at)}catch(P){r({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let _e=Et!=="message"?Et:(it=m.type)!=null?it:"message";if((Tt=this.onSSEEvent)==null||Tt.call(this,_e,m),this.parseSSEEvent){f.current=h;let P=await this.handleCustomSSEEvent(m,r,f,c,g);if(f.current&&!h&&(h=f.current),P)continue}if(_e==="reason_start"){let P=($t=H(m,!0))!=null?$t:`reason-${g()}`,v=oe(P);v.reasoning=(Fe=v.reasoning)!=null?Fe:{id:P,status:"streaming",chunks:[]},v.reasoning.startedAt=(ee=v.reasoning.startedAt)!=null?ee:U((Ae=m.startedAt)!=null?Ae:m.timestamp),v.reasoning.completedAt=void 0,v.reasoning.durationMs=void 0,v.streaming=!0,v.reasoning.status="streaming",c(v)}else if(_e==="reason_delta"||_e==="reason_chunk"){let P=($e=(ge=H(m,!1))!=null?ge:H(m,!0))!=null?$e:`reason-${g()}`,v=oe(P);v.reasoning=(Qe=v.reasoning)!=null?Qe:{id:P,status:"streaming",chunks:[]},v.reasoning.startedAt=(me=v.reasoning.startedAt)!=null?me:U((At=m.startedAt)!=null?At:m.timestamp);let T=(ut=(ct=(J=m.reasoningText)!=null?J:m.text)!=null?ct:m.delta)!=null?ut:"";if(T&&m.hidden!==!0&&v.reasoning.chunks.push(String(T)),v.reasoning.status=m.done?"complete":"streaming",m.done){v.reasoning.completedAt=U((ft=m.completedAt)!=null?ft:m.timestamp);let se=(Ot=v.reasoning.startedAt)!=null?Ot:Date.now();v.reasoning.durationMs=Math.max(0,((wt=v.reasoning.completedAt)!=null?wt:Date.now())-se)}v.streaming=v.reasoning.status!=="complete",c(v)}else if(_e==="reason_complete"){let P=(Ie=(Y=H(m,!1))!=null?Y:H(m,!0))!=null?Ie:`reason-${g()}`,v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U((vt=m.completedAt)!=null?vt:m.timestamp);let se=(yt=v.reasoning.startedAt)!=null?yt:Date.now();v.reasoning.durationMs=Math.max(0,((Q=v.reasoning.completedAt)!=null?Q:Date.now())-se),v.streaming=!1,c(v)}let T=V(m);T&&E.byStep.delete(T)}else if(_e==="tool_start"){let P=(Oe=le(m,!0))!=null?Oe:`tool-${g()}`,v=X(P),T=(bt=v.toolCall)!=null?bt:{id:P,status:"pending"};T.name=(Wt=m.toolName)!=null?Wt:T.name,T.status="running",m.args!==void 0?T.args=m.args:m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=(j=T.startedAt)!=null?j:U((Mt=m.startedAt)!=null?Mt:m.timestamp),T.completedAt=void 0,T.durationMs=void 0,v.toolCall=T,v.streaming=!0;let se=m.agentContext;(se||m.executionId)&&(v.agentMetadata={executionId:(Ze=se==null?void 0:se.executionId)!=null?Ze:m.executionId,iteration:(We=se==null?void 0:se.iteration)!=null?We:m.iteration}),c(v)}else if(_e==="tool_chunk"||_e==="tool_delta"){let P=(R=(z=le(m,!1))!=null?z:le(m,!0))!=null?R:`tool-${g()}`,v=X(P),T=(he=v.toolCall)!=null?he:{id:P,status:"running"};T.startedAt=(te=T.startedAt)!=null?te:U((ue=m.startedAt)!=null?ue:m.timestamp);let se=(q=(Ne=(Le=m.text)!=null?Le:m.delta)!=null?Ne:m.message)!=null?q:"";se&&(T.chunks=(de=T.chunks)!=null?de:[],T.chunks.push(String(se))),T.status="running",v.toolCall=T,v.streaming=!0;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(st=v.agentMetadata)!=null?st:{executionId:(Be=Ee==null?void 0:Ee.executionId)!=null?Be:m.executionId,iteration:(Je=Ee==null?void 0:Ee.iteration)!=null?Je:m.iteration}),c(v)}else if(_e==="tool_complete"){let P=(rt=(vn=le(m,!1))!=null?vn:le(m,!0))!=null?rt:`tool-${g()}`,v=X(P),T=(Jt=v.toolCall)!=null?Jt:{id:P,status:"running"};T.status="complete",m.result!==void 0&&(T.result=m.result),typeof m.duration=="number"&&(T.duration=m.duration),T.completedAt=U((Rn=m.completedAt)!=null?Rn:m.timestamp);let se=(rn=m.duration)!=null?rn:m.executionTime;if(typeof se=="number")T.durationMs=se;else{let Lt=(Kt=T.startedAt)!=null?Kt:Date.now();T.durationMs=Math.max(0,((F=T.completedAt)!=null?F:Date.now())-Lt)}v.toolCall=T,v.streaming=!1;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(cn=v.agentMetadata)!=null?cn:{executionId:(on=Ee==null?void 0:Ee.executionId)!=null?on:m.executionId,iteration:(Gt=Ee==null?void 0:Ee.iteration)!=null?Gt:m.iteration}),c(v);let Ye=y(m);Ye&&S.byCall.delete(Ye)}else if(_e==="step_chunk"||_e==="step_delta"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=O(),se=(yn=(Zt=(Qt=(Fn=m.text)!=null?Fn:m.delta)!=null?Qt:m.content)!=null?Zt:m.chunk)!=null?yn:"";if(se){let Ye=((bn=re.get(T.id))!=null?bn:"")+se;T.rawContent=Ye,N.has(T.id)||N.set(T.id,this.createStreamParser());let Lt=N.get(T.id),tt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(tt&&re.set(T.id,Ye),Lt.__isPlainTextParser===!0){T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T);continue}let gt=Lt.processChunk(Ye);if(gt instanceof Promise)gt.then(De=>{var lt;let qe=typeof De=="string"?De:(lt=De==null?void 0:De.text)!=null?lt:null;if(qe!==null&&qe.trim()!==""){let ze=h;ze&&ze.id===T.id&&(ze.content=qe,c(ze))}else if(!tt&&!Ye.trim().startsWith("<")){let ze=h;ze&&ze.id===T.id&&(ze.content+=se,re.delete(ze.id),N.delete(ze.id),ze.rawContent=void 0,c(ze))}}).catch(()=>{T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T)});else{let De=typeof gt=="string"?gt:(os=gt==null?void 0:gt.text)!=null?os:null;De!==null&&De.trim()!==""?(T.content=De,c(T)):!tt&&!Ye.trim().startsWith("<")&&(T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T))}}if(m.isComplete){let Ee=(as=(is=m.result)==null?void 0:is.response)!=null?as:T.content;if(Ee){let Ye=re.get(T.id),Lt=Ye!=null?Ye:Se(Ee);T.rawContent=Lt;let tt=N.get(T.id),Ct=null,gt=!1;if(tt&&(Ct=tt.getExtractedText(),Ct===null&&(Ct=xs(Lt)),Ct===null)){let De=tt.processChunk(Lt);De instanceof Promise?(gt=!0,De.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===T.id&&(xt.content=lt,xt.streaming=!1,N.delete(xt.id),re.delete(xt.id),c(xt))}})):Ct=typeof De=="string"?De:($n=De==null?void 0:De.text)!=null?$n:null}if(!gt){Ct!==null&&Ct.trim()!==""?T.content=Ct:re.has(T.id)||(T.content=Se(Ee));let De=N.get(T.id);if(De){let qe=(Cn=De.close)==null?void 0:Cn.call(De);qe instanceof Promise&&qe.catch(()=>{}),N.delete(T.id)}re.delete(T.id),T.streaming=!1,c(T)}}}}else if(_e==="step_complete"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=(Ke=m.result)==null?void 0:Ke.response,se=O();if(T!=null){let Ee=N.get(se.id),Ye=!1,Lt=!1;if(Ee){let tt=Ee.getExtractedText(),Ct=re.get(se.id),gt=Ct!=null?Ct:Se(T);if(se.rawContent=gt,tt!==null&&tt.trim()!=="")se.content=tt,Ye=!0;else{let De=xs(gt);if(De!==null)se.content=De,Ye=!0;else{let qe=Ee.processChunk(gt);if(qe instanceof Promise)Lt=!0,qe.then(lt=>{var xt;let ze=typeof lt=="string"?lt:(xt=lt==null?void 0:lt.text)!=null?xt:null;if(ze!==null&&ze.trim()!==""){let Rt=h;Rt&&Rt.id===se.id&&(Rt.content=ze,Rt.streaming=!1,N.delete(Rt.id),re.delete(Rt.id),c(Rt))}else{let Rt=Ee.getExtractedText(),_t=h;_t&&_t.id===se.id&&(Rt!==null&&Rt.trim()!==""?_t.content=Rt:re.has(_t.id)||(_t.content=Se(T)),_t.streaming=!1,N.delete(_t.id),re.delete(_t.id),c(_t))}});else{let lt=typeof qe=="string"?qe:(On=qe==null?void 0:qe.text)!=null?On:null;if(lt!==null&<.trim()!=="")se.content=lt,Ye=!0;else{let ze=Ee.getExtractedText();ze!==null&&ze.trim()!==""&&(se.content=ze,Ye=!0)}}}}}if(!Lt){if(!se.rawContent){let tt=re.get(se.id);se.rawContent=tt!=null?tt:Se(T)}if(!Ye&&!re.has(se.id)&&(se.content=Se(T)),Ee){let tt=(Nn=Ee.close)==null?void 0:Nn.call(Ee);tt instanceof Promise&&tt.catch(()=>{})}N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}}else N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}else if(_e==="flow_complete"){let P=(en=m.result)==null?void 0:en.response;if(P!=null){let v=O(),T=re.get(v.id),se=T!=null?T:Se(P);v.rawContent=se;let Ee=Se(P),Ye=N.get(v.id);if(Ye){let Ct=xs(se);if(Ct!==null)Ee=Ct;else{let gt=Ye.processChunk(se);gt instanceof Promise&>.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===v.id&&(xt.content=lt,xt.streaming=!1,c(xt))}});let De=Ye.getExtractedText();De!==null&&(Ee=De)}}N.delete(v.id),re.delete(v.id);let Lt=Ee!==v.content,tt=v.streaming!==!1;Lt&&(v.content=Ee),v.streaming=!1,(Lt||tt)&&c(v)}else if(h!==null){let v=h;N.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,c(v))}r({type:"status",status:"idle"})}else if(_e==="agent_start")D={executionId:m.executionId,agentId:(ls=m.agentId)!=null?ls:"virtual",agentName:(ds=m.agentName)!=null?ds:"",status:"running",currentIteration:0,maxIterations:(Dn=m.maxIterations)!=null?Dn:1,startedAt:U(m.startedAt)};else if(_e==="agent_iteration_start"){if(D&&(D.currentIteration=m.iteration),ve==="separate"&&m.iteration>1){let P=h;P&&(P.streaming=!1,c(P),Z.set(m.iteration-1,P),h=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(m.contentType==="text"){let P=O();P.content+=(un=m.delta)!=null?un:"",P.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:D==null?void 0:D.agentName},c(P)}else if(m.contentType==="thinking"){let P=(tn=m.turnId)!=null?tn:`agent-think-${m.iteration}`,v=oe(P);v.reasoning=(cs=v.reasoning)!=null?cs:{id:P,status:"streaming",chunks:[]},v.reasoning.chunks.push((us=m.delta)!=null?us:""),v.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},c(v)}else if(m.contentType==="tool_input"){let P=(ps=m.toolCallId)!=null?ps:S.lastId;if(P){let v=C.get(P);v!=null&&v.toolCall&&(v.toolCall.chunks=(Bs=v.toolCall.chunks)!=null?Bs:[],v.toolCall.chunks.push((pn=m.delta)!=null?pn:""),c(v))}}}else if(_e==="agent_turn_complete"){let P=m.turnId;if(P){let v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U(m.completedAt);let T=(gn=v.reasoning.startedAt)!=null?gn:Date.now();v.reasoning.durationMs=Math.max(0,((et=v.reasoning.completedAt)!=null?et:Date.now())-T),v.streaming=!1,c(v)}}}else if(_e==="agent_tool_start"){let P=(xn=m.toolCallId)!=null?xn:`agent-tool-${g()}`;_(y(m),P);let v=X(P),T=(jn=v.toolCall)!=null?jn:{id:P,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};T.name=(_n=m.toolName)!=null?_n:T.name,T.status="running",m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=U((qn=m.startedAt)!=null?qn:m.timestamp),v.toolCall=T,v.streaming=!0,v.agentMetadata={executionId:m.executionId,iteration:m.iteration},c(v)}else if(_e==="agent_tool_delta"){let P=(Ht=m.toolCallId)!=null?Ht:S.lastId;if(P){let v=(Nt=C.get(P))!=null?Nt:X(P);v.toolCall&&(v.toolCall.chunks=(nn=v.toolCall.chunks)!=null?nn:[],v.toolCall.chunks.push((Yt=m.delta)!=null?Yt:""),v.toolCall.status="running",v.streaming=!0,c(v))}}else if(_e==="agent_tool_complete"){let P=(zn=m.toolCallId)!=null?zn:S.lastId;if(P){let v=(mn=C.get(P))!=null?mn:X(P);if(v.toolCall){v.toolCall.status="complete",m.result!==void 0&&(v.toolCall.result=m.result),typeof m.executionTime=="number"&&(v.toolCall.durationMs=m.executionTime),v.toolCall.completedAt=U((qt=m.completedAt)!=null?qt:m.timestamp),v.streaming=!1,c(v);let T=y(m);T&&S.byCall.delete(T)}}}else if(_e!=="agent_iteration_complete")if(_e==="agent_reflection"||_e==="agent_reflect"){let P=`agent-reflection-${m.executionId}-${m.iteration}`,v={id:P,role:"assistant",content:(gs=m.reflection)!=null?gs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:g(),reasoning:{id:P,status:"complete",chunks:[(Sn=m.reflection)!=null?Sn:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};c(v)}else if(_e==="agent_complete"){D&&(D.status=m.success?"complete":"error",D.completedAt=U(m.completedAt),D.stopReason=m.stopReason);let P=h;P&&(P.streaming=!1,c(P)),r({type:"status",status:"idle"})}else if(_e==="agent_error"){let P=typeof m.error=="string"?m.error:(hs=(ms=m.error)==null?void 0:ms.message)!=null?hs:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",P):r({type:"error",error:new Error(P)})}else _e==="agent_ping"||_e==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}};function da(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Xn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function En(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Gn=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,t,o,s,i,a,d;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(t=n.message.agentMetadata.agentName)!=null?t:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new An(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(r=(n=this.callbacks).onError)==null||r.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new An(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:t,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:g=!1}=n,c={id:i!=null?i:r==="user"?Xn():r==="assistant"?En():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:g,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(c),c}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let t of n){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:g,sequence:w,streaming:c=!1}=t,f={id:d!=null?d:o==="user"?Xn():o==="assistant"?En():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:g!=null?g:new Date().toISOString(),sequence:w!=null?w:this.nextSequence(),streaming:c,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(f)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var g,w,c,h,f;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(g=this.abortController)==null||g.abort();let o=Xn(),s=En(),i={id:o,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(c=(w=this.callbacks).onError)==null||c.call(w,x):(f=(h=this.callbacks).onError)==null||f.call(h,new Error(String(x))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=En();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(g){let w={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(w),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,g):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(g)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,t)=>{var d,g;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(g=t.sequence)!=null?g:0;return i!==a?i-a:r.id.localeCompare(t.id)})}};var p=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};import*as ca from"lucide";var ie=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=ca[o];return s?ua(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function ua(e,n,r,t){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([g,w])=>{g!=="stroke"&&d.setAttribute(g,String(w))}),o.appendChild(d)}}}),o}function pa(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ga(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function ma(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function ha(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function qs(e){return{type:"text",text:e}}function fa(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function wa(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function va(e,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var fi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ya=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],ln=[...fi,...ya];function ba(e){return fi.includes(e)||e.startsWith("image/")}function Ss(e){return ba(e.type)}async function wi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;Ss(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function vi(e,n=ln,r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ca(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function yi(e,n){let r=Ca(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var As={allowedTypes:ln,maxFileSize:10*1024*1024,maxFiles:4};function xa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Sa(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Tn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,t,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:As.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:As.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:As.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:As.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,o,s,i,a,d,g;if(!n||n.length===0)return;let r=Array.from(n);for(let w of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,w,"count");continue}let c=vi(w,this.config.allowedTypes,this.config.maxFileSize);if(!c.valid){let h=(s=c.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,w,h);continue}try{let h=await wi(w),f=Ss(w)?URL.createObjectURL(w):null,x={id:xa(),file:w,previewUrl:f,contentPart:h};this.attachments.push(x),this.renderPreview(x)}catch(h){console.error("[AttachmentManager] Failed to process file:",h)}}this.updatePreviewsVisibility(),(g=(d=this.config).onAttachmentsChange)==null||g.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(d=>d.id===n);if(r===-1)return;let t=this.attachments[r];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=Ss(n.file),t=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",r&&n.previewUrl){let i=p("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=p("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Sa(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let g=p("span");g.textContent=yi(n.file.type,n.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--cw-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",i.appendChild(g),t.appendChild(i)}let o=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(o),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:r})}};var zs=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Aa=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",r=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||zs()==="dark"?t:r},bi=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(zs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(zs());r.addEventListener?(r.addEventListener("change",t),n.push(()=>r.removeEventListener("change",t))):r.addListener&&(r.addListener(t),n.push(()=>r.removeListener(t)))}return()=>{n.forEach(r=>r())}},Es=(e,n)=>{let r=Aa(n);Object.entries(r).forEach(([t,o])=>{if(o==null||o==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(o))})};import{Idiomorph as Ea}from"idiomorph";var Ci=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;Ea.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&t&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ut={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Qn=(e,n)=>{let r=p("button");r.type="button",r.innerHTML=`
|
|
6
|
+
`);i=(Je=ae.pop())!=null?Je:"";for(let he of ae){let tt=he.split(`
|
|
7
|
+
`),Et="message",nt="";for(let O of tt)O.startsWith("event:")?Et=O.replace("event:","").trim():O.startsWith("data:")&&(nt+=O.replace("data:","").trim());if(!nt)continue;let f;try{f=JSON.parse(nt)}catch(O){r({type:"error",error:O instanceof Error?O:new Error("Failed to parse chat stream payload")});continue}let we=Et!=="message"?Et:(lt=f.type)!=null?lt:"message";if((Tt=this.onSSEEvent)==null||Tt.call(this,we,f),this.parseSSEEvent){h.current=m;let O=await this.handleCustomSSEEvent(f,r,h,u,c);if(h.current&&!m&&(m=h.current),O)continue}if(we==="reason_start"){let O=($t=H(f,!0))!=null?$t:`reason-${c()}`,w=oe(O);w.reasoning=(Oe=w.reasoning)!=null?Oe:{id:O,status:"streaming",chunks:[]},w.reasoning.startedAt=(te=w.reasoning.startedAt)!=null?te:q((Ee=f.startedAt)!=null?Ee:f.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",u(w)}else if(we==="reason_delta"||we==="reason_chunk"){let O=(Ne=(me=H(f,!1))!=null?me:H(f,!0))!=null?Ne:`reason-${c()}`,w=oe(O);w.reasoning=(Qe=w.reasoning)!=null?Qe:{id:O,status:"streaming",chunks:[]},w.reasoning.startedAt=(ue=w.reasoning.startedAt)!=null?ue:q((At=f.startedAt)!=null?At:f.timestamp);let T=(pt=(ut=(Y=f.reasoningText)!=null?Y:f.text)!=null?ut:f.delta)!=null?pt:"";if(T&&f.hidden!==!0&&w.reasoning.chunks.push(String(T)),w.reasoning.status=f.done?"complete":"streaming",f.done){w.reasoning.completedAt=q((ht=f.completedAt)!=null?ht:f.timestamp);let se=(Ot=w.reasoning.startedAt)!=null?Ot:Date.now();w.reasoning.durationMs=Math.max(0,((wt=w.reasoning.completedAt)!=null?wt:Date.now())-se)}w.streaming=w.reasoning.status!=="complete",u(w)}else if(we==="reason_complete"){let O=(He=(X=H(f,!1))!=null?X:H(f,!0))!=null?He:`reason-${c()}`,w=S.get(O);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=q((vt=f.completedAt)!=null?vt:f.timestamp);let se=(yt=w.reasoning.startedAt)!=null?yt:Date.now();w.reasoning.durationMs=Math.max(0,((Q=w.reasoning.completedAt)!=null?Q:Date.now())-se),w.streaming=!1,u(w)}let T=K(f);T&&E.byStep.delete(T)}else if(we==="tool_start"){let O=(De=re(f,!0))!=null?De:`tool-${c()}`,w=J(O),T=(bt=w.toolCall)!=null?bt:{id:O,status:"pending"};T.name=(Wt=f.toolName)!=null?Wt:T.name,T.status="running",f.args!==void 0?T.args=f.args:f.parameters!==void 0&&(T.args=f.parameters),T.startedAt=(_=T.startedAt)!=null?_:q((Mt=f.startedAt)!=null?Mt:f.timestamp),T.completedAt=void 0,T.durationMs=void 0,w.toolCall=T,w.streaming=!0;let se=f.agentContext;(se||f.executionId)&&(w.agentMetadata={executionId:(Ze=se==null?void 0:se.executionId)!=null?Ze:f.executionId,iteration:(Pe=se==null?void 0:se.iteration)!=null?Pe:f.iteration}),u(w)}else if(we==="tool_chunk"||we==="tool_delta"){let O=(B=(z=re(f,!1))!=null?z:re(f,!0))!=null?B:`tool-${c()}`,w=J(O),T=(fe=w.toolCall)!=null?fe:{id:O,status:"running"};T.startedAt=(ne=T.startedAt)!=null?ne:q((ce=f.startedAt)!=null?ce:f.timestamp);let se=(j=(_e=(We=f.text)!=null?We:f.delta)!=null?_e:f.message)!=null?j:"";se&&(T.chunks=(le=T.chunks)!=null?le:[],T.chunks.push(String(se))),T.status="running",w.toolCall=T,w.streaming=!0;let Me=f.agentContext;(Me||f.executionId)&&(w.agentMetadata=(ot=w.agentMetadata)!=null?ot:{executionId:(Fe=Me==null?void 0:Me.executionId)!=null?Fe:f.executionId,iteration:(Ke=Me==null?void 0:Me.iteration)!=null?Ke:f.iteration}),u(w)}else if(we==="tool_complete"){let O=(it=(vn=re(f,!1))!=null?vn:re(f,!0))!=null?it:`tool-${c()}`,w=J(O),T=(Jt=w.toolCall)!=null?Jt:{id:O,status:"running"};T.status="complete",f.result!==void 0&&(T.result=f.result),typeof f.duration=="number"&&(T.duration=f.duration),T.completedAt=q((Rn=f.completedAt)!=null?Rn:f.timestamp);let se=(rn=f.duration)!=null?rn:f.executionTime;if(typeof se=="number")T.durationMs=se;else{let Lt=(Kt=T.startedAt)!=null?Kt:Date.now();T.durationMs=Math.max(0,((F=T.completedAt)!=null?F:Date.now())-Lt)}w.toolCall=T,w.streaming=!1;let Me=f.agentContext;(Me||f.executionId)&&(w.agentMetadata=(cn=w.agentMetadata)!=null?cn:{executionId:(on=Me==null?void 0:Me.executionId)!=null?on:f.executionId,iteration:(Gt=Me==null?void 0:Me.iteration)!=null?Gt:f.iteration}),u(w);let Ve=y(f);Ve&&x.byCall.delete(Ve)}else if(we==="step_chunk"||we==="step_delta"){let O=f.stepType,w=f.executionType;if(O==="tool"||w==="context")continue;let T=R(),se=(yn=(Zt=(Qt=(Fn=f.text)!=null?Fn:f.delta)!=null?Qt:f.content)!=null?Zt:f.chunk)!=null?yn:"";if(se){let Ve=((bn=Z.get(T.id))!=null?bn:"")+se;T.rawContent=Ve,$.has(T.id)||$.set(T.id,this.createStreamParser());let Lt=$.get(T.id),st=Ve.trim().startsWith("{")||Ve.trim().startsWith("[");if(st&&Z.set(T.id,Ve),Lt.__isPlainTextParser===!0){T.content+=se,Z.delete(T.id),$.delete(T.id),T.rawContent=void 0,u(T);continue}let gt=Lt.processChunk(Ve);if(gt instanceof Promise)gt.then(je=>{var dt;let ze=typeof je=="string"?je:(dt=je==null?void 0:je.text)!=null?dt:null;if(ze!==null&&ze.trim()!==""){let Ue=m;Ue&&Ue.id===T.id&&(Ue.content=ze,u(Ue))}else if(!st&&!Ve.trim().startsWith("<")){let Ue=m;Ue&&Ue.id===T.id&&(Ue.content+=se,Z.delete(Ue.id),$.delete(Ue.id),Ue.rawContent=void 0,u(Ue))}}).catch(()=>{T.content+=se,Z.delete(T.id),$.delete(T.id),T.rawContent=void 0,u(T)});else{let je=typeof gt=="string"?gt:(is=gt==null?void 0:gt.text)!=null?is:null;je!==null&&je.trim()!==""?(T.content=je,u(T)):!st&&!Ve.trim().startsWith("<")&&(T.content+=se,Z.delete(T.id),$.delete(T.id),T.rawContent=void 0,u(T))}}if(f.isComplete){let Me=(ls=(as=f.result)==null?void 0:as.response)!=null?ls:T.content;if(Me){let Ve=Z.get(T.id),Lt=Ve!=null?Ve:pe(Me);T.rawContent=Lt;let st=$.get(T.id),Ct=null,gt=!1;if(st&&(Ct=st.getExtractedText(),Ct===null&&(Ct=xs(Lt)),Ct===null)){let je=st.processChunk(Lt);je instanceof Promise?(gt=!0,je.then(ze=>{var Ue;let dt=typeof ze=="string"?ze:(Ue=ze==null?void 0:ze.text)!=null?Ue:null;if(dt!==null){let xt=m;xt&&xt.id===T.id&&(xt.content=dt,xt.streaming=!1,$.delete(xt.id),Z.delete(xt.id),u(xt))}})):Ct=typeof je=="string"?je:($n=je==null?void 0:je.text)!=null?$n:null}if(!gt){Ct!==null&&Ct.trim()!==""?T.content=Ct:Z.has(T.id)||(T.content=pe(Me));let je=$.get(T.id);if(je){let ze=(Cn=je.close)==null?void 0:Cn.call(je);ze instanceof Promise&&ze.catch(()=>{}),$.delete(T.id)}Z.delete(T.id),T.streaming=!1,u(T)}}}}else if(we==="step_complete"){let O=f.stepType,w=f.executionType;if(O==="tool"||w==="context")continue;let T=(Ye=f.result)==null?void 0:Ye.response,se=R();if(T!=null){let Me=$.get(se.id),Ve=!1,Lt=!1;if(Me){let st=Me.getExtractedText(),Ct=Z.get(se.id),gt=Ct!=null?Ct:pe(T);if(se.rawContent=gt,st!==null&&st.trim()!=="")se.content=st,Ve=!0;else{let je=xs(gt);if(je!==null)se.content=je,Ve=!0;else{let ze=Me.processChunk(gt);if(ze instanceof Promise)Lt=!0,ze.then(dt=>{var xt;let Ue=typeof dt=="string"?dt:(xt=dt==null?void 0:dt.text)!=null?xt:null;if(Ue!==null&&Ue.trim()!==""){let Rt=m;Rt&&Rt.id===se.id&&(Rt.content=Ue,Rt.streaming=!1,$.delete(Rt.id),Z.delete(Rt.id),u(Rt))}else{let Rt=Me.getExtractedText(),jt=m;jt&&jt.id===se.id&&(Rt!==null&&Rt.trim()!==""?jt.content=Rt:Z.has(jt.id)||(jt.content=pe(T)),jt.streaming=!1,$.delete(jt.id),Z.delete(jt.id),u(jt))}});else{let dt=typeof ze=="string"?ze:(On=ze==null?void 0:ze.text)!=null?On:null;if(dt!==null&&dt.trim()!=="")se.content=dt,Ve=!0;else{let Ue=Me.getExtractedText();Ue!==null&&Ue.trim()!==""&&(se.content=Ue,Ve=!0)}}}}}if(!Lt){if(!se.rawContent){let st=Z.get(se.id);se.rawContent=st!=null?st:pe(T)}if(!Ve&&!Z.has(se.id)&&(se.content=pe(T)),Me){let st=(Nn=Me.close)==null?void 0:Nn.call(Me);st instanceof Promise&&st.catch(()=>{})}$.delete(se.id),Z.delete(se.id),se.streaming=!1,u(se)}}else $.delete(se.id),Z.delete(se.id),se.streaming=!1,u(se)}else if(we==="flow_complete"){let O=(en=f.result)==null?void 0:en.response;if(O!=null){let w=R(),T=Z.get(w.id),se=T!=null?T:pe(O);w.rawContent=se;let Me=pe(O),Ve=$.get(w.id);if(Ve){let Ct=xs(se);if(Ct!==null)Me=Ct;else{let gt=Ve.processChunk(se);gt instanceof Promise&>.then(ze=>{var Ue;let dt=typeof ze=="string"?ze:(Ue=ze==null?void 0:ze.text)!=null?Ue:null;if(dt!==null){let xt=m;xt&&xt.id===w.id&&(xt.content=dt,xt.streaming=!1,u(xt))}});let je=Ve.getExtractedText();je!==null&&(Me=je)}}$.delete(w.id),Z.delete(w.id);let Lt=Me!==w.content,st=w.streaming!==!1;Lt&&(w.content=Me),w.streaming=!1,(Lt||st)&&u(w)}else if(m!==null){let w=m;$.delete(w.id),Z.delete(w.id),w.streaming!==!1&&(w.streaming=!1,u(w))}r({type:"status",status:"idle"})}else if(we==="agent_start")P={executionId:f.executionId,agentId:(ds=f.agentId)!=null?ds:"virtual",agentName:(cs=f.agentName)!=null?cs:"",status:"running",currentIteration:0,maxIterations:(Dn=f.maxIterations)!=null?Dn:1,startedAt:q(f.startedAt)};else if(we==="agent_iteration_start"){if(P&&(P.currentIteration=f.iteration),be==="separate"&&f.iteration>1){let O=m;O&&(O.streaming=!1,u(O),ee.set(f.iteration-1,O),m=null)}}else if(we!=="agent_turn_start"){if(we==="agent_turn_delta"){if(f.contentType==="text"){let O=R();O.content+=(un=f.delta)!=null?un:"",O.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId,agentName:P==null?void 0:P.agentName},u(O)}else if(f.contentType==="thinking"){let O=(tn=f.turnId)!=null?tn:`agent-think-${f.iteration}`,w=oe(O);w.reasoning=(us=w.reasoning)!=null?us:{id:O,status:"streaming",chunks:[]},w.reasoning.chunks.push((ps=f.delta)!=null?ps:""),w.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId},u(w)}else if(f.contentType==="tool_input"){let O=(gs=f.toolCallId)!=null?gs:x.lastId;if(O){let w=C.get(O);w!=null&&w.toolCall&&(w.toolCall.chunks=(Rs=w.toolCall.chunks)!=null?Rs:[],w.toolCall.chunks.push((pn=f.delta)!=null?pn:""),u(w))}}}else if(we==="agent_turn_complete"){let O=f.turnId;if(O){let w=S.get(O);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=q(f.completedAt);let T=(gn=w.reasoning.startedAt)!=null?gn:Date.now();w.reasoning.durationMs=Math.max(0,((et=w.reasoning.completedAt)!=null?et:Date.now())-T),w.streaming=!1,u(w)}}}else if(we==="agent_tool_start"){let O=(xn=f.toolCallId)!=null?xn:`agent-tool-${c()}`;U(y(f),O);let w=J(O),T=(_n=w.toolCall)!=null?_n:{id:O,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};T.name=(jn=f.toolName)!=null?jn:T.name,T.status="running",f.parameters!==void 0&&(T.args=f.parameters),T.startedAt=q((qn=f.startedAt)!=null?qn:f.timestamp),w.toolCall=T,w.streaming=!0,w.agentMetadata={executionId:f.executionId,iteration:f.iteration},u(w)}else if(we==="agent_tool_delta"){let O=(zn=f.toolCallId)!=null?zn:x.lastId;if(O){let w=(Ht=C.get(O))!=null?Ht:J(O);w.toolCall&&(w.toolCall.chunks=(Nt=w.toolCall.chunks)!=null?Nt:[],w.toolCall.chunks.push((nn=f.delta)!=null?nn:""),w.toolCall.status="running",w.streaming=!0,u(w))}}else if(we==="agent_tool_complete"){let O=(Yt=f.toolCallId)!=null?Yt:x.lastId;if(O){let w=(Un=C.get(O))!=null?Un:J(O);if(w.toolCall){w.toolCall.status="complete",f.result!==void 0&&(w.toolCall.result=f.result),typeof f.executionTime=="number"&&(w.toolCall.durationMs=f.executionTime),w.toolCall.completedAt=q((mn=f.completedAt)!=null?mn:f.timestamp),w.streaming=!1,u(w);let T=y(f);T&&x.byCall.delete(T)}}}else if(we!=="agent_iteration_complete")if(we==="agent_reflection"||we==="agent_reflect"){let O=`agent-reflection-${f.executionId}-${f.iteration}`,w={id:O,role:"assistant",content:(qt=f.reflection)!=null?qt:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:O,status:"complete",chunks:[(ms=f.reflection)!=null?ms:""]},agentMetadata:{executionId:f.executionId,iteration:f.iteration}};u(w)}else if(we==="agent_complete"){P&&(P.status=f.success?"complete":"error",P.completedAt=q(f.completedAt),P.stopReason=f.stopReason);let O=m;O&&(O.streaming=!1,u(O)),r({type:"status",status:"idle"})}else if(we==="agent_error"){let O=typeof f.error=="string"?f.error:(fs=(Sn=f.error)==null?void 0:Sn.message)!=null?fs:"Agent execution error";f.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",O):r({type:"error",error:new Error(O)})}else we==="agent_ping"||we==="error"&&f.error&&r({type:"error",error:f.error instanceof Error?f.error:new Error(String(f.error))})}}}}};function ua(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Gn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function En(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Ss="[Image]";function pa(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ga(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function ma(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function fa(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function zs(e){return{type:"text",text:e}}function ha(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function wa(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function va(e,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var vi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ya=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],ln=[...vi,...ya];function ba(e){return vi.includes(e)||e.startsWith("image/")}function As(e){return ba(e.type)}async function yi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;As(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function bi(e,n=ln,r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ca(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Ci(e,n){let r=Ca(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var Qn=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,t,o,s,i,a,d;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(t=n.message.agentMetadata.agentName)!=null?t:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new An(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(r=(n=this.callbacks).onError)==null||r.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new An(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:t,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:c=!1}=n,u={id:i!=null?i:r==="user"?Gn():r==="assistant"?En():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(u),u}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let t of n){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:c,sequence:v,streaming:u=!1}=t,h={id:d!=null?d:o==="user"?Gn():o==="assistant"?En():`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:u,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(h)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var c,v,u,m,h;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(c=this.abortController)==null||c.abort();let o=Gn(),s=En(),i={id:o,role:"user",content:t||Ss,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(S){let C=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));if(!C){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(S instanceof Error?(u=(v=this.callbacks).onError)==null||u.call(v,S):(h=(m=this.callbacks).onError)==null||h.call(m,new Error(String(S))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=En();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(c){let v={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(v),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,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)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,t)=>{var d,c;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(c=t.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(t.id)})}};var g=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};import*as xa from"lucide";var ie=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=xa[o];return s?Sa(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Sa(e,n,r,t){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,v])=>{c!=="stroke"&&d.setAttribute(c,String(v))}),o.appendChild(d)}}}),o}var Es={allowedTypes:ln,maxFileSize:10*1024*1024,maxFiles:4};function Aa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ea(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Tn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,t,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Es.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Es.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Es.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Es.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var r,t,o,s,i,a,d;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(t=(r=this.config).onFileRejected)==null||t.call(r,c,"count");continue}let v=bi(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let u=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,u);continue}try{let u=await yi(c),m=As(c)?URL.createObjectURL(c):null,h={id:Aa(),file:c,previewUrl:m,contentPart:u};this.attachments.push(h),this.renderPreview(h)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(a=this.config).onAttachmentsChange)==null||d.call(a,this.getAttachments())}}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(d=>d.id===n);if(r===-1)return;let t=this.attachments[r];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=As(n.file),t=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",r&&n.previewUrl){let i=g("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Ea(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let c=g("span");c.textContent=Ci(n.file.type,n.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),t.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(n.id)}),t.appendChild(o),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:r})}};var Us=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ta=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",r=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||Us()==="dark"?t:r},xi=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Us())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(Us());r.addEventListener?(r.addEventListener("change",t),n.push(()=>r.removeEventListener("change",t))):r.addListener&&(r.addListener(t),n.push(()=>r.removeListener(t)))}return()=>{n.forEach(r=>r())}},Ts=(e,n)=>{let r=Ta(n);Object.entries(r).forEach(([t,o])=>{if(o==null||o==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(o))})};import{Idiomorph as Ma}from"idiomorph";var Si=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;Ma.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&t&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ut={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Zn=(e,n)=>{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,16 +12,16 @@ import{Marked as Qi}from"marked";var Zi=e=>{if(e)return e},ys=e=>{var o,s;let n=
|
|
|
12
12
|
<span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
15
|
-
`,r.addEventListener("click",n);let t=s=>{var S,k,V,y,O,W,H,oe,_,le,X,U;let i=(S=s.launcher)!=null?S:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(k=i.title)!=null?k:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(V=i.subtitle)!=null?V:"Get answers fast");let g=r.querySelector(".tvw-flex-col");g&&(i.textHidden?g.style.display="none":g.style.display="");let w=r.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let Se=(y=i.agentIconSize)!=null?y:"40px";if(w.style.height=Se,w.style.width=Se,w.innerHTML="",i.agentIconName){let N=parseFloat(Se)||24,re=ie(i.agentIconName,N*.6,"#ffffff",2);re?(w.appendChild(re),w.style.display=""):(w.textContent=(O=i.agentIconText)!=null?O:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(W=i.agentIconText)!=null?W:"\u{1F4AC}",w.style.display="")}let c=r.querySelector("[data-role='launcher-image']");if(c){let Se=(H=i.agentIconSize)!=null?H:"40px";c.style.height=Se,c.style.width=Se,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(c.src=i.iconUrl,c.style.display="block"):c.style.display="none"}let h=r.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let Se=(oe=i.callToActionIconSize)!=null?oe:"32px";h.style.height=Se,h.style.width=Se,i.callToActionIconBackgroundColor?(h.style.backgroundColor=i.callToActionIconBackgroundColor,h.classList.remove("tvw-bg-cw-primary")):(h.style.backgroundColor="",h.classList.add("tvw-bg-cw-primary"));let N=0;if(i.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=i.callToActionIconPadding,N=(parseFloat(i.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),i.callToActionIconHidden)h.style.display="none";else if(h.style.display="",h.innerHTML="",i.callToActionIconName){let re=parseFloat(Se)||24,D=Math.max(re-N,8),Z=ie(i.callToActionIconName,D,"currentColor",2);Z?h.appendChild(Z):h.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}else h.textContent=(le=i.callToActionIconText)!=null?le:"\u2197"}let f=i.position&&Ut[i.position]?Ut[i.position]:Ut["bottom-right"],x="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${x} ${f}`;let C="1px solid #e5e7eb",E="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(X=i.border)!=null?X:C,r.style.boxShadow=(U=i.shadow)!=null?U:E},o=()=>{r.removeEventListener("click",n),r.remove()};return e&&t(e),{element:r,update:t,destroy:o}};var dn=e=>{var le,X,U,Se,N,re,D,Z,ve,pe,Ue,it,Tt,$t,Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt;let{config:n,showClose:r=!0}=e,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(le=n==null?void 0:n.launcher)!=null?le:{},s=(X=o.headerIconSize)!=null?X:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",a=(Se=o.closeButtonPlacement)!=null?Se:"inline",d=(N=o.headerIconHidden)!=null?N:!1,g=o.headerIconName,w=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=s,w.style.width=s,!d)if(g){let Q=parseFloat(s)||24,Oe=ie(g,Q*.6,"#ffffff",1);Oe?w.replaceChildren(Oe):w.textContent=(D=(re=n==null?void 0:n.launcher)==null?void 0:re.agentIconText)!=null?D:"\u{1F4AC}"}else if((Z=n==null?void 0:n.launcher)!=null&&Z.iconUrl){let Q=p("img");Q.src=n.launcher.iconUrl,Q.alt="",Q.className="tvw-rounded-xl tvw-object-cover",Q.style.height=s,Q.style.width=s,w.replaceChildren(Q)}else w.textContent=(pe=(ve=n==null?void 0:n.launcher)==null?void 0:ve.agentIconText)!=null?pe:"\u{1F4AC}";let c=p("div","tvw-flex tvw-flex-col"),h=p("span","tvw-text-base tvw-font-semibold");h.textContent=(it=(Ue=n==null?void 0:n.launcher)==null?void 0:Ue.title)!=null?it:"Chat Assistant";let f=p("span","tvw-text-xs tvw-text-cw-muted");f.textContent=($t=(Tt=n==null?void 0:n.launcher)==null?void 0:Tt.subtitle)!=null?$t:"Here to help you get answers fast",c.append(h,f),d?t.append(c):t.append(w,c);let x=(Fe=o.clearChat)!=null?Fe:{},C=(Ae=x.enabled)!=null?Ae:!0,E=(ee=x.placement)!=null?ee:"inline",S=null,k=null;if(C){let Q=(ge=x.size)!=null?ge:"32px",Oe=($e=x.iconName)!=null?$e:"refresh-cw",bt=(Qe=x.iconColor)!=null?Qe:"",Wt=(At=x.backgroundColor)!=null?At:"",Mt=(me=x.borderWidth)!=null?me:"",j=(J=x.borderColor)!=null?J:"",Ze=(ct=x.borderRadius)!=null?ct:"",We=(ut=x.paddingX)!=null?ut:"",z=(ft=x.paddingY)!=null?ft:"",R=(Ot=x.tooltipText)!=null?Ot:"Clear chat",he=(wt=x.showTooltip)!=null?wt:!0;k=p("div",E==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),S=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),S.style.height=Q,S.style.width=Q,S.type="button",S.setAttribute("aria-label",R);let ue=ie(Oe,"20px",bt||"",1);if(ue&&S.appendChild(ue),bt&&(S.style.color=bt,S.classList.remove("tvw-text-cw-muted")),Wt&&(S.style.backgroundColor=Wt,S.classList.remove("hover:tvw-bg-gray-100")),Mt||j){let te=Mt||"0px",Le=j||"transparent";S.style.border=`${te} solid ${Le}`,S.classList.remove("tvw-border-none")}if(Ze&&(S.style.borderRadius=Ze,S.classList.remove("tvw-rounded-full")),We?(S.style.paddingLeft=We,S.style.paddingRight=We):(S.style.paddingLeft="",S.style.paddingRight=""),z?(S.style.paddingTop=z,S.style.paddingBottom=z):(S.style.paddingTop="",S.style.paddingBottom=""),k.appendChild(S),he&&R&&S&&k){let te=null,Le=()=>{if(te||!S)return;te=p("div","tvw-clear-chat-tooltip"),te.textContent=R;let q=p("div");q.className="tvw-clear-chat-tooltip-arrow",te.appendChild(q);let de=S.getBoundingClientRect();te.style.position="fixed",te.style.left=`${de.left+de.width/2}px`,te.style.top=`${de.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Ne=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};k.addEventListener("mouseenter",Le),k.addEventListener("mouseleave",Ne),S.addEventListener("focus",Le),S.addEventListener("blur",Ne),k._cleanupTooltip=()=>{Ne(),k&&(k.removeEventListener("mouseenter",Le),k.removeEventListener("mouseleave",Ne)),S&&(S.removeEventListener("focus",Le),S.removeEventListener("blur",Ne))}}E==="inline"&&t.appendChild(k)}let V=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":C&&E==="inline"?"":"tvw-ml-auto"),y=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");y.style.height=i,y.style.width=i,y.type="button";let O=(Y=o.closeButtonTooltipText)!=null?Y:"Close chat",W=(Ie=o.closeButtonShowTooltip)!=null?Ie:!0;y.setAttribute("aria-label",O),y.style.display=r?"":"none";let H=(vt=o.closeButtonIconName)!=null?vt:"x",oe=(yt=o.closeButtonIconText)!=null?yt:"\xD7",_=ie(H,"20px",o.closeButtonColor||"",1);if(_?y.appendChild(_):y.textContent=oe,o.closeButtonColor?(y.style.color=o.closeButtonColor,y.classList.remove("tvw-text-cw-muted")):(y.style.color="",y.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(y.style.backgroundColor=o.closeButtonBackgroundColor,y.classList.remove("hover:tvw-bg-gray-100")):(y.style.backgroundColor="",y.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Q=o.closeButtonBorderWidth||"0px",Oe=o.closeButtonBorderColor||"transparent";y.style.border=`${Q} solid ${Oe}`,y.classList.remove("tvw-border-none")}else y.style.border="",y.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(y.style.borderRadius=o.closeButtonBorderRadius,y.classList.remove("tvw-rounded-full")):(y.style.borderRadius="",y.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(y.style.paddingLeft=o.closeButtonPaddingX,y.style.paddingRight=o.closeButtonPaddingX):(y.style.paddingLeft="",y.style.paddingRight=""),o.closeButtonPaddingY?(y.style.paddingTop=o.closeButtonPaddingY,y.style.paddingBottom=o.closeButtonPaddingY):(y.style.paddingTop="",y.style.paddingBottom=""),V.appendChild(y),W&&O){let Q=null,Oe=()=>{if(Q)return;Q=p("div","tvw-clear-chat-tooltip"),Q.textContent=O;let Wt=p("div");Wt.className="tvw-clear-chat-tooltip-arrow",Q.appendChild(Wt);let Mt=y.getBoundingClientRect();Q.style.position="fixed",Q.style.left=`${Mt.left+Mt.width/2}px`,Q.style.top=`${Mt.top-8}px`,Q.style.transform="translate(-50%, -100%)",document.body.appendChild(Q)},bt=()=>{Q&&Q.parentNode&&(Q.parentNode.removeChild(Q),Q=null)};V.addEventListener("mouseenter",Oe),V.addEventListener("mouseleave",bt),y.addEventListener("focus",Oe),y.addEventListener("blur",bt),V._cleanupTooltip=()=>{bt(),V.removeEventListener("mouseenter",Oe),V.removeEventListener("mouseleave",bt),y.removeEventListener("focus",Oe),y.removeEventListener("blur",bt)}}return a!=="top-right"&&t.appendChild(V),{header:t,iconHolder:w,headerTitle:h,headerSubtitle:f,closeButton:y,closeButtonWrapper:V,clearChatButton:S,clearChatButtonWrapper:k}},Mn=(e,n,r)=>{var i,a,d,g;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=t.closeButtonPlacement)!=null?a:"inline",s=(g=(d=t.clearChat)==null?void 0:d.placement)!=null?g:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var xi=e=>dn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),Si=e=>{var x,C,E,S;let{config:n,showClose:r=!0,onClose:t}=e,o=(x=n==null?void 0:n.launcher)!=null?x:{},s=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(C=o.title)!=null?C:"Chat Assistant",s.appendChild(i);let a=(E=o.closeButtonSize)!=null?E:"32px",d=p("div",""),g=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");g.style.height=a,g.style.width=a,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=r?"":"none";let w=(S=o.closeButtonIconName)!=null?S:"x",c=ie(w,"20px",o.closeButtonColor||"",2);c?g.appendChild(c):g.textContent="\xD7",t&&g.addEventListener("click",t),d.appendChild(g),s.appendChild(d);let h=p("div");h.style.display="none";let f=p("span");return f.style.display="none",{header:s,iconHolder:h,headerTitle:i,headerSubtitle:f,closeButton:g,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Ai=e=>{var y,O,W,H,oe,_,le,X;let{config:n,showClose:r=!0,onClose:t,onClearChat:o}=e,s=(y=n==null?void 0:n.launcher)!=null?y:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=p("div","tvw-flex tvw-items-center tvw-gap-3"),d=(O=s.headerIconSize)!=null?O:"56px",g=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");g.style.height=d,g.style.width=d;let w=s.headerIconName;if(w){let U=parseFloat(d)||24,Se=ie(w,U*.5,"#ffffff",2);Se?g.replaceChildren(Se):g.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}"}else if(s.iconUrl){let U=p("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=d,U.style.width=d,g.replaceChildren(U)}else g.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}";let c=p("div","tvw-flex tvw-flex-col tvw-flex-1"),h=p("span","tvw-text-lg tvw-font-semibold");h.textContent=(oe=s.title)!=null?oe:"Chat Assistant";let f=p("span","tvw-text-sm tvw-text-cw-muted");f.textContent=(_=s.subtitle)!=null?_:"Here to help you get answers fast",c.append(h,f),a.append(g,c);let x=(le=s.closeButtonSize)!=null?le:"32px",C=p("div",""),E=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");E.style.height=x,E.style.width=x,E.type="button",E.setAttribute("aria-label","Close chat"),E.style.display=r?"":"none";let S=(X=s.closeButtonIconName)!=null?X:"x",k=ie(S,"20px",s.closeButtonColor||"",2);k?E.appendChild(k):E.textContent="\xD7",t&&E.addEventListener("click",t),C.appendChild(E),a.appendChild(C),i.appendChild(a);let V=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return V.textContent="Online and ready to help",i.appendChild(V),{header:i,iconHolder:g,headerTitle:h,headerSubtitle:f,closeButton:E,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}},Us={default:xi,minimal:Si,expanded:Ai},Ei=e=>{var n;return(n=Us[e])!=null?n:Us.default},Zn=(e,n,r)=>{var i,a,d;if(n!=null&&n.render){let g=n.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),w=p("div");w.style.display="none";let c=p("span"),h=p("span"),f=p("button");f.style.display="none";let x=p("div");return x.style.display="none",{header:g,iconHolder:w,headerTitle:c,headerSubtitle:h,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=Ei(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ta=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},es=e=>{var Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt,Q,Oe,bt,Wt,Mt,j,Ze,We,z,R,he,ue;let{config:n}=e,r=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=p("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=p("textarea");s.placeholder=(Ae=(Fe=n==null?void 0:n.copy)==null?void 0:Fe.inputPlaceholder)!=null?Ae:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none tvw-composer-textarea",s.rows=1;let i=(ge=(ee=n==null?void 0:n.theme)==null?void 0:ee.inputFontFamily)!=null?ge:"sans-serif",a=(Qe=($e=n==null?void 0:n.theme)==null?void 0:$e.inputFontWeight)!=null?Qe:"400";s.style.fontFamily=Ta(i),s.style.fontWeight=a;let w=3*20;s.style.maxHeight=`${w}px`,s.style.overflowY="auto";let c=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,w);s.style.height=`${te}px`};s.addEventListener("input",c),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let h=(At=n==null?void 0:n.sendButton)!=null?At:{},f=(me=h.useIcon)!=null?me:!1,x=(J=h.iconText)!=null?J:"\u2191",C=h.iconName,E=(ct=h.tooltipText)!=null?ct:"Send message",S=(ut=h.showTooltip)!=null?ut:!1,k=(ft=h.size)!=null?ft:"40px",V=h.backgroundColor,y=h.textColor,O=p("div","tvw-send-button-wrapper"),W=p("button",f?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(W.type="submit",f){if(W.style.width=k,W.style.height=k,W.style.minWidth=k,W.style.minHeight=k,W.style.fontSize="18px",W.style.lineHeight="1",W.innerHTML="",C){let te=parseFloat(k)||24,Le=y&&typeof y=="string"&&y.trim()?y.trim():"currentColor",Ne=ie(C,te,Le,2);Ne?(W.appendChild(Ne),W.style.color=Le):(W.textContent=x,y?W.style.color=y:W.classList.add("tvw-text-white"))}else W.textContent=x,y?W.style.color=y:W.classList.add("tvw-text-white");V?W.style.backgroundColor=V:W.classList.add("tvw-bg-cw-primary")}else W.textContent=(wt=(Ot=n==null?void 0:n.copy)==null?void 0:Ot.sendButtonLabel)!=null?wt:"Send",y?W.style.color=y:W.classList.add("tvw-text-white");if(h.borderWidth&&(W.style.borderWidth=h.borderWidth,W.style.borderStyle="solid"),h.borderColor&&(W.style.borderColor=h.borderColor),h.paddingX?(W.style.paddingLeft=h.paddingX,W.style.paddingRight=h.paddingX):(W.style.paddingLeft="",W.style.paddingRight=""),h.paddingY?(W.style.paddingTop=h.paddingY,W.style.paddingBottom=h.paddingY):(W.style.paddingTop="",W.style.paddingBottom=""),S&&E){let te=p("div","tvw-send-button-tooltip");te.textContent=E,O.appendChild(te)}O.appendChild(W);let H=(Y=n==null?void 0:n.voiceRecognition)!=null?Y:{},oe=H.enabled===!0,_=null,le=null,X=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(oe&&X){le=p("div","tvw-send-button-wrapper"),_=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),_.type="button",_.setAttribute("aria-label","Start voice recognition");let te=(Ie=H.iconName)!=null?Ie:"mic",Le=(vt=H.iconSize)!=null?vt:k,Ne=parseFloat(Le)||24,q=(yt=H.backgroundColor)!=null?yt:V,de=(Q=H.iconColor)!=null?Q:y;_.style.width=Le,_.style.height=Le,_.style.minWidth=Le,_.style.minHeight=Le,_.style.fontSize="18px",_.style.lineHeight="1";let Be=de||"currentColor",Je=ie(te,Ne,Be,1.5);Je?(_.appendChild(Je),_.style.color=Be):(_.textContent="\u{1F3A4}",_.style.color=Be),q?_.style.backgroundColor=q:_.classList.add("tvw-bg-cw-primary"),de?_.style.color=de:!de&&!y&&_.classList.add("tvw-text-white"),H.borderWidth&&(_.style.borderWidth=H.borderWidth,_.style.borderStyle="solid"),H.borderColor&&(_.style.borderColor=H.borderColor),H.paddingX&&(_.style.paddingLeft=H.paddingX,_.style.paddingRight=H.paddingX),H.paddingY&&(_.style.paddingTop=H.paddingY,_.style.paddingBottom=H.paddingY),le.appendChild(_);let st=(Oe=H.tooltipText)!=null?Oe:"Start voice recognition";if(((bt=H.showTooltip)!=null?bt:!1)&&st){let rt=p("div","tvw-send-button-tooltip");rt.textContent=st,le.appendChild(rt)}}let U=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},Se=U.enabled===!0,N=null,re=null,D=null,Z=null;if(Se){Z=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),Z.style.display="none",D=p("input"),D.type="file",D.accept=((Mt=U.allowedTypes)!=null?Mt:ln).join(","),D.multiple=((j=U.maxFiles)!=null?j:4)>1,D.style.display="none",D.setAttribute("aria-label","Attach files"),re=p("div","tvw-send-button-wrapper"),N=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),N.type="button",N.setAttribute("aria-label",(Ze=U.buttonTooltipText)!=null?Ze:"Attach file");let te=(We=U.buttonIconName)!=null?We:"paperclip",Le=k,Ne=parseFloat(Le)||40,q=Math.round(Ne*.6);N.style.width=Le,N.style.height=Le,N.style.minWidth=Le,N.style.minHeight=Le,N.style.fontSize="18px",N.style.lineHeight="1",N.style.backgroundColor="transparent",N.style.color="var(--cw-primary, #111827)",N.style.border="none",N.style.borderRadius="6px",N.style.transition="background-color 0.15s ease",N.addEventListener("mouseenter",()=>{N.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),N.addEventListener("mouseleave",()=>{N.style.backgroundColor="transparent"});let de=ie(te,q,"currentColor",1.5);de?N.appendChild(de):N.textContent="\u{1F4CE}",N.addEventListener("click",st=>{st.preventDefault(),D==null||D.click()}),re.appendChild(N);let Be=(z=U.buttonTooltipText)!=null?z:"Attach file",Je=p("div","tvw-send-button-tooltip");Je.textContent=Be,re.appendChild(Je)}o.addEventListener("click",te=>{te.target!==W&&te.target!==O&&te.target!==_&&te.target!==le&&te.target!==N&&te.target!==re&&s.focus()}),Z&&(Z.style.gap="8px",o.append(Z)),D&&o.append(D),o.append(s);let ve=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),pe=p("div","tvw-flex tvw-items-center tvw-gap-2");re&&pe.append(re);let Ue=p("div","tvw-flex tvw-items-center tvw-gap-1");le&&Ue.append(le),Ue.append(O),ve.append(pe,Ue),o.append(ve);let it=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Tt=(R=n==null?void 0:n.statusIndicator)!=null?R:{},$t=(he=Tt.visible)!=null?he:!0;return it.style.display=$t?"":"none",it.textContent=(ue=Tt.idleText)!=null?ue:"Online",r.append(t,o,it),{footer:r,suggestions:t,composerForm:o,textarea:s,sendButton:W,sendButtonWrapper:O,micButton:_,micButtonWrapper:le,statusText:it,attachmentButton:N,attachmentButtonWrapper:re,attachmentInput:D,attachmentPreviewsContainer:Z,actionsRow:ve,leftActions:pe,rightActions:Ue}};var Ti=e=>{var d,g,w,c,h,f,x;if(!((g=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?g:!0)){let C=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),E=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),S=(c=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?c:"100%";return C.style.width=S,E.style.width="100%",C.appendChild(E),{wrapper:C,panel:E}}let r=(h=e==null?void 0:e.launcher)!=null?h:{},t=r.position&&Ut[r.position]?Ut[r.position]:Ut["bottom-right"],o=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(x=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?x:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},Mi=(e,n=!0)=>{var f,x,C,E,S,k,V;let r=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(f=e==null?void 0:e.layout)==null?void 0:f.header,o=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,s=t?Zn(e,t,{showClose:n}):dn({config:e,showClose:n}),i=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(E=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?E:"Hello \u{1F44B}";let g=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");g.textContent=(k=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",a.append(d,g);let w=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,w);let c=es({config:e}),h=((V=e==null?void 0:e.layout)==null?void 0:V.showFooter)!==!1;return o?Mn(r,s,e):(s.header.style.display="none",Mn(r,s,e)),r.append(i),h||(c.footer.style.display="none"),r.append(c.footer),{container:r,body:i,messagesWrapper:w,suggestions:c.suggestions,textarea:c.textarea,sendButton:c.sendButton,sendButtonWrapper:c.sendButtonWrapper,micButton:c.micButton,micButtonWrapper:c.micButtonWrapper,composerForm:c.composerForm,statusText:c.statusText,introTitle:d,introSubtitle:g,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:c.footer,attachmentButton:c.attachmentButton,attachmentButtonWrapper:c.attachmentButtonWrapper,attachmentInput:c.attachmentInput,attachmentPreviewsContainer:c.attachmentPreviewsContainer,actionsRow:c.actionsRow,leftActions:c.leftActions,rightActions:c.rightActions}};var Ln=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(r),e.appendChild(t),e.appendChild(o),e},ki=(e,n,r)=>{let t={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:Ln};if(n){let o=n(t);if(o!==null)return o}return Ln()},Ma=(e,n)=>{let r=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=p("img");o.src=t,o.alt=n==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=n==="user"?"U":"A",r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Li=(e,n)=>{let r=p("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?r.textContent=n.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},La=(e,n="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},Wi=(e,n,r)=>{var f,x,C,E,S,k;let t=(f=n.showCopy)!=null?f:!0,o=(x=n.showUpvote)!=null?x:!0,s=(C=n.showDownvote)!=null?C:!0,i=(E=n.visibility)!=null?E:"hover",a=(S=n.align)!=null?S:"right",d=(k=n.layout)!=null?k:"pill-inside",g={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],c=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${g} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`);c.id=`actions-${e.id}`,c.setAttribute("data-actions-for",e.id);let h=(V,y,O)=>{let W=document.createElement("button");W.className="tvw-message-action-btn",W.setAttribute("aria-label",y),W.setAttribute("title",y),W.setAttribute("data-action",O);let H=ie(V,14,"currentColor",2);return H&&W.appendChild(H),W};return t&&c.appendChild(h("copy","Copy message","copy")),o&&c.appendChild(h("thumbs-up","Upvote","upvote")),s&&c.appendChild(h("thumbs-down","Downvote","downvote")),c},ts=(e,n,r,t,o,s)=>{var y,O,W,H,oe;let i=r!=null?r:{},a=(y=i.layout)!=null?y:"bubble",d=i.avatar,g=i.timestamp,w=(O=d==null?void 0:d.show)!=null?O:!1,c=(W=g==null?void 0:g.show)!=null?W:!1,h=(H=d==null?void 0:d.position)!=null?H:"left",f=(oe=g==null?void 0:g.position)!=null?oe:"below",x=La(e.role,a),C=p("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id);let E=document.createElement("div");if(E.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),c&&f==="inline"&&e.createdAt){let _=Li(e,g);_.classList.add("tvw-ml-2","tvw-inline"),E.appendChild(_)}if(C.appendChild(E),c&&f==="below"&&e.createdAt){let _=Li(e,g);_.classList.add("tvw-mt-1"),C.appendChild(_)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let _=ki("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);_&&C.appendChild(_)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let _=Wi(e,t,o);C.appendChild(_)}if(!w||e.role==="system")return C;let k=p("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),V=Ma(d,e.role);return h==="right"||h==="left"&&e.role==="user"?k.append(C,V):k.append(V,C),C.classList.remove("tvw-max-w-[85%]"),C.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),k},ka=(e,n,r,t,o,s)=>{let i=r!=null?r:{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ts(e,n,r,t,o,s)};var kn=new Set,Ii=(e,n)=>{let r=kn.has(e),t=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".tvw-border-t");if(!t||!o)return;t.setAttribute("aria-expanded",r?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},Js=e=>{let n=e.reasoning,r=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let t=kn.has(e.id),o=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=p("span","tvw-text-xs tvw-text-cw-primary");a.textContent=gi(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),w=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=t?"Hide":"Show";let c=p("div","tvw-flex tvw-items-center tvw-ml-auto");c.append(d),o.append(s,c);let h=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");h.style.display=t?"":"none";let f=n.chunks.join(""),x=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return x.textContent=f||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),h.appendChild(x),(()=>{o.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let S=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);S?d.appendChild(S):d.textContent=t?"Hide":"Show",h.style.display=t?"":"none"})(),r.append(o,h),r};var Wn=new Set,Pi=(e,n,r)=>{var g;let t=Wn.has(e),o=(g=r==null?void 0:r.toolCall)!=null?g:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",t?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let w=o.toggleTextColor||o.headerTextColor||"currentColor",c=ie(t?"chevron-up":"chevron-down",16,w,2);c?d.appendChild(c):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Ks=(e,n)=>{var C;let r=e.toolCall,t=(C=n==null?void 0:n.toolCall)!=null?C:{},o=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=Wn.has(e.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=p("div","tvw-flex tvw-flex-col tvw-text-left"),d=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=mi(r),a.appendChild(d);let g=p("div","tvw-flex tvw-items-center"),w=t.toggleTextColor||t.headerTextColor||"currentColor",c=ie(s?"chevron-up":"chevron-down",16,w,2);c?g.appendChild(c):g.textContent=s?"Hide":"Show";let h=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");h.append(g),i.append(a,h);let f=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(f.style.display=s?"":"none",t.contentBackgroundColor&&(f.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(f.style.color=t.contentTextColor),t.contentPaddingX&&(f.style.paddingLeft=t.contentPaddingX,f.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(f.style.paddingTop=t.contentPaddingY,f.style.paddingBottom=t.contentPaddingY),r.name){let E=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?E.style.color=t.contentTextColor:t.headerTextColor&&(E.style.color=t.headerTextColor),E.textContent=r.name,f.appendChild(E)}if(r.args!==void 0){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Arguments";let k=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=$s(r.args),E.append(S,k),f.appendChild(E)}if(r.chunks&&r.chunks.length){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Activity";let k=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=r.chunks.join(`
|
|
16
|
-
`),E.append(S,k),f.appendChild(E)}if(r.status==="complete"&&r.result!==void 0){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Result";let k=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=$s(r.result),E.append(S,k),f.appendChild(E)}if(r.status==="complete"&&typeof r.duration=="number"){let E=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(E.style.color=t.contentTextColor),E.textContent=`Duration: ${r.duration}ms`,f.appendChild(E)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),g.innerHTML="";let E=t.toggleTextColor||t.headerTextColor||"currentColor",S=ie(s?"chevron-up":"chevron-down",16,E,2);S?g.appendChild(S):g.textContent=s?"Hide":"Show",f.style.display=s?"":"none"})(),o.append(i,f),o};var Hi=e=>{let n=[];return{buttons:n,render:(t,o,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(f=>f.role==="user"))return;let w=document.createDocumentFragment(),c=o?o.isStreaming():!1,h=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(f=>{let x=p("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");x.type="button",x.textContent=f,x.disabled=c,a!=null&&a.fontFamily&&(x.style.fontFamily=h(a.fontFamily)),a!=null&&a.fontWeight&&(x.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(x.style.paddingLeft=a.paddingX,x.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(x.style.paddingTop=a.paddingY,x.style.paddingBottom=a.paddingY),x.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(f))}),w.appendChild(x),n.push(x)}),e.appendChild(w)}}};var ns=class{constructor(n=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=r}push(n){var r;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(r=this.store)==null||r.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let r=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let t of r)this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(t.type);return this.totalCaptured=n.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let r=this.getAll();return n>=r.length?r:r.slice(r.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ss=class{constructor(n="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=r}open(){return new Promise((n,r)=>{try{let t=indexedDB.open(this.dbName,1);t.onupgradeneeded=()=>{let o=t.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},t.onsuccess=()=>{this.db=t.result,n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}getAll(){return new Promise((n,r)=>{if(!this.db){n([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{n(i.result)},i.onerror=()=>{r(i.error)}}catch(t){r(t)}})}getCount(){return new Promise((n,r)=>{if(!this.db){n(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}clear(){return new Promise((n,r)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,r)=>{try{let t=indexedDB.deleteDatabase(this.dbName);t.onsuccess=()=>{n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}};function In(e,n){n&&n.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var Wa={flow_:{bg:"#dcfce7",text:"#166534"},step_:{bg:"#dbeafe",text:"#1e40af"},reason_:{bg:"#ffedd5",text:"#9a3412"},tool_:{bg:"#f3e8ff",text:"#6b21a8"},agent_:{bg:"#ccfbf1",text:"#115e59"},error:{bg:"#fecaca",text:"#991b1b"}},Ia={bg:"#f3f4f6",text:"#4b5563"},Pa=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ha=100;function Ba(e,n){let r={...Wa,...n};if(r[e])return r[e];for(let t of Object.keys(r))if(t.endsWith("_")&&e.startsWith(t))return r[t];return Ia}function Ra(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Fa(e){let n=new Date(e),r=String(n.getHours()).padStart(2,"0"),t=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${r}:${t}:${o}.${s}`}function $a(e,n){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let t of n){let o=t.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Oa(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),r()})}function Na(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Da(e,n,r){let t,o;try{o=JSON.parse(e.payload),t=JSON.stringify(o,null,2)}catch{o=e.payload,t=e.payload}let s=n.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=p("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),d=p("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return d.textContent=t,a.appendChild(d),a}}function Ys(e,n,r,t,o,s,i,a){var h;let d=o.has(e.id),g=p("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");In(g,(h=t.classNames)==null?void 0:h.eventRow);let w=i.find(f=>f.renderEventStreamRow);if(w!=null&&w.renderEventStreamRow&&a){let f=w.renderEventStreamRow({event:e,index:n,config:a,defaultRenderer:()=>c(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return g.appendChild(f),g}return g.appendChild(c()),g;function c(){var U,Se;let f=p("div",""),x=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-3 tvw-py-3 hover:tvw-bg-cw-container tvw-cursor-pointer tvw-group");x.setAttribute("data-event-id",e.id);let C=p("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),E=ie(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&C.appendChild(E);let S=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),k=(U=t.timestampFormat)!=null?U:"relative";S.textContent=k==="relative"?Ra(e.timestamp,r):Fa(e.timestamp);let V=null;t.showSequenceNumbers!==!1&&(V=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),V.textContent=String(n+1));let y=Ba(e.type,t.badgeColors),O=p("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded tvw-text-[11px] tvw-font-mono tvw-font-medium tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-border");O.style.backgroundColor=y.bg,O.style.color=y.text,O.style.borderColor=y.text+"50",O.textContent=e.type;let W=(Se=t.descriptionFields)!=null?Se:Pa,H=$a(e.payload,W),oe=null;H&&(oe=p("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),oe.textContent=H);let _=p("div","tvw-flex-1 tvw-min-w-0"),le=p("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),X=ie("clipboard","12px","currentColor",1.5);return X&&le.appendChild(X),le.addEventListener("click",async N=>{N.stopPropagation(),await Oa(Na(e)),le.innerHTML="";let re=ie("check","12px","currentColor",1.5);re&&le.appendChild(re),setTimeout(()=>{le.innerHTML="";let D=ie("clipboard","12px","currentColor",1.5);D&&le.appendChild(D)},1500)}),x.appendChild(C),x.appendChild(S),V&&x.appendChild(V),x.appendChild(O),oe&&x.appendChild(oe),x.appendChild(_),x.appendChild(le),f.appendChild(x),d&&f.appendChild(Da(e,i,a)),f}}function Bi(e){var g,w;let{buffer:n,getFullHistory:r,onClose:t,config:o,plugins:s=[]}=e,i=(w=(g=o==null?void 0:o.features)==null?void 0:g.eventStream)!=null?w:{},a=s.find(c=>c.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let c=a.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>d().element,onClose:t});if(c)return{element:c,update:()=>{},destroy:()=>{}}}return d();function d(){let c=i.classNames,h=p("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");In(h,c==null?void 0:c.panel);let f=[],x="",C="",E=null,S=[],k={},V=0,y=!1,O=0,W=0,H=!1,oe=null,_=!1,le=0,X=new Set,U=new Map,Se="",N="",re=null,D,Z,ve,pe,Ue;function it(){let z=p("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),R=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-4 tvw-py-3 tvw-pb-0 tvw-border-cw-divider tvw-bg-cw-surface tvw-overflow-hidden");In(R,c==null?void 0:c.headerBar);let he=p("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");he.textContent="Events",D=p("span","tvw-text-[11px] tvw-font-mono tvw-bg-cw-container tvw-text-cw-muted tvw-px-2 tvw-py-0.5 tvw-rounded tvw-border tvw-border-cw-border"),D.textContent="0";let ue=p("div","tvw-flex-1");Z=p("select","tvw-text-xs tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded tvw-px-2.5 tvw-py-1 tvw-text-cw-primary tvw-cursor-pointer");let te=p("option","");te.value="",te.textContent="All events",Z.appendChild(te),ve=p("button","tvw-inline-flex tvw-items-center tvw-gap-1.5 tvw-rounded tvw-text-xs tvw-text-cw-muted hover:tvw-bg-cw-container hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border tvw-border-cw-border tvw-bg-cw-surface tvw-flex-shrink-0 tvw-px-2.5 tvw-py-1"),ve.type="button",ve.title="Copy All";let Ne=ie("clipboard-copy","12px","currentColor",1.5);Ne&&ve.appendChild(Ne);let q=p("span","tvw-text-xs");q.textContent="Copy All",ve.appendChild(q),R.appendChild(he),R.appendChild(D),R.appendChild(ue),R.appendChild(Z),R.appendChild(ve);let de=p("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");In(de,c==null?void 0:c.searchBar);let Be=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),Je=p("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Be&&Je.appendChild(Be),pe=p("input","tvw-text-sm tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded-md tvw-pl-8 tvw-pr-3 tvw-py-1 tvw-w-full tvw-text-cw-primary"),In(pe,c==null?void 0:c.searchInput),pe.type="text",pe.placeholder="Search event payloads...",Ue=p("button","tvw-absolute tvw-right-5 tvw-top-1/2 tvw--translate-y-1/2 tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-0 tvw-leading-none"),Ue.type="button",Ue.style.display="none";let st=ie("x","12px","currentColor",2);return st&&Ue.appendChild(st),de.appendChild(Je),de.appendChild(pe),de.appendChild(Ue),z.appendChild(R),z.appendChild(de),z}let Tt,$t=s.find(z=>z.renderEventStreamToolbar);if($t!=null&&$t.renderEventStreamToolbar&&o){let z=$t.renderEventStreamToolbar({config:o,defaultRenderer:()=>it(),eventCount:n.getSize(),filteredCount:0,onFilterChange:R=>{x=R,ut(),wt()},onSearchChange:R=>{C=R,ut(),wt()}});Tt=z!=null?z:it()}else Tt=it();let Fe=p("div","tvw-text-xs tvw-text-cw-muted tvw-text-center tvw-py-0.5 tvw-px-4 tvw-bg-cw-container tvw-border-b tvw-border-cw-divider tvw-italic tvw-flex-shrink-0");Fe.style.display="none";let Ae=p("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ee=p("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ee.style.height="100%";let ge=p("div","tvw-absolute tvw-bottom-3 tvw-left-1/2 tvw-transform tvw--translate-x-1/2 tvw-bg-cw-accent tvw-text-white tvw-text-xs tvw-px-3 tvw-py-1.5 tvw-rounded-full tvw-cursor-pointer tvw-shadow-md tvw-z-10 tvw-flex tvw-items-center tvw-gap-1");In(ge,c==null?void 0:c.scrollIndicator),ge.style.display="none";let $e=ie("arrow-down","12px","currentColor",2);$e&&ge.appendChild($e);let Qe=p("span","");ge.appendChild(Qe);let At=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");At.style.display="none",Ae.appendChild(ee),Ae.appendChild(At),Ae.appendChild(ge),h.setAttribute("tabindex","0"),h.appendChild(Tt),h.appendChild(Fe),h.appendChild(Ae);function me(){let z=n.getAll(),R={};for(let q of z)R[q.type]=(R[q.type]||0)+1;let he=Object.keys(R).sort(),ue=he.length!==S.length||!he.every((q,de)=>q===S[de]),te=!ue&&he.some(q=>R[q]!==k[q]),Le=z.length!==Object.values(k).reduce((q,de)=>q+de,0);if(!ue&&!te&&!Le||(S=he,k=R,!Z))return;let Ne=Z.value;if(Z.options[0].textContent="All events",ue){for(;Z.options.length>1;)Z.remove(1);for(let q of he){let de=p("option","");de.value=q,de.textContent=`${q} (${R[q]||0})`,Z.appendChild(de)}Ne&&he.includes(Ne)?Z.value=Ne:Ne&&(Z.value="",x="")}else for(let q=1;q<Z.options.length;q++){let de=Z.options[q];de.textContent=`${de.value} (${R[de.value]||0})`}}function J(){let z=n.getAll();if(x&&(z=z.filter(R=>R.type===x)),C){let R=C.toLowerCase();z=z.filter(he=>he.type.toLowerCase().includes(R)||he.payload.toLowerCase().includes(R))}return z}function ct(){return x!==""||C!==""}function ut(){V=0,O=0,y=!1,ge.style.display="none"}function ft(z){X.has(z)?X.delete(z):X.add(z),re=z;let R=ee.scrollTop,he=y;_=!0,y=!0,wt(),ee.scrollTop=R,y=he,_=!1}function Ot(){return ee.scrollHeight-ee.scrollTop-ee.clientHeight<=50}function wt(){W=Date.now(),H=!1,me();let z=n.getEvictedCount();z>0?(Fe.textContent=`${z.toLocaleString()} older events truncated`,Fe.style.display=""):Fe.style.display="none",f=J();let R=f.length,he=n.getSize()>0;D&&(D.textContent=String(n.getSize())),R===0&&he&&ct()?(At.textContent=C?`No events matching '${C}'`:"No events matching filter",At.style.display="",ee.style.display="none"):(At.style.display="none",ee.style.display=""),ve&&(ve.title=ct()?`Copy Filtered (${R})`:"Copy All"),y&&R>V&&(O+=R-V,Qe.textContent=`${O} new event${O===1?"":"s"}`,ge.style.display=""),V=R;let ue=n.getAll(),te=ue.length>0?ue[0].timestamp:0,Le=new Set(f.map(de=>de.id));for(let de of X)Le.has(de)||X.delete(de);let Ne=x!==Se||C!==N,q=U.size===0&&f.length>0;if(Ne||q||f.length===0){ee.innerHTML="",U.clear();let de=document.createDocumentFragment();for(let Be=0;Be<f.length;Be++){let Je=Ys(f[Be],Be,te,i,X,ft,s,o);U.set(f[Be].id,Je),de.appendChild(Je)}ee.appendChild(de),Se=x,N=C,re=null}else{if(re!==null){let Be=U.get(re);if(Be&&Be.parentNode===ee){let Je=f.findIndex(st=>st.id===re);if(Je>=0){let st=Ys(f[Je],Je,te,i,X,ft,s,o);ee.insertBefore(st,Be),Be.remove(),U.set(re,st)}}re=null}let de=new Set(f.map(Be=>Be.id));for(let[Be,Je]of U)de.has(Be)||(Je.remove(),U.delete(Be));for(let Be=0;Be<f.length;Be++){let Je=f[Be];if(!U.has(Je.id)){let st=Ys(Je,Be,te,i,X,ft,s,o);U.set(Je.id,st),ee.appendChild(st)}}}y||(ee.scrollTop=ee.scrollHeight)}function Y(){if(Date.now()-W>=Ha){oe!==null&&(cancelAnimationFrame(oe),oe=null),wt();return}H||(H=!0,oe=requestAnimationFrame(()=>{oe=null,wt()}))}let Ie=(z,R)=>{if(!ve)return;ve.innerHTML="";let he=ie(z,"12px","currentColor",1.5);he&&ve.appendChild(he);let ue=p("span","tvw-text-xs");ue.textContent="Copy All",ve.appendChild(ue),setTimeout(()=>{ve.innerHTML="";let te=ie("clipboard-copy","12px","currentColor",1.5);te&&ve.appendChild(te);let Le=p("span","tvw-text-xs");Le.textContent="Copy All",ve.appendChild(Le),ve.disabled=!1},R)},vt=async()=>{if(ve){ve.disabled=!0;try{let z;ct()?z=f:z=r?await r():n.getAll();let R=z.map(he=>{try{return JSON.parse(he.payload)}catch{return he.payload}});await navigator.clipboard.writeText(JSON.stringify(R,null,2)),Ie("check",1500)}catch{Ie("x",1500)}}},yt=()=>{Z&&(x=Z.value,ut(),wt())},Q=()=>{!pe||!Ue||(Ue.style.display=pe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{C=pe.value,ut(),wt()},150))},Oe=()=>{!pe||!Ue||(pe.value="",C="",Ue.style.display="none",E&&clearTimeout(E),ut(),wt())},bt=()=>{if(_)return;let z=ee.scrollTop,R=z>le;le=z,Ot()&&R?(y=!1,O=0,ge.style.display="none"):Ot()||(y=!0)},Wt=z=>{z.deltaY<0&&(y=!0)},Mt=()=>{ee.scrollTop=ee.scrollHeight,y=!1,O=0,ge.style.display="none"},j=z=>{let R=z.target;if(!R||R.closest("button"))return;let he=R.closest("[data-event-id]");if(!he)return;let ue=he.getAttribute("data-event-id");ue&&ft(ue)},Ze=z=>{if((z.metaKey||z.ctrlKey)&&z.key==="f"){z.preventDefault(),pe==null||pe.focus(),pe==null||pe.select();return}z.key==="Escape"&&(pe&&document.activeElement===pe?(Oe(),pe.blur(),h.focus()):t&&t())};ve&&ve.addEventListener("click",vt),Z&&Z.addEventListener("change",yt),pe&&pe.addEventListener("input",Q),Ue&&Ue.addEventListener("click",Oe),ee.addEventListener("scroll",bt),ee.addEventListener("wheel",Wt,{passive:!0}),ee.addEventListener("click",j),ge.addEventListener("click",Mt),h.addEventListener("keydown",Ze);function We(){E&&clearTimeout(E),oe!==null&&(cancelAnimationFrame(oe),oe=null),H=!1,U.clear(),ve&&ve.removeEventListener("click",vt),Z&&Z.removeEventListener("change",yt),pe&&pe.removeEventListener("input",Q),Ue&&Ue.removeEventListener("click",Oe),ee.removeEventListener("scroll",bt),ee.removeEventListener("wheel",Wt),ee.removeEventListener("click",j),ge.removeEventListener("click",Mt),h.removeEventListener("keydown",Ze)}return{element:h,update:Y,destroy:We}}}var Ri={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Vs=(e,n,r,t)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,C,E;if(s.dataset.enhanced==="true")return;let i=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let a=(C=Ri[i])!=null?C:Ri.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),g=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(g.textContent=a.title,d.appendChild(g),a.description){let S=p("p","tvw-text-sm tvw-text-cw-muted");S.textContent=a.description,d.appendChild(S)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(S=>{var W,H;let k=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");k.htmlFor=`${n.id}-${i}-${S.name}`;let V=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");V.textContent=S.label,k.appendChild(V);let y=(W=S.type)!=null?W:"text",O;y==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=y),O.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",O.id=`${n.id}-${i}-${S.name}`,O.name=S.name,O.placeholder=(H=S.placeholder)!=null?H:"",S.required&&(O.required=!0),k.appendChild(O),w.appendChild(k)});let c=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),h=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),f=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");f.type="submit",f.textContent=(E=a.submitLabel)!=null?E:"Submit",c.appendChild(h),c.appendChild(f),w.appendChild(c),s.replaceChildren(d,w),w.addEventListener("submit",async S=>{var O,W;S.preventDefault();let k=(O=r.formEndpoint)!=null?O:"/form",V=new FormData(w),y={};V.forEach((H,oe)=>{y[oe]=H}),y.type=i,f.disabled=!0,h.textContent="Submitting\u2026";try{let H=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let oe=await H.json();h.textContent=(W=oe.message)!=null?W:"Thanks! We'll be in touch soon.",oe.success&&oe.nextPrompt&&await t.sendMessage(String(oe.nextPrompt))}catch(H){h.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Xs=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var t;let r=this.plugins.get(n);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let t=new Set(n.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},Ts=new Xs;var Fi={primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},$i={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},nt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Fi,darkTheme:$i,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Gs(e){var n,r,t,o,s,i,a,d,g,w,c,h,f,x,C,E,S,k,V;return e?{...nt,...e,theme:{...nt.theme,...e.theme},darkTheme:{...nt.darkTheme,...e.darkTheme},launcher:{...nt.launcher,...e.launcher,clearChat:{...(n=nt.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...nt.copy,...e.copy},sendButton:{...nt.sendButton,...e.sendButton},statusIndicator:{...nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...nt.voiceRecognition,...e.voiceRecognition},features:{...nt.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:nt.suggestionChips,suggestionChipsConfig:{...nt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...nt.layout,...e.layout,header:{...(o=nt.layout)==null?void 0:o.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=nt.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(g=(d=nt.layout)==null?void 0:d.messages)==null?void 0:g.avatar,...(c=(w=e.layout)==null?void 0:w.messages)==null?void 0:c.avatar},timestamp:{...(f=(h=nt.layout)==null?void 0:h.messages)==null?void 0:f.timestamp,...(C=(x=e.layout)==null?void 0:x.messages)==null?void 0:C.timestamp}},slots:{...(E=nt.layout)==null?void 0:E.slots,...(S=e.layout)==null?void 0:S.slots}},markdown:{...nt.markdown,...e.markdown,options:{...(k=nt.markdown)==null?void 0:k.options,...(V=e.markdown)==null?void 0:V.options}},messageActions:{...nt.messageActions,...e.messageActions}}:nt}var Oi=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=e.get(o))==null||i.delete(s)};return{on:n,off:r,emit:(o,s)=>{var i;(i=e.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var ja=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},_a=e=>{let n=e.trim(),r=n.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(r,o+1)}return null},Ms=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=ja(e),r=_a(n);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},Qs=e=>typeof e=="string"?e:e==null?"":String(e),Pn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Qs(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=Qs(r.element);if(t&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Qs(r.text)}}},Ni=e=>Array.isArray(e)?e.map(n=>String(n)):[],Ls=e=>{let n=new Set(Ni(e.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(Ni(e.getSessionMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(n);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?e.parsers.reduce((g,w)=>g||(w==null?void 0:w({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),t();let d={action:a,message:s.message};e.emit("action:detected",d);for(let g of e.handlers)if(g)try{let w=()=>{e.emit("action:resubmit",d)},c=g(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:w});if(!c)continue;if(c.handled){let h=c.persistMessage!==!1;return{text:c.displayText!==void 0?c.displayText:"",persist:h,resubmit:c.resubmit}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:r}};var qa=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},za=e=>e.map(n=>({...n,streaming:!1})),Zs=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?qa(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?za(r.messages):void 0};t.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var er=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([r,t])=>{this.register(r,t)})}},rs=new er;import{parse as Ua,STR as Ja,OBJ as Ka}from"partial-json";function Ya(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Va(e,n){if(!Ya(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:n}}function tr(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e;try{let o=Ua(r,Ja|Ka),s=Va(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function Xa(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function nr(e,n){let{config:r,message:t,onPropsUpdate:o}=n,s=rs.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:a=>{o&&o(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function Ga(){let e=tr();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function sr(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function rr(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var Qa=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function or(e){let{onSubmit:n,onDismiss:r,title:t="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:g=Qa}=e,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-csat",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Customer satisfaction feedback");let c=null,h=document.createElement("div");h.className="tvw-feedback-content";let f=document.createElement("div");f.className="tvw-feedback-header";let x=document.createElement("h3");x.className="tvw-feedback-title",x.textContent=t,f.appendChild(x);let C=document.createElement("p");C.className="tvw-feedback-subtitle",C.textContent=o,f.appendChild(C),h.appendChild(f);let E=document.createElement("div");E.className="tvw-feedback-rating tvw-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let W=1;W<=5;W++){let H=document.createElement("button");H.type="button",H.className="tvw-feedback-rating-btn tvw-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${g[W-1]}`),H.title=g[W-1],H.dataset.rating=String(W),H.innerHTML=`
|
|
15
|
+
`,r.addEventListener("click",n);let t=s=>{var x,k,K,y,R,W,H,oe,U,re,J,q;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 d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(K=i.subtitle)!=null?K:"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 pe=(y=i.agentIconSize)!=null?y:"40px";if(v.style.height=pe,v.style.width=pe,v.innerHTML="",i.agentIconName){let $=parseFloat(pe)||24,Z=ie(i.agentIconName,$*.6,"#ffffff",2);Z?(v.appendChild(Z),v.style.display=""):(v.textContent=(R=i.agentIconText)!=null?R:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(W=i.agentIconText)!=null?W:"\u{1F4AC}",v.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let pe=(H=i.agentIconSize)!=null?H:"40px";u.style.height=pe,u.style.width=pe,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(u.src=i.iconUrl,u.style.display="block"):u.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let pe=(oe=i.callToActionIconSize)!=null?oe:"32px";m.style.height=pe,m.style.width=pe,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 $=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,$=(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 Z=parseFloat(pe)||24,P=Math.max(Z-$,8),ee=ie(i.callToActionIconName,P,"currentColor",2);ee?m.appendChild(ee):m.textContent=(U=i.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(re=i.callToActionIconText)!=null?re:"\u2197"}let h=i.position&&Ut[i.position]?Ut[i.position]:Ut["bottom-right"],S="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=`${S} ${h}`;let C="1px solid #e5e7eb",E="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(J=i.border)!=null?J:C,r.style.boxShadow=(q=i.shadow)!=null?q:E},o=()=>{r.removeEventListener("click",n),r.remove()};return e&&t(e),{element:r,update:t,destroy:o}};var dn=e=>{var re,J,q,pe,$,Z,P,ee,be,ge,Je,lt,Tt,$t,Oe,Ee,te,me,Ne,Qe,At,ue,Y,ut,pt,ht,Ot,wt,X,He,vt,yt;let{config:n,showClose:r=!0}=e,t=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(re=n==null?void 0:n.launcher)!=null?re:{},s=(J=o.headerIconSize)!=null?J:"48px",i=(q=o.closeButtonSize)!=null?q:"32px",a=(pe=o.closeButtonPlacement)!=null?pe:"inline",d=($=o.headerIconHidden)!=null?$:!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 Q=parseFloat(s)||24,De=ie(c,Q*.6,"#ffffff",1);De?v.replaceChildren(De):v.textContent=(P=(Z=n==null?void 0:n.launcher)==null?void 0:Z.agentIconText)!=null?P:"\u{1F4AC}"}else if((ee=n==null?void 0:n.launcher)!=null&&ee.iconUrl){let Q=g("img");Q.src=n.launcher.iconUrl,Q.alt="",Q.className="tvw-rounded-xl tvw-object-cover",Q.style.height=s,Q.style.width=s,v.replaceChildren(Q)}else v.textContent=(ge=(be=n==null?void 0:n.launcher)==null?void 0:be.agentIconText)!=null?ge:"\u{1F4AC}";let u=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(lt=(Je=n==null?void 0:n.launcher)==null?void 0:Je.title)!=null?lt:"Chat Assistant";let h=g("span","tvw-text-xs tvw-text-cw-muted");h.textContent=($t=(Tt=n==null?void 0:n.launcher)==null?void 0:Tt.subtitle)!=null?$t:"Here to help you get answers fast",u.append(m,h),d?t.append(u):t.append(v,u);let S=(Oe=o.clearChat)!=null?Oe:{},C=(Ee=S.enabled)!=null?Ee:!0,E=(te=S.placement)!=null?te:"inline",x=null,k=null;if(C){let Q=(me=S.size)!=null?me:"32px",De=(Ne=S.iconName)!=null?Ne:"refresh-cw",bt=(Qe=S.iconColor)!=null?Qe:"",Wt=(At=S.backgroundColor)!=null?At:"",Mt=(ue=S.borderWidth)!=null?ue:"",_=(Y=S.borderColor)!=null?Y:"",Ze=(ut=S.borderRadius)!=null?ut:"",Pe=(pt=S.paddingX)!=null?pt:"",z=(ht=S.paddingY)!=null?ht:"",B=(Ot=S.tooltipText)!=null?Ot:"Clear chat",fe=(wt=S.showTooltip)!=null?wt:!0;k=g("div",E==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),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=Q,x.style.width=Q,x.type="button",x.setAttribute("aria-label",B);let ce=ie(De,"20px",bt||"",1);if(ce&&x.appendChild(ce),bt&&(x.style.color=bt,x.classList.remove("tvw-text-cw-muted")),Wt&&(x.style.backgroundColor=Wt,x.classList.remove("hover:tvw-bg-gray-100")),Mt||_){let ne=Mt||"0px",We=_||"transparent";x.style.border=`${ne} solid ${We}`,x.classList.remove("tvw-border-none")}if(Ze&&(x.style.borderRadius=Ze,x.classList.remove("tvw-rounded-full")),Pe?(x.style.paddingLeft=Pe,x.style.paddingRight=Pe):(x.style.paddingLeft="",x.style.paddingRight=""),z?(x.style.paddingTop=z,x.style.paddingBottom=z):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),fe&&B&&x&&k){let ne=null,We=()=>{if(ne||!x)return;ne=g("div","tvw-clear-chat-tooltip"),ne.textContent=B;let j=g("div");j.className="tvw-clear-chat-tooltip-arrow",ne.appendChild(j);let le=x.getBoundingClientRect();ne.style.position="fixed",ne.style.left=`${le.left+le.width/2}px`,ne.style.top=`${le.top-8}px`,ne.style.transform="translate(-50%, -100%)",document.body.appendChild(ne)},_e=()=>{ne&&ne.parentNode&&(ne.parentNode.removeChild(ne),ne=null)};k.addEventListener("mouseenter",We),k.addEventListener("mouseleave",_e),x.addEventListener("focus",We),x.addEventListener("blur",_e),k._cleanupTooltip=()=>{_e(),k&&(k.removeEventListener("mouseenter",We),k.removeEventListener("mouseleave",_e)),x&&(x.removeEventListener("focus",We),x.removeEventListener("blur",_e))}}E==="inline"&&t.appendChild(k)}let K=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":C&&E==="inline"?"":"tvw-ml-auto"),y=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");y.style.height=i,y.style.width=i,y.type="button";let R=(X=o.closeButtonTooltipText)!=null?X:"Close chat",W=(He=o.closeButtonShowTooltip)!=null?He:!0;y.setAttribute("aria-label",R),y.style.display=r?"":"none";let H=(vt=o.closeButtonIconName)!=null?vt:"x",oe=(yt=o.closeButtonIconText)!=null?yt:"\xD7",U=ie(H,"20px",o.closeButtonColor||"",1);if(U?y.appendChild(U):y.textContent=oe,o.closeButtonColor?(y.style.color=o.closeButtonColor,y.classList.remove("tvw-text-cw-muted")):(y.style.color="",y.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(y.style.backgroundColor=o.closeButtonBackgroundColor,y.classList.remove("hover:tvw-bg-gray-100")):(y.style.backgroundColor="",y.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Q=o.closeButtonBorderWidth||"0px",De=o.closeButtonBorderColor||"transparent";y.style.border=`${Q} solid ${De}`,y.classList.remove("tvw-border-none")}else y.style.border="",y.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(y.style.borderRadius=o.closeButtonBorderRadius,y.classList.remove("tvw-rounded-full")):(y.style.borderRadius="",y.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(y.style.paddingLeft=o.closeButtonPaddingX,y.style.paddingRight=o.closeButtonPaddingX):(y.style.paddingLeft="",y.style.paddingRight=""),o.closeButtonPaddingY?(y.style.paddingTop=o.closeButtonPaddingY,y.style.paddingBottom=o.closeButtonPaddingY):(y.style.paddingTop="",y.style.paddingBottom=""),K.appendChild(y),W&&R){let Q=null,De=()=>{if(Q)return;Q=g("div","tvw-clear-chat-tooltip"),Q.textContent=R;let Wt=g("div");Wt.className="tvw-clear-chat-tooltip-arrow",Q.appendChild(Wt);let Mt=y.getBoundingClientRect();Q.style.position="fixed",Q.style.left=`${Mt.left+Mt.width/2}px`,Q.style.top=`${Mt.top-8}px`,Q.style.transform="translate(-50%, -100%)",document.body.appendChild(Q)},bt=()=>{Q&&Q.parentNode&&(Q.parentNode.removeChild(Q),Q=null)};K.addEventListener("mouseenter",De),K.addEventListener("mouseleave",bt),y.addEventListener("focus",De),y.addEventListener("blur",bt),K._cleanupTooltip=()=>{bt(),K.removeEventListener("mouseenter",De),K.removeEventListener("mouseleave",bt),y.removeEventListener("focus",De),y.removeEventListener("blur",bt)}}return a!=="top-right"&&t.appendChild(K),{header:t,iconHolder:v,headerTitle:m,headerSubtitle:h,closeButton:y,closeButtonWrapper:K,clearChatButton:x,clearChatButtonWrapper:k}},Mn=(e,n,r)=>{var i,a,d,c;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=t.closeButtonPlacement)!=null?a:"inline",s=(c=(d=t.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var Ai=e=>dn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),Ei=e=>{var S,C,E,x;let{config:n,showClose:r=!0,onClose:t}=e,o=(S=n==null?void 0:n.launcher)!=null?S:{},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=(C=o.title)!=null?C:"Chat Assistant",s.appendChild(i);let a=(E=o.closeButtonSize)!=null?E:"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",u=ie(v,"20px",o.closeButtonColor||"",2);u?c.appendChild(u):c.textContent="\xD7",t&&c.addEventListener("click",t),d.appendChild(c),s.appendChild(d);let m=g("div");m.style.display="none";let h=g("span");return h.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:h,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Ti=e=>{var y,R,W,H,oe,U,re,J;let{config:n,showClose:r=!0,onClose:t,onClearChat:o}=e,s=(y=n==null?void 0:n.launcher)!=null?y:{},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=(R=s.headerIconSize)!=null?R:"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 q=parseFloat(d)||24,pe=ie(v,q*.5,"#ffffff",2);pe?c.replaceChildren(pe):c.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}"}else if(s.iconUrl){let q=g("img");q.src=s.iconUrl,q.alt="",q.className="tvw-rounded-xl tvw-object-cover",q.style.height=d,q.style.width=d,c.replaceChildren(q)}else c.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}";let u=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(oe=s.title)!=null?oe:"Chat Assistant";let h=g("span","tvw-text-sm tvw-text-cw-muted");h.textContent=(U=s.subtitle)!=null?U:"Here to help you get answers fast",u.append(m,h),a.append(c,u);let S=(re=s.closeButtonSize)!=null?re:"32px",C=g("div",""),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=S,E.style.width=S,E.type="button",E.setAttribute("aria-label","Close chat"),E.style.display=r?"":"none";let x=(J=s.closeButtonIconName)!=null?J:"x",k=ie(x,"20px",s.closeButtonColor||"",2);k?E.appendChild(k):E.textContent="\xD7",t&&E.addEventListener("click",t),C.appendChild(E),a.appendChild(C),i.appendChild(a);let K=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return K.textContent="Online and ready to help",i.appendChild(K),{header:i,iconHolder:c,headerTitle:m,headerSubtitle:h,closeButton:E,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}},Js={default:Ai,minimal:Ei,expanded:Ti},Mi=e=>{var n;return(n=Js[e])!=null?n:Js.default},es=(e,n,r)=>{var i,a,d;if(n!=null&&n.render){let c=n.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),v=g("div");v.style.display="none";let u=g("span"),m=g("span"),h=g("button");h.style.display="none";let S=g("div");return S.style.display="none",{header:c,iconHolder:v,headerTitle:u,headerSubtitle:m,closeButton:h,closeButtonWrapper:S,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=Mi(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var La=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},ts=e=>{var Oe,Ee,te,me,Ne,Qe,At,ue,Y,ut,pt,ht,Ot,wt,X,He,vt,yt,Q,De,bt,Wt,Mt,_,Ze,Pe,z,B,fe,ce;let{config:n}=e,r=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),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=(Ee=(Oe=n==null?void 0:n.copy)==null?void 0:Oe.inputPlaceholder)!=null?Ee:"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=(me=(te=n==null?void 0:n.theme)==null?void 0:te.inputFontFamily)!=null?me:"sans-serif",a=(Qe=(Ne=n==null?void 0:n.theme)==null?void 0:Ne.inputFontWeight)!=null?Qe:"400";s.style.fontFamily=La(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let u=()=>{s.style.height="auto";let ne=Math.min(s.scrollHeight,v);s.style.height=`${ne}px`};s.addEventListener("input",u),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=(At=n==null?void 0:n.sendButton)!=null?At:{},h=(ue=m.useIcon)!=null?ue:!1,S=(Y=m.iconText)!=null?Y:"\u2191",C=m.iconName,E=(ut=m.tooltipText)!=null?ut:"Send message",x=(pt=m.showTooltip)!=null?pt:!1,k=(ht=m.size)!=null?ht:"40px",K=m.backgroundColor,y=m.textColor,R=g("div","tvw-send-button-wrapper"),W=g("button",h?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(W.type="submit",h){if(W.style.width=k,W.style.height=k,W.style.minWidth=k,W.style.minHeight=k,W.style.fontSize="18px",W.style.lineHeight="1",W.innerHTML="",C){let ne=parseFloat(k)||24,We=y&&typeof y=="string"&&y.trim()?y.trim():"currentColor",_e=ie(C,ne,We,2);_e?(W.appendChild(_e),W.style.color=We):(W.textContent=S,y?W.style.color=y:W.classList.add("tvw-text-white"))}else W.textContent=S,y?W.style.color=y:W.classList.add("tvw-text-white");K?W.style.backgroundColor=K:W.classList.add("tvw-bg-cw-primary")}else W.textContent=(wt=(Ot=n==null?void 0:n.copy)==null?void 0:Ot.sendButtonLabel)!=null?wt:"Send",y?W.style.color=y:W.classList.add("tvw-text-white");if(m.borderWidth&&(W.style.borderWidth=m.borderWidth,W.style.borderStyle="solid"),m.borderColor&&(W.style.borderColor=m.borderColor),m.paddingX?(W.style.paddingLeft=m.paddingX,W.style.paddingRight=m.paddingX):(W.style.paddingLeft="",W.style.paddingRight=""),m.paddingY?(W.style.paddingTop=m.paddingY,W.style.paddingBottom=m.paddingY):(W.style.paddingTop="",W.style.paddingBottom=""),x&&E){let ne=g("div","tvw-send-button-tooltip");ne.textContent=E,R.appendChild(ne)}R.appendChild(W);let H=(X=n==null?void 0:n.voiceRecognition)!=null?X:{},oe=H.enabled===!0,U=null,re=null,J=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(oe&&J){re=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"),U.type="button",U.setAttribute("aria-label","Start voice recognition");let ne=(He=H.iconName)!=null?He:"mic",We=(vt=H.iconSize)!=null?vt:k,_e=parseFloat(We)||24,j=(yt=H.backgroundColor)!=null?yt:K,le=(Q=H.iconColor)!=null?Q:y;U.style.width=We,U.style.height=We,U.style.minWidth=We,U.style.minHeight=We,U.style.fontSize="18px",U.style.lineHeight="1";let Fe=le||"currentColor",Ke=ie(ne,_e,Fe,1.5);Ke?(U.appendChild(Ke),U.style.color=Fe):(U.textContent="\u{1F3A4}",U.style.color=Fe),j?U.style.backgroundColor=j:U.classList.add("tvw-bg-cw-primary"),le?U.style.color=le:!le&&!y&&U.classList.add("tvw-text-white"),H.borderWidth&&(U.style.borderWidth=H.borderWidth,U.style.borderStyle="solid"),H.borderColor&&(U.style.borderColor=H.borderColor),H.paddingX&&(U.style.paddingLeft=H.paddingX,U.style.paddingRight=H.paddingX),H.paddingY&&(U.style.paddingTop=H.paddingY,U.style.paddingBottom=H.paddingY),re.appendChild(U);let ot=(De=H.tooltipText)!=null?De:"Start voice recognition";if(((bt=H.showTooltip)!=null?bt:!1)&&ot){let it=g("div","tvw-send-button-tooltip");it.textContent=ot,re.appendChild(it)}}let q=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},pe=q.enabled===!0,$=null,Z=null,P=null,ee=null;if(pe){ee=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ee.style.display="none",P=g("input"),P.type="file",P.accept=((Mt=q.allowedTypes)!=null?Mt:ln).join(","),P.multiple=((_=q.maxFiles)!=null?_:4)>1,P.style.display="none",P.setAttribute("aria-label","Attach files"),Z=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",(Ze=q.buttonTooltipText)!=null?Ze:"Attach file");let ne=(Pe=q.buttonIconName)!=null?Pe:"paperclip",We=k,_e=parseFloat(We)||40,j=Math.round(_e*.6);$.style.width=We,$.style.height=We,$.style.minWidth=We,$.style.minHeight=We,$.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 le=ie(ne,j,"currentColor",1.5);le?$.appendChild(le):$.textContent="\u{1F4CE}",$.addEventListener("click",ot=>{ot.preventDefault(),P==null||P.click()}),Z.appendChild($);let Fe=(z=q.buttonTooltipText)!=null?z:"Attach file",Ke=g("div","tvw-send-button-tooltip");Ke.textContent=Fe,Z.appendChild(Ke)}o.addEventListener("click",ne=>{ne.target!==W&&ne.target!==R&&ne.target!==U&&ne.target!==re&&ne.target!==$&&ne.target!==Z&&s.focus()}),ee&&(ee.style.gap="8px",o.append(ee)),P&&o.append(P),o.append(s);let be=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),ge=g("div","tvw-flex tvw-items-center tvw-gap-2");Z&&ge.append(Z);let Je=g("div","tvw-flex tvw-items-center tvw-gap-1");re&&Je.append(re),Je.append(R),be.append(ge,Je),o.append(be);let lt=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Tt=(B=n==null?void 0:n.statusIndicator)!=null?B:{},$t=(fe=Tt.visible)!=null?fe:!0;return lt.style.display=$t?"":"none",lt.textContent=(ce=Tt.idleText)!=null?ce:"Online",r.append(t,o,lt),{footer:r,suggestions:t,composerForm:o,textarea:s,sendButton:W,sendButtonWrapper:R,micButton:U,micButtonWrapper:re,statusText:lt,attachmentButton:$,attachmentButtonWrapper:Z,attachmentInput:P,attachmentPreviewsContainer:ee,actionsRow:be,leftActions:ge,rightActions:Je}};var Li=e=>{var d,c,v,u,m,h,S;if(!((c=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?c:!0)){let C=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),E=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(u=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?u:"100%";return C.style.width=x,E.style.width="100%",C.appendChild(E),{wrapper:C,panel:E}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},t=r.position&&Ut[r.position]?Ut[r.position]:Ut["bottom-right"],o=g("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(S=(h=e==null?void 0:e.launcher)==null?void 0:h.width)!=null?S:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},ki=(e,n=!0)=>{var h,S,C,E,x,k,K;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"),t=(h=e==null?void 0:e.layout)==null?void 0:h.header,o=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,s=t?es(e,t,{showClose:n}):dn({config:e,showClose:n}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(E=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?E:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeSubtitle)!=null?k:"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 u=ts({config:e}),m=((K=e==null?void 0:e.layout)==null?void 0:K.showFooter)!==!1;return o?Mn(r,s,e):(s.header.style.display="none",Mn(r,s,e)),r.append(i),m||(u.footer.style.display="none"),r.append(u.footer),{container:r,body:i,messagesWrapper:v,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.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:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions}};var ka=320,Wa=320,Ia=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Pa=(e,n,r)=>{if(e.length===0)return null;try{let t=g("div","tvw-flex tvw-flex-col tvw-gap-2");t.setAttribute("data-message-attachments","images"),n&&(t.style.marginBottom="8px");let o=0,s=!1,i=()=>{s||(s=!0,t.remove(),r==null||r())};return e.forEach((a,d)=>{var u;let c=g("img");c.alt=((u=a.alt)==null?void 0:u.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=`${ka}px`,c.style.maxHeight=`${Wa}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,t.appendChild(c)}),o===0?(i(),null):t}catch{return r==null||r(),null}},Ln=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(r),e.appendChild(t),e.appendChild(o),e},Ii=(e,n,r)=>{let t={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:Ln};if(n){let o=n(t);if(o!==null)return o}return Ln()},Ha=(e,n)=>{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"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=g("img");o.src=t,o.alt=n==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=n==="user"?"U":"A",r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Wi=(e,n)=>{let r=g("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?r.textContent=n.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Ba=(e,n="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},Pi=(e,n,r)=>{var h,S,C,E,x,k;let t=(h=n.showCopy)!=null?h:!0,o=(S=n.showUpvote)!=null?S:!0,s=(C=n.showDownvote)!=null?C:!0,i=(E=n.visibility)!=null?E:"hover",a=(x=n.align)!=null?x:"right",d=(k=n.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"}[d],u=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let m=(K,y,R)=>{let W=document.createElement("button");W.className="tvw-message-action-btn",W.setAttribute("aria-label",y),W.setAttribute("title",y),W.setAttribute("data-action",R);let H=ie(K,14,"currentColor",2);return H&&W.appendChild(H),W};return t&&u.appendChild(m("copy","Copy message","copy")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),s&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},ns=(e,n,r,t,o,s)=>{var U,re,J,q,pe,$,Z;let i=r!=null?r:{},a=(U=i.layout)!=null?U:"bubble",d=i.avatar,c=i.timestamp,v=(re=d==null?void 0:d.show)!=null?re:!1,u=(J=c==null?void 0:c.show)!=null?J:!1,m=(q=d==null?void 0:d.position)!=null?q:"left",h=(pe=c==null?void 0:c.position)!=null?pe:"below",S=Ba(e.role,a),C=g("div",S.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id);let E=Ia(e),x=(Z=($=e.content)==null?void 0:$.trim())!=null?Z:"",K=E.length>0&&x===Ss,y=document.createElement("div"),R=document.createElement("div");if(R.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),y.appendChild(R),K&&(R.style.display="none"),u&&h==="inline"&&e.createdAt){let P=Wi(e,c);P.classList.add("tvw-ml-2","tvw-inline"),y.appendChild(P)}if(E.length>0){let P=Pa(E,!K&&!!x,()=>{K&&(R.style.display="")});P?C.appendChild(P):K&&(R.style.display="")}if(C.appendChild(y),u&&h==="below"&&e.createdAt){let P=Wi(e,c);P.classList.add("tvw-mt-1"),C.appendChild(P)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let P=Ii("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);P&&C.appendChild(P)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let P=Pi(e,t,o);C.appendChild(P)}if(!v||e.role==="system")return C;let H=g("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),oe=Ha(d,e.role);return m==="right"||m==="left"&&e.role==="user"?H.append(C,oe):H.append(oe,C),C.classList.remove("tvw-max-w-[85%]"),C.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),H},Ra=(e,n,r,t,o,s)=>{let i=r!=null?r:{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ns(e,n,r,t,o,s)};var kn=new Set,Hi=(e,n)=>{let r=kn.has(e),t=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".tvw-border-t");if(!t||!o)return;t.setAttribute("aria-expanded",r?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},Ks=e=>{let n=e.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-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let t=kn.has(e.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",t?"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=fi(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),v=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);v?d.appendChild(v):d.textContent=t?"Hide":"Show";let u=g("div","tvw-flex tvw-items-center tvw-ml-auto");u.append(d),o.append(s,u);let m=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let h=n.chunks.join(""),S=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return S.textContent=h||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(S),(()=>{o.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let x=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),r.append(o,m),r};var Wn=new Set,Bi=(e,n,r)=>{var c;let t=Wn.has(e),o=(c=r==null?void 0:r.toolCall)!=null?c:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",t?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let v=o.toggleTextColor||o.headerTextColor||"currentColor",u=ie(t?"chevron-up":"chevron-down",16,v,2);u?d.appendChild(u):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Ys=(e,n)=>{var C;let r=e.toolCall,t=(C=n==null?void 0:n.toolCall)!=null?C:{},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-${e.id}`,o.setAttribute("data-message-id",e.id),t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=Wn.has(e.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),d=g("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=hi(r),a.appendChild(d);let c=g("div","tvw-flex tvw-items-center"),v=t.toggleTextColor||t.headerTextColor||"currentColor",u=ie(s?"chevron-up":"chevron-down",16,v,2);u?c.appendChild(u):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 h=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(h.style.display=s?"":"none",t.contentBackgroundColor&&(h.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(h.style.color=t.contentTextColor),t.contentPaddingX&&(h.style.paddingLeft=t.contentPaddingX,h.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(h.style.paddingTop=t.contentPaddingY,h.style.paddingBottom=t.contentPaddingY),r.name){let E=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?E.style.color=t.contentTextColor:t.headerTextColor&&(E.style.color=t.headerTextColor),E.textContent=r.name,h.appendChild(E)}if(r.args!==void 0){let E=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.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-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=Os(r.args),E.append(x,k),h.appendChild(E)}if(r.chunks&&r.chunks.length){let E=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.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-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=r.chunks.join(`
|
|
16
|
+
`),E.append(x,k),h.appendChild(E)}if(r.status==="complete"&&r.result!==void 0){let E=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(x.style.color=t.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-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=Os(r.result),E.append(x,k),h.appendChild(E)}if(r.status==="complete"&&typeof r.duration=="number"){let E=g("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(E.style.color=t.contentTextColor),E.textContent=`Duration: ${r.duration}ms`,h.appendChild(E)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let E=t.toggleTextColor||t.headerTextColor||"currentColor",x=ie(s?"chevron-up":"chevron-down",16,E,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",h.style.display=s?"":"none"})(),o.append(i,h),o};var Ri=e=>{let n=[];return{buttons:n,render:(t,o,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(h=>h.role==="user"))return;let v=document.createDocumentFragment(),u=o?o.isStreaming():!1,m=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(h=>{let S=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");S.type="button",S.textContent=h,S.disabled=u,a!=null&&a.fontFamily&&(S.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(S.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(S.style.paddingLeft=a.paddingX,S.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(S.style.paddingTop=a.paddingY,S.style.paddingBottom=a.paddingY),S.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(h))}),v.appendChild(S),n.push(S)}),e.appendChild(v)}}};var ss=class{constructor(n=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=r}push(n){var r;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(r=this.store)==null||r.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let r=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let t of r)this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(t.type);return this.totalCaptured=n.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let r=this.getAll();return n>=r.length?r:r.slice(r.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var rs=class{constructor(n="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=r}open(){return new Promise((n,r)=>{try{let t=indexedDB.open(this.dbName,1);t.onupgradeneeded=()=>{let o=t.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},t.onsuccess=()=>{this.db=t.result,n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}getAll(){return new Promise((n,r)=>{if(!this.db){n([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{n(i.result)},i.onerror=()=>{r(i.error)}}catch(t){r(t)}})}getCount(){return new Promise((n,r)=>{if(!this.db){n(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}clear(){return new Promise((n,r)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,r)=>{try{let t=indexedDB.deleteDatabase(this.dbName);t.onsuccess=()=>{n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}};function In(e,n){n&&n.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var Fa={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"}},$a={bg:"#f3f4f6",text:"#4b5563"},Oa=["flowName","stepName","reasoningText","text","name","tool","toolName"],Na=100;function Da(e,n){let r={...Fa,...n};if(r[e])return r[e];for(let t of Object.keys(r))if(t.endsWith("_")&&e.startsWith(t))return r[t];return $a}function _a(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function ja(e){let n=new Date(e),r=String(n.getHours()).padStart(2,"0"),t=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${r}:${t}:${o}.${s}`}function qa(e,n){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let t of n){let o=t.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function za(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),r()})}function Ua(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Ja(e,n,r){let t,o;try{o=JSON.parse(e.payload),t=JSON.stringify(o,null,2)}catch{o=e.payload,t=e.payload}let s=n.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=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=t,a.appendChild(d),a}}function Vs(e,n,r,t,o,s,i,a){var m;let d=o.has(e.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");In(c,(m=t.classNames)==null?void 0:m.eventRow);let v=i.find(h=>h.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let h=v.renderEventStreamRow({event:e,index:n,config:a,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(h)return c.appendChild(h),c}return c.appendChild(u()),c;function u(){var q,pe;let h=g("div",""),S=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");S.setAttribute("data-event-id",e.id);let C=g("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),E=ie(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&C.appendChild(E);let x=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),k=(q=t.timestampFormat)!=null?q:"relative";x.textContent=k==="relative"?_a(e.timestamp,r):ja(e.timestamp);let K=null;t.showSequenceNumbers!==!1&&(K=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),K.textContent=String(n+1));let y=Da(e.type,t.badgeColors),R=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");R.style.backgroundColor=y.bg,R.style.color=y.text,R.style.borderColor=y.text+"50",R.textContent=e.type;let W=(pe=t.descriptionFields)!=null?pe:Oa,H=qa(e.payload,W),oe=null;H&&(oe=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),oe.textContent=H);let U=g("div","tvw-flex-1 tvw-min-w-0"),re=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"),J=ie("clipboard","12px","currentColor",1.5);return J&&re.appendChild(J),re.addEventListener("click",async $=>{$.stopPropagation(),await za(Ua(e)),re.innerHTML="";let Z=ie("check","12px","currentColor",1.5);Z&&re.appendChild(Z),setTimeout(()=>{re.innerHTML="";let P=ie("clipboard","12px","currentColor",1.5);P&&re.appendChild(P)},1500)}),S.appendChild(C),S.appendChild(x),K&&S.appendChild(K),S.appendChild(R),oe&&S.appendChild(oe),S.appendChild(U),S.appendChild(re),h.appendChild(S),d&&h.appendChild(Ja(e,i,a)),h}}function Fi(e){var c,v;let{buffer:n,getFullHistory:r,onClose:t,config:o,plugins:s=[]}=e,i=(v=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?v:{},a=s.find(u=>u.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let u=a.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>d().element,onClose:t});if(u)return{element:u,update:()=>{},destroy:()=>{}}}return d();function d(){let u=i.classNames,m=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");In(m,u==null?void 0:u.panel);let h=[],S="",C="",E=null,x=[],k={},K=0,y=!1,R=0,W=0,H=!1,oe=null,U=!1,re=0,J=new Set,q=new Map,pe="",$="",Z=null,P,ee,be,ge,Je;function lt(){let z=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),B=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");In(B,u==null?void 0:u.headerBar);let fe=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");fe.textContent="Events",P=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"),P.textContent="0";let ce=g("div","tvw-flex-1");ee=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 ne=g("option","");ne.value="",ne.textContent="All events",ee.appendChild(ne),be=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"),be.type="button",be.title="Copy All";let _e=ie("clipboard-copy","12px","currentColor",1.5);_e&&be.appendChild(_e);let j=g("span","tvw-text-xs");j.textContent="Copy All",be.appendChild(j),B.appendChild(fe),B.appendChild(P),B.appendChild(ce),B.appendChild(ee),B.appendChild(be);let le=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");In(le,u==null?void 0:u.searchBar);let Fe=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),Ke=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");Fe&&Ke.appendChild(Fe),ge=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"),In(ge,u==null?void 0:u.searchInput),ge.type="text",ge.placeholder="Search event payloads...",Je=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"),Je.type="button",Je.style.display="none";let ot=ie("x","12px","currentColor",2);return ot&&Je.appendChild(ot),le.appendChild(Ke),le.appendChild(ge),le.appendChild(Je),z.appendChild(B),z.appendChild(le),z}let Tt,$t=s.find(z=>z.renderEventStreamToolbar);if($t!=null&&$t.renderEventStreamToolbar&&o){let z=$t.renderEventStreamToolbar({config:o,defaultRenderer:()=>lt(),eventCount:n.getSize(),filteredCount:0,onFilterChange:B=>{S=B,pt(),wt()},onSearchChange:B=>{C=B,pt(),wt()}});Tt=z!=null?z:lt()}else Tt=lt();let Oe=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");Oe.style.display="none";let Ee=g("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),te=g("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");te.style.height="100%";let me=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");In(me,u==null?void 0:u.scrollIndicator),me.style.display="none";let Ne=ie("arrow-down","12px","currentColor",2);Ne&&me.appendChild(Ne);let Qe=g("span","");me.appendChild(Qe);let At=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");At.style.display="none",Ee.appendChild(te),Ee.appendChild(At),Ee.appendChild(me),m.setAttribute("tabindex","0"),m.appendChild(Tt),m.appendChild(Oe),m.appendChild(Ee);function ue(){let z=n.getAll(),B={};for(let j of z)B[j.type]=(B[j.type]||0)+1;let fe=Object.keys(B).sort(),ce=fe.length!==x.length||!fe.every((j,le)=>j===x[le]),ne=!ce&&fe.some(j=>B[j]!==k[j]),We=z.length!==Object.values(k).reduce((j,le)=>j+le,0);if(!ce&&!ne&&!We||(x=fe,k=B,!ee))return;let _e=ee.value;if(ee.options[0].textContent="All events",ce){for(;ee.options.length>1;)ee.remove(1);for(let j of fe){let le=g("option","");le.value=j,le.textContent=`${j} (${B[j]||0})`,ee.appendChild(le)}_e&&fe.includes(_e)?ee.value=_e:_e&&(ee.value="",S="")}else for(let j=1;j<ee.options.length;j++){let le=ee.options[j];le.textContent=`${le.value} (${B[le.value]||0})`}}function Y(){let z=n.getAll();if(S&&(z=z.filter(B=>B.type===S)),C){let B=C.toLowerCase();z=z.filter(fe=>fe.type.toLowerCase().includes(B)||fe.payload.toLowerCase().includes(B))}return z}function ut(){return S!==""||C!==""}function pt(){K=0,R=0,y=!1,me.style.display="none"}function ht(z){J.has(z)?J.delete(z):J.add(z),Z=z;let B=te.scrollTop,fe=y;U=!0,y=!0,wt(),te.scrollTop=B,y=fe,U=!1}function Ot(){return te.scrollHeight-te.scrollTop-te.clientHeight<=50}function wt(){W=Date.now(),H=!1,ue();let z=n.getEvictedCount();z>0?(Oe.textContent=`${z.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",h=Y();let B=h.length,fe=n.getSize()>0;P&&(P.textContent=String(n.getSize())),B===0&&fe&&ut()?(At.textContent=C?`No events matching '${C}'`:"No events matching filter",At.style.display="",te.style.display="none"):(At.style.display="none",te.style.display=""),be&&(be.title=ut()?`Copy Filtered (${B})`:"Copy All"),y&&B>K&&(R+=B-K,Qe.textContent=`${R} new event${R===1?"":"s"}`,me.style.display=""),K=B;let ce=n.getAll(),ne=ce.length>0?ce[0].timestamp:0,We=new Set(h.map(le=>le.id));for(let le of J)We.has(le)||J.delete(le);let _e=S!==pe||C!==$,j=q.size===0&&h.length>0;if(_e||j||h.length===0){te.innerHTML="",q.clear();let le=document.createDocumentFragment();for(let Fe=0;Fe<h.length;Fe++){let Ke=Vs(h[Fe],Fe,ne,i,J,ht,s,o);q.set(h[Fe].id,Ke),le.appendChild(Ke)}te.appendChild(le),pe=S,$=C,Z=null}else{if(Z!==null){let Fe=q.get(Z);if(Fe&&Fe.parentNode===te){let Ke=h.findIndex(ot=>ot.id===Z);if(Ke>=0){let ot=Vs(h[Ke],Ke,ne,i,J,ht,s,o);te.insertBefore(ot,Fe),Fe.remove(),q.set(Z,ot)}}Z=null}let le=new Set(h.map(Fe=>Fe.id));for(let[Fe,Ke]of q)le.has(Fe)||(Ke.remove(),q.delete(Fe));for(let Fe=0;Fe<h.length;Fe++){let Ke=h[Fe];if(!q.has(Ke.id)){let ot=Vs(Ke,Fe,ne,i,J,ht,s,o);q.set(Ke.id,ot),te.appendChild(ot)}}}y||(te.scrollTop=te.scrollHeight)}function X(){if(Date.now()-W>=Na){oe!==null&&(cancelAnimationFrame(oe),oe=null),wt();return}H||(H=!0,oe=requestAnimationFrame(()=>{oe=null,wt()}))}let He=(z,B)=>{if(!be)return;be.innerHTML="";let fe=ie(z,"12px","currentColor",1.5);fe&&be.appendChild(fe);let ce=g("span","tvw-text-xs");ce.textContent="Copy All",be.appendChild(ce),setTimeout(()=>{be.innerHTML="";let ne=ie("clipboard-copy","12px","currentColor",1.5);ne&&be.appendChild(ne);let We=g("span","tvw-text-xs");We.textContent="Copy All",be.appendChild(We),be.disabled=!1},B)},vt=async()=>{if(be){be.disabled=!0;try{let z;ut()?z=h:z=r?await r():n.getAll();let B=z.map(fe=>{try{return JSON.parse(fe.payload)}catch{return fe.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),He("check",1500)}catch{He("x",1500)}}},yt=()=>{ee&&(S=ee.value,pt(),wt())},Q=()=>{!ge||!Je||(Je.style.display=ge.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{C=ge.value,pt(),wt()},150))},De=()=>{!ge||!Je||(ge.value="",C="",Je.style.display="none",E&&clearTimeout(E),pt(),wt())},bt=()=>{if(U)return;let z=te.scrollTop,B=z>re;re=z,Ot()&&B?(y=!1,R=0,me.style.display="none"):Ot()||(y=!0)},Wt=z=>{z.deltaY<0&&(y=!0)},Mt=()=>{te.scrollTop=te.scrollHeight,y=!1,R=0,me.style.display="none"},_=z=>{let B=z.target;if(!B||B.closest("button"))return;let fe=B.closest("[data-event-id]");if(!fe)return;let ce=fe.getAttribute("data-event-id");ce&&ht(ce)},Ze=z=>{if((z.metaKey||z.ctrlKey)&&z.key==="f"){z.preventDefault(),ge==null||ge.focus(),ge==null||ge.select();return}z.key==="Escape"&&(ge&&document.activeElement===ge?(De(),ge.blur(),m.focus()):t&&t())};be&&be.addEventListener("click",vt),ee&&ee.addEventListener("change",yt),ge&&ge.addEventListener("input",Q),Je&&Je.addEventListener("click",De),te.addEventListener("scroll",bt),te.addEventListener("wheel",Wt,{passive:!0}),te.addEventListener("click",_),me.addEventListener("click",Mt),m.addEventListener("keydown",Ze);function Pe(){E&&clearTimeout(E),oe!==null&&(cancelAnimationFrame(oe),oe=null),H=!1,q.clear(),be&&be.removeEventListener("click",vt),ee&&ee.removeEventListener("change",yt),ge&&ge.removeEventListener("input",Q),Je&&Je.removeEventListener("click",De),te.removeEventListener("scroll",bt),te.removeEventListener("wheel",Wt),te.removeEventListener("click",_),me.removeEventListener("click",Mt),m.removeEventListener("keydown",Ze)}return{element:m,update:X,destroy:Pe}}}var $i={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Xs=(e,n,r,t)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var S,C,E;if(s.dataset.enhanced==="true")return;let i=(S=s.dataset.tvForm)!=null?S:"init";s.dataset.enhanced="true";let a=(C=$i[i])!=null?C:$i.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 W,H;let k=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");k.htmlFor=`${n.id}-${i}-${x.name}`;let K=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");K.textContent=x.label,k.appendChild(K);let y=(W=x.type)!=null?W:"text",R;y==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=y),R.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",R.id=`${n.id}-${i}-${x.name}`,R.name=x.name,R.placeholder=(H=x.placeholder)!=null?H:"",x.required&&(R.required=!0),k.appendChild(R),v.appendChild(k)});let u=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]"),h=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");h.type="submit",h.textContent=(E=a.submitLabel)!=null?E:"Submit",u.appendChild(m),u.appendChild(h),v.appendChild(u),s.replaceChildren(d,v),v.addEventListener("submit",async x=>{var R,W;x.preventDefault();let k=(R=r.formEndpoint)!=null?R:"/form",K=new FormData(v),y={};K.forEach((H,oe)=>{y[oe]=H}),y.type=i,h.disabled=!0,m.textContent="Submitting\u2026";try{let H=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let oe=await H.json();m.textContent=(W=oe.message)!=null?W:"Thanks! We'll be in touch soon.",oe.success&&oe.nextPrompt&&await t.sendMessage(String(oe.nextPrompt))}catch(H){m.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{h.disabled=!1}})})};var Gs=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var t;let r=this.plugins.get(n);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let t=new Set(n.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},Ms=new Gs;var Oi={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"},Ni={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},rt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Oi,darkTheme:Ni,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 Qs(e){var n,r,t,o,s,i,a,d,c,v,u,m,h,S,C,E,x,k,K;return e?{...rt,...e,theme:{...rt.theme,...e.theme},darkTheme:{...rt.darkTheme,...e.darkTheme},launcher:{...rt.launcher,...e.launcher,clearChat:{...(n=rt.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:{...rt.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...(o=rt.layout)==null?void 0:o.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=rt.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(c=(d=rt.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(u=(v=e.layout)==null?void 0:v.messages)==null?void 0:u.avatar},timestamp:{...(h=(m=rt.layout)==null?void 0:m.messages)==null?void 0:h.timestamp,...(C=(S=e.layout)==null?void 0:S.messages)==null?void 0:C.timestamp}},slots:{...(E=rt.layout)==null?void 0:E.slots,...(x=e.layout)==null?void 0:x.slots}},markdown:{...rt.markdown,...e.markdown,options:{...(k=rt.markdown)==null?void 0:k.options,...(K=e.markdown)==null?void 0:K.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var Di=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=e.get(o))==null||i.delete(s)};return{on:n,off:r,emit:(o,s)=>{var i;(i=e.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ka=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Ya=e=>{let n=e.trim(),r=n.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(r,o+1)}return null},Ls=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Ka(e),r=Ya(n);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},Zs=e=>typeof e=="string"?e:e==null?"":String(e),Pn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Zs(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=Zs(r.element);if(t&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Zs(r.text)}}},_i=e=>Array.isArray(e)?e.map(n=>String(n)):[],ks=e=>{let n=new Set(_i(e.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(_i(e.getSessionMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(n);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?e.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),t();let d={action:a,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let v=()=>{e.emit("action:resubmit",d)},u=c(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:v});if(!u)continue;if(u.handled){let m=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:m,resubmit:u.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var Va=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Xa=e=>e.map(n=>({...n,streaming:!1})),er=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?Va(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?Xa(r.messages):void 0};t.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var tr=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([r,t])=>{this.register(r,t)})}},os=new tr;import{parse as Ga,STR as Qa,OBJ as Za}from"partial-json";function el(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function tl(e,n){if(!el(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:n}}function nr(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e;try{let o=Ga(r,Qa|Za),s=tl(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function nl(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function sr(e,n){let{config:r,message:t,onPropsUpdate:o}=n,s=os.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:a=>{o&&o(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function sl(){let e=nr();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rr(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function or(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var rl=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ir(e){let{onSubmit:n,onDismiss:r,title:t="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:c=rl}=e,v=document.createElement("div");v.className="tvw-feedback-container tvw-feedback-csat",v.setAttribute("role","dialog"),v.setAttribute("aria-label","Customer satisfaction feedback");let u=null,m=document.createElement("div");m.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let S=document.createElement("h3");S.className="tvw-feedback-title",S.textContent=t,h.appendChild(S);let C=document.createElement("p");C.className="tvw-feedback-subtitle",C.textContent=o,h.appendChild(C),m.appendChild(h);let E=document.createElement("div");E.className="tvw-feedback-rating tvw-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let W=1;W<=5;W++){let H=document.createElement("button");H.type="button",H.className="tvw-feedback-rating-btn tvw-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${c[W-1]}`),H.title=c[W-1],H.dataset.rating=String(W),H.innerHTML=`
|
|
17
17
|
<svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
18
18
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
19
19
|
</svg>
|
|
20
|
-
`,H.addEventListener("click",()=>{c=W,S.forEach((oe,_)=>{let le=_<W;oe.classList.toggle("selected",le),oe.setAttribute("aria-checked",_===W-1?"true":"false")})}),S.push(H),E.appendChild(H)}h.appendChild(E);let k=null;if(d){let W=document.createElement("div");W.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),W.appendChild(k),h.appendChild(W)}let V=document.createElement("div");V.className="tvw-feedback-actions";let y=document.createElement("button");y.type="button",y.className="tvw-feedback-btn tvw-feedback-btn-skip",y.textContent=a,y.addEventListener("click",()=>{r==null||r(),w.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(c===null){E.classList.add("tvw-feedback-shake"),setTimeout(()=>E.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let W=(k==null?void 0:k.value.trim())||void 0;await n(c,W),w.remove()}catch(W){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",W)}}),V.appendChild(y),V.appendChild(O),h.appendChild(V),w.appendChild(h),w}function ir(e){let{onSubmit:n,onDismiss:r,title:t="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:g="Not likely",highLabel:w="Very likely"}=e,c=document.createElement("div");c.className="tvw-feedback-container tvw-feedback-nps",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Net Promoter Score feedback");let h=null,f=document.createElement("div");f.className="tvw-feedback-content";let x=document.createElement("div");x.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=t,x.appendChild(C);let E=document.createElement("p");E.className="tvw-feedback-subtitle",E.textContent=o,x.appendChild(E),f.appendChild(x);let S=document.createElement("div");S.className="tvw-feedback-rating tvw-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="tvw-feedback-labels";let V=document.createElement("span");V.className="tvw-feedback-label-low",V.textContent=g;let y=document.createElement("span");y.className="tvw-feedback-label-high",y.textContent=w,k.appendChild(V),k.appendChild(y);let O=document.createElement("div");O.className="tvw-feedback-numbers";let W=[];for(let X=0;X<=10;X++){let U=document.createElement("button");U.type="button",U.className="tvw-feedback-rating-btn tvw-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${X} out of 10`),U.textContent=String(X),U.dataset.rating=String(X),X<=6?U.classList.add("tvw-feedback-detractor"):X<=8?U.classList.add("tvw-feedback-passive"):U.classList.add("tvw-feedback-promoter"),U.addEventListener("click",()=>{h=X,W.forEach((Se,N)=>{Se.classList.toggle("selected",N===X),Se.setAttribute("aria-checked",N===X?"true":"false")})}),W.push(U),O.appendChild(U)}S.appendChild(k),S.appendChild(O),f.appendChild(S);let H=null;if(d){let X=document.createElement("div");X.className="tvw-feedback-comment-container",H=document.createElement("textarea"),H.className="tvw-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),X.appendChild(H),f.appendChild(X)}let oe=document.createElement("div");oe.className="tvw-feedback-actions";let _=document.createElement("button");_.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-skip",_.textContent=a,_.addEventListener("click",()=>{r==null||r(),c.remove()});let le=document.createElement("button");return le.type="button",le.className="tvw-feedback-btn tvw-feedback-btn-submit",le.textContent=i,le.addEventListener("click",async()=>{if(h===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}le.disabled=!0,le.textContent="Submitting...";try{let X=(H==null?void 0:H.value.trim())||void 0;await n(h,X),c.remove()}catch(X){le.disabled=!1,le.textContent=i,console.error("[NPS Feedback] Failed to submit:",X)}}),oe.appendChild(_),oe.appendChild(le),f.appendChild(oe),c.appendChild(f),c}var Hn="persona-chat-history",Za=30*1e3;function el(e){var n,r,t,o,s,i,a,d,g;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(t=e.persist)==null?void 0:t.openState)!=null?o:!0,voiceState:(i=(s=e.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=e.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(g=e.clearOnChatClear)!=null?g:!0}:null}function tl(e){try{let n=e==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var ar=e=>!e||typeof e!="object"?{}:{...e},Di=e=>e.map(n=>({...n,streaming:!1})),ji=(e,n,r)=>{let t=e!=null&&e.markdown?bs(e.markdown):null;return o=>{var a,d,g;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(n){let w=n.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});w!==null&&(s=w.text,w.persist||(o.message.__skipPersist=!0),w.resubmit&&!o.streaming&&r&&r())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(g=i!=null?i:o.text)!=null?g:""}):t?t(s):Fs(s)}},lr=(e,n,r)=>{var v,T,se,Ee,Ye,Lt,tt,Ct,gt,De,qe,lt,ze,xt,Rt,_t,ur,pr,gr,mr,hr,fr,wr,vr,yr,br,Cr,xr,Sr,Ar,Er,Tr;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let t=Gs(n),o=Ts.getForInstance(t.plugins);t.components&&rs.registerAll(t.components);let s=Oi(),i=(v=t.storageAdapter)!=null?v:Zs(),a={},d=null,g=l=>{if(t.onStateLoaded)try{return t.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(u=>{let b=u!=null?u:{messages:[],metadata:{}};return g(b)});else{let u=l!=null?l:{messages:[],metadata:{}},b=g(u);b.metadata&&(a=ar(b.metadata)),(T=b.messages)!=null&&T.length&&(t={...t,initialMessages:b.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(t.onStateLoaded)try{let l=g({messages:[],metadata:{}});(se=l.messages)!=null&&se.length&&(t={...t,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let w=()=>a,c=l=>{var b;a=(b=l({...a}))!=null?b:{},Dn()},h=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Ms],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Pn.message,Pn.messageAndClick],x=Ls({parsers:h,handlers:f,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null});x.syncFromMetadata();let C=(Ye=(Ee=t.launcher)==null?void 0:Ee.enabled)!=null?Ye:!0,E=(tt=(Lt=t.launcher)==null?void 0:Lt.autoExpand)!=null?tt:!1,S=E,k=C,V=(gt=(Ct=t.layout)==null?void 0:Ct.header)==null?void 0:gt.layout,y=C?E:!0,O=!1,W=null,H=()=>{O=!0,W&&clearTimeout(W),W=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},oe=ji(t,x,H),_=(qe=(De=t.features)==null?void 0:De.showReasoning)!=null?qe:!0,le=(ze=(lt=t.features)==null?void 0:lt.showToolCalls)!=null?ze:!0,X=(Rt=(xt=t.features)==null?void 0:xt.showEventStreamToggle)!=null?Rt:!1,Se=`${(ur=typeof t.persistState=="object"?(_t=t.persistState)==null?void 0:_t.keyPrefix:void 0)!=null?ur:"persona-"}event-stream`,N=X?new ss(Se):null,re=(mr=(gr=(pr=t.features)==null?void 0:pr.eventStream)==null?void 0:gr.maxEvents)!=null?mr:2e3,D=X?new ns(re,N):null,Z=null,ve=!1,pe=null,Ue=0;N==null||N.open().then(()=>D==null?void 0:D.restore()).catch(l=>{t.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let it={onCopy:l=>{var u,b;s.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(L=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",L)}),(b=(u=t.messageActions)==null?void 0:u.onCopy)==null||b.call(u,l)},onFeedback:l=>{var u,b;s.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(L=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",L)}),(b=(u=t.messageActions)==null?void 0:u.onFeedback)==null||b.call(u,l)}},Tt=(hr=t.statusIndicator)!=null?hr:{},$t=l=>{var u,b,L,A;return l==="idle"?(u=Tt.idleText)!=null?u:Pt.idle:l==="connecting"?(b=Tt.connectingText)!=null?b:Pt.connecting:l==="connected"?(L=Tt.connectedText)!=null?L:Pt.connected:l==="error"?(A=Tt.errorText)!=null?A:Pt.error:Pt[l]},{wrapper:Fe,panel:Ae}=Ti(t),ee=Mi(t,C),{container:ge,body:$e,messagesWrapper:Qe,suggestions:At,textarea:me,sendButton:J,sendButtonWrapper:ct,composerForm:ut,statusText:ft,introTitle:Ot,introSubtitle:wt,closeButton:Y,iconHolder:Ie,headerTitle:vt,headerSubtitle:yt,header:Q,footer:Oe,actionsRow:bt,leftActions:Wt,rightActions:Mt}=ee,j=ee.micButton,Ze=ee.micButtonWrapper,We=ee.attachmentButton,z=ee.attachmentButtonWrapper,R=ee.attachmentInput,he=ee.attachmentPreviewsContainer,ue=null;(fr=t.attachments)!=null&&fr.enabled&&R&&he&&(ue=Tn.fromConfig(t.attachments),ue.setPreviewsContainer(he),R.addEventListener("change",l=>{let u=l.target;ue==null||ue.handleFileSelect(u.files),u.value=""}));let te=o.find(l=>l.renderHeader);if(te!=null&&te.renderHeader){let l=te.renderHeader({config:t,defaultRenderer:()=>{let u=dn({config:t,showClose:C});return Mn(ge,u,t),u.header},onClose:()=>et(!1,"user")});if(l){let u=ge.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),Q=l)}}let Le=()=>{var u,b,L,A;if(!D)return;if(ve=!0,!Z&&D&&(Z=Bi({buffer:D,getFullHistory:()=>D.getAllFromStore(),onClose:()=>Ne(),config:t,plugins:o})),Z&&($e.style.display="none",(u=Oe.parentNode)==null||u.insertBefore(Z.element,Oe),Z.update()),q){q.classList.remove("tvw-text-cw-muted"),q.classList.add("tvw-text-cw-accent"),q.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let $=(A=(L=(b=t.features)==null?void 0:b.eventStream)==null?void 0:L.classNames)==null?void 0:A.toggleButtonActive;$&&$.split(/\s+/).forEach(ye=>ye&&q.classList.add(ye))}let l=()=>{if(!ve)return;let $=Date.now();$-Ue>=200&&(Z==null||Z.update(),Ue=$),pe=requestAnimationFrame(l)};Ue=0,pe=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},Ne=()=>{var l,u,b;if(ve){if(ve=!1,Z&&Z.element.remove(),$e.style.display="",q){q.classList.remove("tvw-text-cw-accent"),q.classList.add("tvw-text-cw-muted"),q.style.boxShadow="";let L=(b=(u=(l=t.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:b.toggleButtonActive;L&&L.split(/\s+/).forEach(A=>A&&q.classList.remove(A))}pe!==null&&(cancelAnimationFrame(pe),pe=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},q=null;if(X){let l=(vr=(wr=t.features)==null?void 0:wr.eventStream)==null?void 0:vr.classNames,u="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");q=p("button",u),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let b=ie("activity","18px","currentColor",1.5);b&&q.appendChild(b);let L=ee.clearChatButtonWrapper,A=ee.closeButtonWrapper,$=L||A;$&&$.parentNode===Q?Q.insertBefore(q,$):Q.appendChild(q),q.addEventListener("click",()=>{ve?Ne():Le()})}let de=o.find(l=>l.renderComposer);if(de!=null&&de.renderComposer){let l=de.renderComposer({config:t,defaultRenderer:()=>es({config:t}).footer,onSubmit:u=>{F&&!F.isStreaming()&&F.sendMessage(u)},disabled:!1});l&&(Oe.replaceWith(l),Oe=l)}(()=>{var L,A;let l=(A=(L=t.layout)==null?void 0:L.slots)!=null?A:{},u=$=>{switch($){case"body-top":return ge.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Qe;case"footer-top":return At;case"composer":return ut;case"footer-bottom":return ft;default:return null}},b=($,ye)=>{var ce;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Q.insertBefore(ye,Q.firstChild);else if($==="header-right")Q.appendChild(ye);else{let be=Q.querySelector(".tvw-flex-col");be?(ce=be.parentNode)==null||ce.insertBefore(ye,be.nextSibling):Q.appendChild(ye)}break;case"body-top":{let be=$e.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");be?be.replaceWith(ye):$e.insertBefore(ye,$e.firstChild);break}case"body-bottom":$e.appendChild(ye);break;case"footer-top":At.replaceWith(ye);break;case"footer-bottom":ft.replaceWith(ye);break;default:break}};for(let[$,ye]of Object.entries(l))if(ye)try{let ce=ye({config:t,defaultContent:()=>u($)});ce&&b($,ce)}catch(ce){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,ce)}})();let Je=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let L=b.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!L)return;let A=L.getAttribute("data-message-id");if(!A)return;let $=b.getAttribute("data-bubble-type");$==="reasoning"?(kn.has(A)?kn.delete(A):kn.add(A),Ii(A,L)):$==="tool"&&(Wn.has(A)?Wn.delete(A):Wn.add(A),Pi(A,L,t))};Qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),Qe.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))});let st=new Map;Qe.addEventListener("click",l=>{var ye;let b=l.target.closest(".tvw-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let L=b.closest("[data-actions-for]");if(!L)return;let A=L.getAttribute("data-actions-for");if(!A)return;let $=b.getAttribute("data-action");if($==="copy"){let be=F.getMessages().find(Te=>Te.id===A);if(be&&it.onCopy){let Te=be.content||"";navigator.clipboard.writeText(Te).then(()=>{b.classList.add("tvw-message-action-success");let Ce=ie("check",14,"currentColor",2);Ce&&(b.innerHTML="",b.appendChild(Ce)),setTimeout(()=>{b.classList.remove("tvw-message-action-success");let Pe=ie("copy",14,"currentColor",2);Pe&&(b.innerHTML="",b.appendChild(Pe))},2e3)}).catch(Ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ce)}),it.onCopy(be)}}else if($==="upvote"||$==="downvote")if(((ye=st.get(A))!=null?ye:null)===$)st.delete(A),b.classList.remove("tvw-message-action-active");else{let Te=$==="upvote"?"downvote":"upvote",Ce=L.querySelector(`[data-action="${Te}"]`);Ce&&Ce.classList.remove("tvw-message-action-active"),st.set(A,$),b.classList.add("tvw-message-action-active");let G=F.getMessages().find(I=>I.id===A);G&&it.onFeedback&&it.onFeedback({type:$,messageId:G.id,message:G})}}),Ae.appendChild(ge),e.appendChild(Fe);let vn=()=>{var we,xe,Ve,He,mt,It,K,je,Vt,zt,an,fs,Rs,dt,ws,Un;let l=(xe=(we=t.launcher)==null?void 0:we.sidebarMode)!=null?xe:!1,u=l||((He=(Ve=t.launcher)==null?void 0:Ve.fullHeight)!=null?He:!1),b=(mt=t.theme)!=null?mt:{},L=(K=(It=t.launcher)==null?void 0:It.position)!=null?K:"bottom-left",A=L==="bottom-left"||L==="top-left",$=l?"none":"1px solid var(--tvw-cw-border)",ye=l?A?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",ce=l?"0":"16px",be=(je=b.panelBorder)!=null?je:$,Te=(Vt=b.panelShadow)!=null?Vt:ye,Ce=(zt=b.panelBorderRadius)!=null?zt:ce;e.style.cssText="",Fe.style.cssText="",Ae.style.cssText="",ge.style.cssText="",$e.style.cssText="",Oe.style.cssText="";let Pe=(fs=(an=t==null?void 0:t.launcher)==null?void 0:an.width)!=null?fs:t==null?void 0:t.launcherWidth,G=Pe!=null?Pe:"min(400px, calc(100vw - 24px))";l||(Ae.style.width=G,Ae.style.maxWidth=G),Ae.style.boxShadow=Te,Ae.style.borderRadius=Ce,ge.style.border=be,ge.style.borderRadius=Ce;let I=((Rs=t.launcher)==null?void 0:Rs.enabled)===!1;if(u&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",Fe.style.display="flex",Fe.style.flexDirection="column",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.maxHeight="100%",Fe.style.height="100%",I&&(Fe.style.overflow="hidden"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",Ae.style.overflow="hidden",ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.overflow="hidden",$e.style.flex="1 1 0%",$e.style.minHeight="0",$e.style.overflowY="auto",Oe.style.flexShrink="0"),Fe.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!I&&((dt=Ut[L])!=null?dt:Ut["bottom-right"]).split(" ").forEach(fn=>Fe.classList.add(fn)),l){let hn=(Un=(ws=t.launcher)==null?void 0:ws.sidebarWidth)!=null?Un:"420px";Fe.style.cssText=`
|
|
20
|
+
`,H.addEventListener("click",()=>{u=W,x.forEach((oe,U)=>{let re=U<W;oe.classList.toggle("selected",re),oe.setAttribute("aria-checked",U===W-1?"true":"false")})}),x.push(H),E.appendChild(H)}m.appendChild(E);let k=null;if(d){let W=document.createElement("div");W.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),W.appendChild(k),m.appendChild(W)}let K=document.createElement("div");K.className="tvw-feedback-actions";let y=document.createElement("button");y.type="button",y.className="tvw-feedback-btn tvw-feedback-btn-skip",y.textContent=a,y.addEventListener("click",()=>{r==null||r(),v.remove()});let R=document.createElement("button");return R.type="button",R.className="tvw-feedback-btn tvw-feedback-btn-submit",R.textContent=i,R.addEventListener("click",async()=>{if(u===null){E.classList.add("tvw-feedback-shake"),setTimeout(()=>E.classList.remove("tvw-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let W=(k==null?void 0:k.value.trim())||void 0;await n(u,W),v.remove()}catch(W){R.disabled=!1,R.textContent=i,console.error("[CSAT Feedback] Failed to submit:",W)}}),K.appendChild(y),K.appendChild(R),m.appendChild(K),v.appendChild(m),v}function ar(e){let{onSubmit:n,onDismiss:r,title:t="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:v="Very likely"}=e,u=document.createElement("div");u.className="tvw-feedback-container tvw-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let m=null,h=document.createElement("div");h.className="tvw-feedback-content";let S=document.createElement("div");S.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=t,S.appendChild(C);let E=document.createElement("p");E.className="tvw-feedback-subtitle",E.textContent=o,S.appendChild(E),h.appendChild(S);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 K=document.createElement("span");K.className="tvw-feedback-label-low",K.textContent=c;let y=document.createElement("span");y.className="tvw-feedback-label-high",y.textContent=v,k.appendChild(K),k.appendChild(y);let R=document.createElement("div");R.className="tvw-feedback-numbers";let W=[];for(let J=0;J<=10;J++){let q=document.createElement("button");q.type="button",q.className="tvw-feedback-rating-btn tvw-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${J} out of 10`),q.textContent=String(J),q.dataset.rating=String(J),J<=6?q.classList.add("tvw-feedback-detractor"):J<=8?q.classList.add("tvw-feedback-passive"):q.classList.add("tvw-feedback-promoter"),q.addEventListener("click",()=>{m=J,W.forEach((pe,$)=>{pe.classList.toggle("selected",$===J),pe.setAttribute("aria-checked",$===J?"true":"false")})}),W.push(q),R.appendChild(q)}x.appendChild(k),x.appendChild(R),h.appendChild(x);let H=null;if(d){let J=document.createElement("div");J.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"),J.appendChild(H),h.appendChild(J)}let oe=document.createElement("div");oe.className="tvw-feedback-actions";let U=document.createElement("button");U.type="button",U.className="tvw-feedback-btn tvw-feedback-btn-skip",U.textContent=a,U.addEventListener("click",()=>{r==null||r(),u.remove()});let re=document.createElement("button");return re.type="button",re.className="tvw-feedback-btn tvw-feedback-btn-submit",re.textContent=i,re.addEventListener("click",async()=>{if(m===null){R.classList.add("tvw-feedback-shake"),setTimeout(()=>R.classList.remove("tvw-feedback-shake"),500);return}re.disabled=!0,re.textContent="Submitting...";try{let J=(H==null?void 0:H.value.trim())||void 0;await n(m,J),u.remove()}catch(J){re.disabled=!1,re.textContent=i,console.error("[NPS Feedback] Failed to submit:",J)}}),oe.appendChild(U),oe.appendChild(re),h.appendChild(oe),u.appendChild(h),u}var Hn="persona-chat-history",ol=30*1e3,il={"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 al(e){var t,o,s;if(!e)return[];let n=[],r=Array.from((t=e.items)!=null?t:[]);for(let i of r){if(i.kind!=="file"||!i.type.startsWith("image/"))continue;let a=i.getAsFile();if(!a)continue;if(a.name){n.push(a);continue}let d=(o=il[a.type])!=null?o:"png";n.push(new File([a],`clipboard-image-${Date.now()}.${d}`,{type:a.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let i of Array.from((s=e.files)!=null?s:[]))i.type.startsWith("image/")&&n.push(i);return n}function ll(e){var n,r,t,o,s,i,a,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(t=e.persist)==null?void 0:t.openState)!=null?o:!0,voiceState:(i=(s=e.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=e.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function dl(e){try{let n=e==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var lr=e=>!e||typeof e!="object"?{}:{...e},ji=e=>e.map(n=>({...n,streaming:!1})),qi=(e,n,r)=>{let t=e!=null&&e.markdown?bs(e.markdown):null;return o=>{var a,d,c;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(n){let v=n.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});v!==null&&(s=v.text,v.persist||(o.message.__skipPersist=!0),v.resubmit&&!o.streaming&&r&&r())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(c=i!=null?i:o.text)!=null?c:""}):t?t(s):$s(s)}},dr=(e,n,r)=>{var T,se,Me,Ve,Lt,st,Ct,gt,je,ze,dt,Ue,xt,Rt,jt,pr,gr,mr,fr,hr,wr,vr,yr,br,Cr,xr,Sr,Ar,Er,Tr,Mr,Lr;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let t=Qs(n),o=Ms.getForInstance(t.plugins);t.components&&os.registerAll(t.components);let s=Di(),i=(T=t.storageAdapter)!=null?T:er(),a={},d=null,c=l=>{if(t.onStateLoaded)try{return t.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")d=l.then(p=>{let b=p!=null?p:{messages:[],metadata:{}};return c(b)});else{let p=l!=null?l:{messages:[],metadata:{}},b=c(p);b.metadata&&(a=lr(b.metadata)),(se=b.messages)!=null&&se.length&&(t={...t,initialMessages:b.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(t.onStateLoaded)try{let l=c({messages:[],metadata:{}});(Me=l.messages)!=null&&Me.length&&(t={...t,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,u=l=>{var b;a=(b=l({...a}))!=null?b:{},Dn()},m=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Ls],h=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Pn.message,Pn.messageAndClick],S=ks({parsers:m,handlers:h,getSessionMetadata:v,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let C=(Lt=(Ve=t.launcher)==null?void 0:Ve.enabled)!=null?Lt:!0,E=(Ct=(st=t.launcher)==null?void 0:st.autoExpand)!=null?Ct:!1,x=E,k=C,K=(je=(gt=t.layout)==null?void 0:gt.header)==null?void 0:je.layout,y=C?E:!0,R=!1,W=null,H=()=>{R=!0,W&&clearTimeout(W),W=setTimeout(()=>{R&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),R=!1)},1e4)},oe=qi(t,S,H),U=(dt=(ze=t.features)==null?void 0:ze.showReasoning)!=null?dt:!0,re=(xt=(Ue=t.features)==null?void 0:Ue.showToolCalls)!=null?xt:!0,J=(jt=(Rt=t.features)==null?void 0:Rt.showEventStreamToggle)!=null?jt:!1,pe=`${(gr=typeof t.persistState=="object"?(pr=t.persistState)==null?void 0:pr.keyPrefix:void 0)!=null?gr:"persona-"}event-stream`,$=J?new rs(pe):null,Z=(hr=(fr=(mr=t.features)==null?void 0:mr.eventStream)==null?void 0:fr.maxEvents)!=null?hr:2e3,P=J?new ss(Z,$):null,ee=null,be=!1,ge=null,Je=0;$==null||$.open().then(()=>P==null?void 0:P.restore()).catch(l=>{t.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let lt={onCopy:l=>{var p,b;s.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(L=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",L)}),(b=(p=t.messageActions)==null?void 0:p.onCopy)==null||b.call(p,l)},onFeedback:l=>{var p,b;s.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(L=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",L)}),(b=(p=t.messageActions)==null?void 0:p.onFeedback)==null||b.call(p,l)}},Tt=(wr=t.statusIndicator)!=null?wr:{},$t=l=>{var p,b,L,A;return l==="idle"?(p=Tt.idleText)!=null?p:Pt.idle:l==="connecting"?(b=Tt.connectingText)!=null?b:Pt.connecting:l==="connected"?(L=Tt.connectedText)!=null?L:Pt.connected:l==="error"?(A=Tt.errorText)!=null?A:Pt.error:Pt[l]},{wrapper:Oe,panel:Ee}=Li(t),te=ki(t,C),{container:me,body:Ne,messagesWrapper:Qe,suggestions:At,textarea:ue,sendButton:Y,sendButtonWrapper:ut,composerForm:pt,statusText:ht,introTitle:Ot,introSubtitle:wt,closeButton:X,iconHolder:He,headerTitle:vt,headerSubtitle:yt,header:Q,footer:De,actionsRow:bt,leftActions:Wt,rightActions:Mt}=te,_=te.micButton,Ze=te.micButtonWrapper,Pe=te.attachmentButton,z=te.attachmentButtonWrapper,B=te.attachmentInput,fe=te.attachmentPreviewsContainer,ce=null;(vr=t.attachments)!=null&&vr.enabled&&B&&fe&&(ce=Tn.fromConfig(t.attachments),ce.setPreviewsContainer(fe),B.addEventListener("change",l=>{let p=l.target;ce==null||ce.handleFileSelect(p.files),p.value=""}));let ne=o.find(l=>l.renderHeader);if(ne!=null&&ne.renderHeader){let l=ne.renderHeader({config:t,defaultRenderer:()=>{let p=dn({config:t,showClose:C});return Mn(me,p,t),p.header},onClose:()=>et(!1,"user")});if(l){let p=me.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(l),Q=l)}}let We=()=>{var p,b,L,A;if(!P)return;if(be=!0,!ee&&P&&(ee=Fi({buffer:P,getFullHistory:()=>P.getAllFromStore(),onClose:()=>_e(),config:t,plugins:o})),ee&&(Ne.style.display="none",(p=De.parentNode)==null||p.insertBefore(ee.element,De),ee.update()),j){j.classList.remove("tvw-text-cw-muted"),j.classList.add("tvw-text-cw-accent"),j.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let N=(A=(L=(b=t.features)==null?void 0:b.eventStream)==null?void 0:L.classNames)==null?void 0:A.toggleButtonActive;N&&N.split(/\s+/).forEach(Ce=>Ce&&j.classList.add(Ce))}let l=()=>{if(!be)return;let N=Date.now();N-Je>=200&&(ee==null||ee.update(),Je=N),ge=requestAnimationFrame(l)};Je=0,ge=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},_e=()=>{var l,p,b;if(be){if(be=!1,ee&&ee.element.remove(),Ne.style.display="",j){j.classList.remove("tvw-text-cw-accent"),j.classList.add("tvw-text-cw-muted"),j.style.boxShadow="";let L=(b=(p=(l=t.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:b.toggleButtonActive;L&&L.split(/\s+/).forEach(A=>A&&j.classList.remove(A))}ge!==null&&(cancelAnimationFrame(ge),ge=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},j=null;if(J){let l=(br=(yr=t.features)==null?void 0:yr.eventStream)==null?void 0:br.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:"");j=g("button",p),j.style.width="28px",j.style.height="28px",j.type="button",j.setAttribute("aria-label","Event Stream"),j.title="Event Stream";let b=ie("activity","18px","currentColor",1.5);b&&j.appendChild(b);let L=te.clearChatButtonWrapper,A=te.closeButtonWrapper,N=L||A;N&&N.parentNode===Q?Q.insertBefore(j,N):Q.appendChild(j),j.addEventListener("click",()=>{be?_e():We()})}let le=o.find(l=>l.renderComposer);if(le!=null&&le.renderComposer){let l=le.renderComposer({config:t,defaultRenderer:()=>ts({config:t}).footer,onSubmit:p=>{F&&!F.isStreaming()&&F.sendMessage(p)},disabled:!1});l&&(De.replaceWith(l),De=l)}(()=>{var L,A;let l=(A=(L=t.layout)==null?void 0:L.slots)!=null?A:{},p=N=>{switch(N){case"body-top":return me.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Qe;case"footer-top":return At;case"composer":return pt;case"footer-bottom":return ht;default:return null}},b=(N,Ce)=>{var de;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Q.insertBefore(Ce,Q.firstChild);else if(N==="header-right")Q.appendChild(Ce);else{let xe=Q.querySelector(".tvw-flex-col");xe?(de=xe.parentNode)==null||de.insertBefore(Ce,xe.nextSibling):Q.appendChild(Ce)}break;case"body-top":{let xe=Ne.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");xe?xe.replaceWith(Ce):Ne.insertBefore(Ce,Ne.firstChild);break}case"body-bottom":Ne.appendChild(Ce);break;case"footer-top":At.replaceWith(Ce);break;case"footer-bottom":ht.replaceWith(Ce);break;default:break}};for(let[N,Ce]of Object.entries(l))if(Ce)try{let de=Ce({config:t,defaultContent:()=>p(N)});de&&b(N,de)}catch(de){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,de)}})();let Ke=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let L=b.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!L)return;let A=L.getAttribute("data-message-id");if(!A)return;let N=b.getAttribute("data-bubble-type");N==="reasoning"?(kn.has(A)?kn.delete(A):kn.add(A),Hi(A,L)):N==="tool"&&(Wn.has(A)?Wn.delete(A):Wn.add(A),Bi(A,L,t))};Qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ke(l))}),Qe.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ke(l))});let ot=new Map;Qe.addEventListener("click",l=>{var Ce;let b=l.target.closest(".tvw-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let L=b.closest("[data-actions-for]");if(!L)return;let A=L.getAttribute("data-actions-for");if(!A)return;let N=b.getAttribute("data-action");if(N==="copy"){let xe=F.getMessages().find(Le=>Le.id===A);if(xe&<.onCopy){let Le=xe.content||"";navigator.clipboard.writeText(Le).then(()=>{b.classList.add("tvw-message-action-success");let Se=ie("check",14,"currentColor",2);Se&&(b.innerHTML="",b.appendChild(Se)),setTimeout(()=>{b.classList.remove("tvw-message-action-success");let Be=ie("copy",14,"currentColor",2);Be&&(b.innerHTML="",b.appendChild(Be))},2e3)}).catch(Se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Se)}),lt.onCopy(xe)}}else if(N==="upvote"||N==="downvote")if(((Ce=ot.get(A))!=null?Ce:null)===N)ot.delete(A),b.classList.remove("tvw-message-action-active");else{let Le=N==="upvote"?"downvote":"upvote",Se=L.querySelector(`[data-action="${Le}"]`);Se&&Se.classList.remove("tvw-message-action-active"),ot.set(A,N),b.classList.add("tvw-message-action-active");let G=F.getMessages().find(I=>I.id===A);G&<.onFeedback&<.onFeedback({type:N,messageId:G.id,message:G})}}),Ee.appendChild(me),e.appendChild(Oe);let vn=()=>{var ye,Ae,Xe,Re,mt,It,V,qe,Vt,zt,an,hs,Fs,ct,ws,Jn;let l=(Ae=(ye=t.launcher)==null?void 0:ye.sidebarMode)!=null?Ae:!1,p=l||((Re=(Xe=t.launcher)==null?void 0:Xe.fullHeight)!=null?Re:!1),b=(mt=t.theme)!=null?mt:{},L=(V=(It=t.launcher)==null?void 0:It.position)!=null?V:"bottom-left",A=L==="bottom-left"||L==="top-left",N=l?"none":"1px solid var(--tvw-cw-border)",Ce=l?A?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",de=l?"0":"16px",xe=(qe=b.panelBorder)!=null?qe:N,Le=(Vt=b.panelShadow)!=null?Vt:Ce,Se=(zt=b.panelBorderRadius)!=null?zt:de;e.style.cssText="",Oe.style.cssText="",Ee.style.cssText="",me.style.cssText="",Ne.style.cssText="",De.style.cssText="";let Be=(hs=(an=t==null?void 0:t.launcher)==null?void 0:an.width)!=null?hs:t==null?void 0:t.launcherWidth,G=Be!=null?Be:"min(400px, calc(100vw - 24px))";l||(Ee.style.width=G,Ee.style.maxWidth=G),Ee.style.boxShadow=Le,Ee.style.borderRadius=Se,me.style.border=xe,me.style.borderRadius=Se;let I=((Fs=t.launcher)==null?void 0:Fs.enabled)===!1;if(p&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",I&&(Oe.style.overflow="hidden"),Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.height="100%",Ee.style.overflow="hidden",me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.overflow="hidden",Ne.style.flex="1 1 0%",Ne.style.minHeight="0",Ne.style.overflowY="auto",De.style.flexShrink="0"),Oe.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!I&&((ct=Ut[L])!=null?ct:Ut["bottom-right"]).split(" ").forEach(hn=>Oe.classList.add(hn)),l){let fn=(Jn=(ws=t.launcher)==null?void 0:ws.sidebarWidth)!=null?Jn:"420px";Oe.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
top: 0 !important;
|
|
23
23
|
bottom: 0 !important;
|
|
24
|
-
width: ${
|
|
24
|
+
width: ${fn} !important;
|
|
25
25
|
height: 100vh !important;
|
|
26
26
|
max-height: 100vh !important;
|
|
27
27
|
margin: 0 !important;
|
|
@@ -29,7 +29,7 @@ import{Marked as Qi}from"marked";var Zi=e=>{if(e)return e},ys=e=>{var o,s;let n=
|
|
|
29
29
|
display: flex !important;
|
|
30
30
|
flex-direction: column !important;
|
|
31
31
|
${A?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
32
|
-
`,
|
|
32
|
+
`,Ee.style.cssText=`
|
|
33
33
|
position: relative !important;
|
|
34
34
|
display: flex !important;
|
|
35
35
|
flex-direction: column !important;
|
|
@@ -40,9 +40,9 @@ import{Marked as Qi}from"marked";var Zi=e=>{if(e)return e},ys=e=>{var o,s;let n=
|
|
|
40
40
|
min-height: 0 !important;
|
|
41
41
|
margin: 0 !important;
|
|
42
42
|
padding: 0 !important;
|
|
43
|
-
box-shadow: ${
|
|
44
|
-
border-radius: ${
|
|
45
|
-
`,
|
|
43
|
+
box-shadow: ${Le} !important;
|
|
44
|
+
border-radius: ${Se} !important;
|
|
45
|
+
`,Ee.style.setProperty("width","100%","important"),Ee.style.setProperty("max-width","100%","important"),me.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 Qi}from"marked";var Zi=e=>{if(e)return e},ys=e=>{var o,s;let n=
|
|
|
51
51
|
min-height: 0 !important;
|
|
52
52
|
max-height: 100% !important;
|
|
53
53
|
overflow: hidden !important;
|
|
54
|
-
border-radius: ${
|
|
55
|
-
border: ${
|
|
56
|
-
`,
|
|
54
|
+
border-radius: ${Se} !important;
|
|
55
|
+
border: ${xe} !important;
|
|
56
|
+
`,De.style.cssText=`
|
|
57
57
|
flex-shrink: 0 !important;
|
|
58
58
|
border-top: none !important;
|
|
59
59
|
padding: 8px 16px 12px 16px !important;
|
|
60
|
-
`}if(!I){let hn="max-height: -moz-available !important; max-height: stretch !important;",fn=l?"":"padding-top: 1.25em !important;";Fe.style.cssText+=hn+fn}};vn(),Es(e,t);let rt=[];X&&rt.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),Z==null||Z.destroy(),Z=null,D==null||D.destroy(),D=null,N=null});let Jt=null,Rn=()=>{Jt&&(Jt(),Jt=null),t.colorScheme==="auto"&&(Jt=bi(()=>{Es(e,t)}))};Rn(),rt.push(()=>{Jt&&(Jt(),Jt=null)});let rn=Hi(At),Kt=null,F,on=!1,Gt=!0,cn=0,Fn=0,Qt=null,Zt=!1,yn=0,bn=!1,os=125,is=2e3,as=5,$n=50,Cn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},On=(br=(yr=t.voiceRecognition)==null?void 0:yr.autoResume)!=null?br:!1,Nn=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},en=()=>{c(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},ls=()=>{var L,A;if(((L=t.voiceRecognition)==null?void 0:L.enabled)===!1)return;let l=ar(a.voiceState),u=!!l.active,b=Number((A=l.timestamp)!=null?A:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-b<Za&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,mn("restore"))},1e3)},ds=()=>F?Di(F.getMessages()).filter(l=>!l.__skipPersist):[];function Dn(l){if(!(i!=null&&i.save))return;let b={messages:l?Di(l):F?ds():[],metadata:a};try{let L=i.save(b);L instanceof Promise&&L.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(L){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)}}let un=(l=!1)=>{if(!Gt)return;let u=Date.now();Zt&&u<yn&&!l||(Zt&&u>=yn&&(Zt=!1),!(!l&&!on)&&(u-Fn<os||(Fn=u,Qt&&cancelAnimationFrame(Qt),Qt=requestAnimationFrame(()=>{Zt||!Gt||(bn=!0,$e.scrollTop=$e.scrollHeight,cn=$e.scrollTop,requestAnimationFrame(()=>{bn=!1}),Qt=null)}))))},tn=null,cs=()=>Fe.querySelector("#persona-scroll-container")||$e,us=(l,u=500)=>{let b=l.scrollTop,L=l.clientHeight,A=l.scrollHeight,$=A-b;if(b+L>=A-2||Math.abs($)<5)return;tn!==null&&(cancelAnimationFrame(tn),tn=null);let ce=performance.now(),be=Ce=>1-Math.pow(1-Ce,3),Te=Ce=>{let Pe=l.scrollHeight;Pe!==A&&(A=Pe,$=A-b);let G=Ce-ce,I=Math.min(G/u,1),we=be(I),xe=b+$*we;l.scrollTop=xe,I<1?tn=requestAnimationFrame(Te):(l.scrollTop=l.scrollHeight,tn=null)};tn=requestAnimationFrame(Te)},ps=l=>{let u=new Map;l.forEach(b=>{let L=Cn.get(b.id);u.set(b.id,{streaming:b.streaming,role:b.role}),!L&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(L!=null&&L.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b)}),Cn.clear(),u.forEach((b,L)=>{Cn.set(L,b)})},pn=(l,u,b)=>{var Te,Ce,Pe,G;let L=document.createElement("div"),$=(()=>{var we;let I=o.find(xe=>xe.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((we=t.loadingIndicator)!=null&&we.render)return t.loadingIndicator.render})();u.forEach(I=>{var mt,It;let we=null,xe=o.find(K=>!!(I.variant==="reasoning"&&K.renderReasoning||I.variant==="tool"&&K.renderToolCall||!I.variant&&K.renderMessage)),Ve=(mt=t.layout)==null?void 0:mt.messages;if(xe)if(I.variant==="reasoning"&&I.reasoning&&xe.renderReasoning){if(!_)return;we=xe.renderReasoning({message:I,defaultRenderer:()=>Js(I),config:t})}else if(I.variant==="tool"&&I.toolCall&&xe.renderToolCall){if(!le)return;we=xe.renderToolCall({message:I,defaultRenderer:()=>Ks(I,t),config:t})}else xe.renderMessage&&(we=xe.renderMessage({message:I,defaultRenderer:()=>{let K=ts(I,b,Ve,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t});return I.role!=="user"&&Vs(K,I,t,F),K},config:t}));if(!we&&I.role==="assistant"&&!I.variant&&t.enableComponentStreaming!==!1&&sr(I)){let je=rr(I);if(je){let Vt=nr(je,{config:t,message:I,transform:b});if(Vt){let zt=document.createElement("div");if(zt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),zt.id=`bubble-${I.id}`,zt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let an=document.createElement("div");an.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",an.innerHTML=b({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),zt.appendChild(an)}zt.appendChild(Vt),we=zt}}}if(!we)if(I.variant==="reasoning"&&I.reasoning){if(!_)return;we=Js(I)}else if(I.variant==="tool"&&I.toolCall){if(!le)return;we=Ks(I,t)}else{let K=(It=t.layout)==null?void 0:It.messages;K!=null&&K.renderUserMessage&&I.role==="user"?we=K.renderUserMessage({message:I,config:t,streaming:!!I.streaming}):K!=null&&K.renderAssistantMessage&&I.role==="assistant"?we=K.renderAssistantMessage({message:I,config:t,streaming:!!I.streaming}):we=ts(I,b,K,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t}),I.role!=="user"&&we&&Vs(we,I,t,F)}let He=document.createElement("div");He.className="tvw-flex",He.id=`wrapper-${I.id}`,He.setAttribute("data-wrapper-id",I.id),I.role==="user"&&He.classList.add("tvw-justify-end"),He.appendChild(we),L.appendChild(He)});let ye=u.some(I=>I.role==="assistant"&&I.streaming),ce=u[u.length-1],be=(ce==null?void 0:ce.role)==="assistant"&&!ce.streaming;if(on&&u.some(I=>I.role==="user")&&!ye&&!be){let I={config:t,streaming:!0,location:"standalone",defaultRenderer:Ln},we=o.find(Ve=>Ve.renderLoadingIndicator),xe=null;if(we!=null&&we.renderLoadingIndicator&&(xe=we.renderLoadingIndicator(I)),xe===null&&((Te=t.loadingIndicator)!=null&&Te.render)&&(xe=t.loadingIndicator.render(I)),xe===null&&(xe=Ln()),xe){let Ve=document.createElement("div"),He=((Ce=t.loadingIndicator)==null?void 0:Ce.showBubble)!==!1;Ve.className=He?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(xe);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Ve),L.appendChild(mt)}}if(!on&&u.length>0){let I=u[u.length-1],we={config:t,lastMessage:I,messageCount:u.length},xe=o.find(He=>He.renderIdleIndicator),Ve=null;if(xe!=null&&xe.renderIdleIndicator&&(Ve=xe.renderIdleIndicator(we)),Ve===null&&((Pe=t.loadingIndicator)!=null&&Pe.renderIdle)&&(Ve=t.loadingIndicator.renderIdle(we)),Ve){let He=document.createElement("div"),mt=((G=t.loadingIndicator)==null?void 0:G.showBubble)!==!1;He.className=mt?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(Ve);let It=document.createElement("div");It.className="tvw-flex",It.id="wrapper-idle-indicator",It.setAttribute("data-wrapper-id","idle-indicator"),It.appendChild(He),L.appendChild(It)}}Ci(l,L),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=cs();us(I)})})},gn=()=>{C&&(y?(Fe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-95","tvw-opacity-0"),Ae.classList.add("tvw-scale-100","tvw-opacity-100"),ne?ne.element.style.display="none":ae&&(ae.style.display="none")):(Fe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-100","tvw-opacity-100"),Ae.classList.add("tvw-scale-95","tvw-opacity-0"),ne?ne.element.style.display="":ae&&(ae.style.display="")))},et=(l,u="user")=>{if(!C||y===l)return;let b=y;y=l,gn(),y&&(Xe(),un(!0));let L={open:y,source:u,timestamp:Date.now()};y&&!b?s.emit("widget:opened",L):!y&&b&&s.emit("widget:closed",L),s.emit("widget:state",{open:y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()})},xn=l=>{J.disabled=l,j&&(j.disabled=l),rn.buttons.forEach(u=>{u.disabled=l})},jn=()=>{var A,$,ye,ce,be,Te,Ce,Pe,G,I,we,xe,Ve,He;Ot.textContent=($=(A=t.copy)==null?void 0:A.welcomeTitle)!=null?$:"Hello \u{1F44B}",wt.textContent=(ce=(ye=t.copy)==null?void 0:ye.welcomeSubtitle)!=null?ce:"Ask anything about your account or products.",me.placeholder=(Te=(be=t.copy)==null?void 0:be.inputPlaceholder)!=null?Te:"How can I help...",((Pe=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?Pe:!1)||(J.textContent=(I=(G=t.copy)==null?void 0:G.sendButtonLabel)!=null?I:"Send");let u=(xe=(we=t.theme)==null?void 0:we.inputFontFamily)!=null?xe:"sans-serif",b=(He=(Ve=t.theme)==null?void 0:Ve.inputFontWeight)!=null?He:"400",L=mt=>{switch(mt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};me.style.fontFamily=L(u),me.style.fontWeight=b};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{c(u=>({...u,sessionId:l}))}}),F=new Gn(t,{onMessagesChanged(l){pn(Qe,l,oe),F&&(l.some(A=>A.role==="user")?rn.render([],F,me,l):rn.render(t.suggestionChips,F,me,l,t.suggestionChipsConfig)),un(!on),ps(l);let u=[...l].reverse().find(L=>L.role==="user"),b=Ke.lastUserMessageId;u&&u.id!==b&&(Ke.lastUserMessageId=u.id,s.emit("user:message",u)),Ke.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Dn(l)},onStatusChanged(l){var L;let u=(L=t.statusIndicator)!=null?L:{},b=A=>{var $,ye,ce,be;return A==="idle"?($=u.idleText)!=null?$:Pt.idle:A==="connecting"?(ye=u.connectingText)!=null?ye:Pt.connecting:A==="connected"?(ce=u.connectedText)!=null?ce:Pt.connected:A==="error"?(be=u.errorText)!=null?be:Pt.error:Pt[A]};ft.textContent=b(l)},onStreamingChanged(l){on=l,xn(l),F&&pn(Qe,F.getMessages(),oe),l||un(!0)}}),t.clientToken&&F.initClientSession().catch(l=>{t.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&F.setSSEEventCallback((l,u)=>{D==null||D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(a=ar(l.metadata),x.syncFromMetadata()),(u=l.messages)!=null&&u.length&&F.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let _n=l=>{var A;l.preventDefault();let u=me.value.trim(),b=(A=ue==null?void 0:ue.hasAttachments())!=null?A:!1;if(!u&&!b)return;let L;b&&(L=[],L.push(...ue.getContentParts()),u&&L.push(qs(u))),me.value="",me.style.height="auto",F.sendMessage(u,{contentParts:L}),b&&ue.clearAttachments()},qn=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},Ht=null,Nt=!1,nn=null,Yt=null,zn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,mn=(l="user")=>{var $,ye,ce,be;if(Nt||F.isStreaming())return;let u=zn();if(!u)return;Ht=new u;let L=(ye=(($=t.voiceRecognition)!=null?$:{}).pauseDuration)!=null?ye:2e3;Ht.continuous=!0,Ht.interimResults=!0,Ht.lang="en-US";let A=me.value;Ht.onresult=Te=>{let Ce="",Pe="";for(let I=0;I<Te.results.length;I++){let we=Te.results[I],xe=we[0].transcript;we.isFinal?Ce+=xe+" ":Pe=xe}let G=A+Ce+Pe;me.value=G,nn&&clearTimeout(nn),(Ce||Pe)&&(nn=window.setTimeout(()=>{let I=me.value.trim();I&&Ht&&Nt&&(qt(),me.value="",me.style.height="auto",F.sendMessage(I,{viaVoice:!0}))},L))},Ht.onerror=Te=>{Te.error!=="no-speech"&&qt()},Ht.onend=()=>{if(Nt){let Te=me.value.trim();Te&&Te!==A.trim()&&(me.value="",me.style.height="auto",F.sendMessage(Te,{viaVoice:!0})),qt()}};try{if(Ht.start(),Nt=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),Nn(l),en(),j){Yt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let Te=(ce=t.voiceRecognition)!=null?ce:{},Ce=(be=Te.recordingBackgroundColor)!=null?be:"#ef4444",Pe=Te.recordingIconColor,G=Te.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=Ce,Pe){j.style.color=Pe;let I=j.querySelector("svg");I&&I.setAttribute("stroke",Pe)}G&&(j.style.borderColor=G),j.setAttribute("aria-label","Stop voice recognition")}}catch{qt("system")}},qt=(l="user")=>{if(Nt){if(Nt=!1,nn&&(clearTimeout(nn),nn=null),Ht){try{Ht.stop()}catch{}Ht=null}if(Ke.active=!1,Nn(l),en(),j){if(j.classList.remove("tvw-voice-recording"),Yt){j.style.backgroundColor=Yt.backgroundColor,j.style.color=Yt.color,j.style.borderColor=Yt.borderColor;let u=j.querySelector("svg");u&&u.setAttribute("stroke",Yt.color||"currentColor"),Yt=null}j.setAttribute("aria-label","Start voice recognition")}}},gs=(l,u)=>{var xe,Ve,He,mt,It,K,je;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let L=p("div","tvw-send-button-wrapper"),A=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let $=(xe=l==null?void 0:l.iconName)!=null?xe:"mic",ye=(Ve=u==null?void 0:u.size)!=null?Ve:"40px",ce=(He=l==null?void 0:l.iconSize)!=null?He:ye,be=parseFloat(ce)||24,Te=(mt=l==null?void 0:l.backgroundColor)!=null?mt:u==null?void 0:u.backgroundColor,Ce=(It=l==null?void 0:l.iconColor)!=null?It:u==null?void 0:u.textColor;A.style.width=ce,A.style.height=ce,A.style.minWidth=ce,A.style.minHeight=ce,A.style.fontSize="18px",A.style.lineHeight="1";let Pe=Ce||"currentColor",G=ie($,be,Pe,1.5);G?(A.appendChild(G),A.style.color=Pe):(A.textContent="\u{1F3A4}",A.style.color=Pe),Te?A.style.backgroundColor=Te:A.classList.add("tvw-bg-cw-primary"),Ce?A.style.color=Ce:!Ce&&!(u!=null&&u.textColor)&&A.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(A.style.borderWidth=l.borderWidth,A.style.borderStyle="solid"),l!=null&&l.borderColor&&(A.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(A.style.paddingLeft=l.paddingX,A.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(A.style.paddingTop=l.paddingY,A.style.paddingBottom=l.paddingY),L.appendChild(A);let I=(K=l==null?void 0:l.tooltipText)!=null?K:"Start voice recognition";if(((je=l==null?void 0:l.showTooltip)!=null?je:!1)&&I){let Vt=p("div","tvw-send-button-tooltip");Vt.textContent=I,L.appendChild(Vt)}return{micButton:A,micButtonWrapper:L}},Sn=()=>{if(Nt){let l=me.value.trim();Ke.manuallyDeactivated=!0,en(),qt("user"),l&&(me.value="",me.style.height="auto",F.sendMessage(l))}else Ke.manuallyDeactivated=!1,en(),mn("user")};j&&(j.addEventListener("click",Sn),rt.push(()=>{qt("system"),j&&j.removeEventListener("click",Sn)}));let ms=s.on("assistant:complete",()=>{On&&(Ke.active||Ke.manuallyDeactivated||On==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&mn("auto")},600))});rt.push(ms);let hs=s.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});rt.push(hs);let B=()=>{et(!y,"user")},ne=null,ae=null;if(C){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:t,defaultRenderer:()=>Qn(t,B).element,onToggle:B});u&&(ae=u)}ae||(ne=Qn(t,B))}ne?e.appendChild(ne.element):ae&&e.appendChild(ae),gn(),rn.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),jn(),xn(F.isStreaming()),un(!0),ls();let Xe=()=>{var b,L,A,$,ye,ce,be,Te;let l=(L=(b=t.launcher)==null?void 0:b.sidebarMode)!=null?L:!1,u=l||(($=(A=t.launcher)==null?void 0:A.fullHeight)!=null?$:!1);if(!C){Ae.style.height="",Ae.style.width="";return}if(!l){let Ce=(ce=(ye=t==null?void 0:t.launcher)==null?void 0:ye.width)!=null?ce:t==null?void 0:t.launcherWidth,Pe=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";Ae.style.width=Pe,Ae.style.maxWidth=Pe}if(!u){let Ce=window.innerHeight,Pe=64,G=(Te=(be=t.launcher)==null?void 0:be.heightOffset)!=null?Te:0,I=Math.max(200,Ce-Pe),we=Math.min(640,I),xe=Math.max(200,we-G);Ae.style.height=`${xe}px`}};Xe(),window.addEventListener("resize",Xe),rt.push(()=>window.removeEventListener("resize",Xe)),cn=$e.scrollTop;let pt=()=>{let l=$e.scrollTop,u=$e.scrollHeight,b=$e.clientHeight,L=u-l-b,A=Math.abs(l-cn);if(cn=l,!bn&&!(A<=as)){if(!Gt&&L<$n){Zt=!1,Gt=!0;return}Gt&&L>$n&&(Zt=!0,yn=Date.now()+is,Gt=!1)}};$e.addEventListener("scroll",pt,{passive:!0}),rt.push(()=>$e.removeEventListener("scroll",pt)),rt.push(()=>{Qt&&cancelAnimationFrame(Qt)});let Et=()=>{Y&&(Kt&&(Y.removeEventListener("click",Kt),Kt=null),C?(Y.style.display="",Kt=()=>{y=!1,gn()},Y.addEventListener("click",Kt)):Y.style.display="none")};Et(),(()=>{let{clearChatButton:l}=ee;l&&l.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(Hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Hn}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",L)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()})})(),ut.addEventListener("submit",_n),me.addEventListener("keydown",qn),rt.push(()=>{ut.removeEventListener("submit",_n),me.removeEventListener("keydown",qn)}),rt.push(()=>{F.cancel()}),ne?rt.push(()=>{ne==null||ne.destroy()}):ae&&rt.push(()=>{ae==null||ae.remove()});let m={update(l){var Mr,Lr,kr,Wr,Ir,Pr,Hr,Br,Rr,Fr,$r,Or,Nr,Dr,jr,_r,qr,zr,Ur,Jr,Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,Lo,ko,Wo,Io,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,jo,_o,qo,zo,Uo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi;let u=t.toolCall,b=t.colorScheme;t={...t,...l},vn(),Es(e,t),t.colorScheme!==b&&Rn();let L=Ts.getForInstance(t.plugins);o.length=0,o.push(...L),C=(Lr=(Mr=t.launcher)==null?void 0:Mr.enabled)!=null?Lr:!0,E=(Wr=(kr=t.launcher)==null?void 0:kr.autoExpand)!=null?Wr:!1,_=(Pr=(Ir=t.features)==null?void 0:Ir.showReasoning)!=null?Pr:!0,le=(Br=(Hr=t.features)==null?void 0:Hr.showToolCalls)!=null?Br:!0;let A=X;if(X=(Fr=(Rr=t.features)==null?void 0:Rr.showEventStreamToggle)!=null?Fr:!1,X&&!A){if(D||(N=new ss(Se),D=new ns(re,N),N.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),F.setSSEEventCallback((M,Me)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:M,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!q&&Q){let M=(Or=($r=t.features)==null?void 0:$r.eventStream)==null?void 0:Or.classNames,Me="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(M!=null&&M.toggleButton?" "+M.toggleButton:"");q=p("button",Me),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let Ge=ie("activity","18px","currentColor",1.5);Ge&&q.appendChild(Ge);let fe=ee.clearChatButtonWrapper,Re=ee.closeButtonWrapper,ht=fe||Re;ht&&ht.parentNode===Q?Q.insertBefore(q,ht):Q.appendChild(q),q.addEventListener("click",()=>{ve?Ne():Le()})}}else!X&&A&&(Ne(),q&&(q.remove(),q=null),D==null||D.clear(),N==null||N.destroy(),D=null,N=null);if(((Nr=t.launcher)==null?void 0:Nr.enabled)===!1&&ne&&(ne.destroy(),ne=null),((Dr=t.launcher)==null?void 0:Dr.enabled)===!1&&ae&&(ae.remove(),ae=null),((jr=t.launcher)==null?void 0:jr.enabled)!==!1&&!ne&&!ae){let M=o.find(Me=>Me.renderLauncher);if(M!=null&&M.renderLauncher){let Me=M.renderLauncher({config:t,defaultRenderer:()=>Qn(t,B).element,onToggle:B});Me&&(ae=Me,e.appendChild(ae))}ae||(ne=Qn(t,B),e.appendChild(ne.element))}ne&&ne.update(t),vt&&((_r=t.launcher)==null?void 0:_r.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((qr=t.launcher)==null?void 0:qr.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let $=(zr=t.layout)==null?void 0:zr.header;if(($==null?void 0:$.layout)!==V&&Q){let M=$?Zn(t,$,{showClose:C,onClose:()=>et(!1,"user")}):dn({config:t,showClose:C,onClose:()=>et(!1,"user")});Q.replaceWith(M.header),Q=M.header,Ie=M.iconHolder,vt=M.headerTitle,yt=M.headerSubtitle,Y=M.closeButton,V=$==null?void 0:$.layout}else if($&&(Ie&&(Ie.style.display=$.showIcon===!1?"none":""),vt&&(vt.style.display=$.showTitle===!1?"none":""),yt&&(yt.style.display=$.showSubtitle===!1?"none":""),Y&&(Y.style.display=$.showCloseButton===!1?"none":""),ee.clearChatButtonWrapper)){let M=$.showClearChat;if(M!==void 0){ee.clearChatButtonWrapper.style.display=M?"":"none";let{closeButtonWrapper:Me}=ee;Me&&!Me.classList.contains("tvw-absolute")&&(M?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let ce=((Ur=t.layout)==null?void 0:Ur.showHeader)!==!1;Q&&(Q.style.display=ce?"":"none");let be=((Jr=t.layout)==null?void 0:Jr.showFooter)!==!1;Oe&&(Oe.style.display=be?"":"none"),C!==k?C?et(E,"auto"):(y=!0,gn()):E!==S&&et(E,"auto"),S=E,k=C,Xe(),Et(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&F&&pn(Qe,F.getMessages(),oe);let G=(Kr=t.launcher)!=null?Kr:{},I=(Yr=G.headerIconHidden)!=null?Yr:!1,we=(Xr=(Vr=t.layout)==null?void 0:Vr.header)==null?void 0:Xr.showIcon,xe=I||we===!1,Ve=G.headerIconName,He=(Gr=G.headerIconSize)!=null?Gr:"48px";if(Ie){let M=ge.querySelector(".tvw-border-b-cw-divider"),Me=M==null?void 0:M.querySelector(".tvw-flex-col");if(xe)Ie.style.display="none",M&&Me&&!M.contains(Me)&&M.insertBefore(Me,M.firstChild);else{if(Ie.style.display="",Ie.style.height=He,Ie.style.width=He,M&&Me&&(M.contains(Ie)?Ie.nextSibling!==Me&&(Ie.remove(),M.insertBefore(Ie,Me)):M.insertBefore(Ie,Me)),Ve){let fe=parseFloat(He)||24,Re=ie(Ve,fe*.6,"#ffffff",2);Re?Ie.replaceChildren(Re):Ie.textContent=(Qr=G.agentIconText)!=null?Qr:"\u{1F4AC}"}else if(G.iconUrl){let fe=Ie.querySelector("img");if(fe)fe.src=G.iconUrl,fe.style.height=He,fe.style.width=He;else{let Re=document.createElement("img");Re.src=G.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=He,Re.style.width=He,Ie.replaceChildren(Re)}}else{let fe=Ie.querySelector("svg"),Re=Ie.querySelector("img");(fe||Re)&&Ie.replaceChildren(),Ie.textContent=(Zr=G.agentIconText)!=null?Zr:"\u{1F4AC}"}let Ge=Ie.querySelector("img");Ge&&(Ge.style.height=He,Ge.style.width=He)}}let mt=(to=(eo=t.layout)==null?void 0:eo.header)==null?void 0:to.showTitle,It=(so=(no=t.layout)==null?void 0:no.header)==null?void 0:so.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=It===!1?"none":""),Y){((oo=(ro=t.layout)==null?void 0:ro.header)==null?void 0:oo.showCloseButton)===!1?Y.style.display="none":Y.style.display="";let Me=(io=G.closeButtonSize)!=null?io:"32px",Ge=(ao=G.closeButtonPlacement)!=null?ao:"inline";Y.style.height=Me,Y.style.width=Me;let{closeButtonWrapper:fe}=ee,Re=Ge==="top-right",ht=fe==null?void 0:fe.classList.contains("tvw-absolute");if(fe&&Re!==ht)if(fe.remove(),Re)fe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",ge.style.position="relative",ge.appendChild(fe);else{let ke=(co=(lo=G.clearChat)==null?void 0:lo.placement)!=null?co:"inline",St=(po=(uo=G.clearChat)==null?void 0:uo.enabled)!=null?po:!0;fe.className=St&&ke==="inline"?"":"tvw-ml-auto";let Ft=ge.querySelector(".tvw-border-b-cw-divider");Ft&&Ft.appendChild(fe)}if(G.closeButtonColor?(Y.style.color=G.closeButtonColor,Y.classList.remove("tvw-text-cw-muted")):(Y.style.color="",Y.classList.add("tvw-text-cw-muted")),G.closeButtonBackgroundColor?(Y.style.backgroundColor=G.closeButtonBackgroundColor,Y.classList.remove("hover:tvw-bg-gray-100")):(Y.style.backgroundColor="",Y.classList.add("hover:tvw-bg-gray-100")),G.closeButtonBorderWidth||G.closeButtonBorderColor){let ke=G.closeButtonBorderWidth||"0px",St=G.closeButtonBorderColor||"transparent";Y.style.border=`${ke} solid ${St}`,Y.classList.remove("tvw-border-none")}else Y.style.border="",Y.classList.add("tvw-border-none");G.closeButtonBorderRadius?(Y.style.borderRadius=G.closeButtonBorderRadius,Y.classList.remove("tvw-rounded-full")):(Y.style.borderRadius="",Y.classList.add("tvw-rounded-full")),G.closeButtonPaddingX?(Y.style.paddingLeft=G.closeButtonPaddingX,Y.style.paddingRight=G.closeButtonPaddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),G.closeButtonPaddingY?(Y.style.paddingTop=G.closeButtonPaddingY,Y.style.paddingBottom=G.closeButtonPaddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let kt=(go=G.closeButtonIconName)!=null?go:"x",Dt=(mo=G.closeButtonIconText)!=null?mo:"\xD7";Y.innerHTML="";let Bt=ie(kt,"20px",G.closeButtonColor||"",2);Bt?Y.appendChild(Bt):Y.textContent=Dt;let ot=(ho=G.closeButtonTooltipText)!=null?ho:"Close chat",jt=(fo=G.closeButtonShowTooltip)!=null?fo:!0;if(Y.setAttribute("aria-label",ot),fe&&(fe._cleanupTooltip&&(fe._cleanupTooltip(),delete fe._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!Y)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let Vn=p("div");Vn.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(Vn);let wn=Y.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${wn.left+wn.width/2}px`,ke.style.top=`${wn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};fe.addEventListener("mouseenter",St),fe.addEventListener("mouseleave",Ft),Y.addEventListener("focus",St),Y.addEventListener("blur",Ft),fe._cleanupTooltip=()=>{Ft(),fe&&(fe.removeEventListener("mouseenter",St),fe.removeEventListener("mouseleave",Ft)),Y&&(Y.removeEventListener("focus",St),Y.removeEventListener("blur",Ft))}}}let{clearChatButton:K,clearChatButtonWrapper:je}=ee;if(K){let M=(wo=G.clearChat)!=null?wo:{},Me=(vo=M.enabled)!=null?vo:!0,Ge=(bo=(yo=t.layout)==null?void 0:yo.header)==null?void 0:bo.showClearChat,fe=Ge!==void 0?Ge:Me,Re=(Co=M.placement)!=null?Co:"inline";if(je){je.style.display=fe?"":"none";let{closeButtonWrapper:ht}=ee;ht&&!ht.classList.contains("tvw-absolute")&&(fe?ht.classList.remove("tvw-ml-auto"):ht.classList.add("tvw-ml-auto"));let kt=Re==="top-right",Dt=je.classList.contains("tvw-absolute");if(kt!==Dt&&fe){if(je.remove(),kt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",ge.style.position="relative",ge.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ot=ge.querySelector(".tvw-border-b-cw-divider"),jt=ee.closeButtonWrapper;ot&&jt&&jt.parentElement===ot?ot.insertBefore(je,jt):ot&&ot.appendChild(je)}let Bt=ee.closeButtonWrapper;Bt&&!Bt.classList.contains("tvw-absolute")&&(kt?Bt.classList.add("tvw-ml-auto"):Bt.classList.remove("tvw-ml-auto"))}}if(fe){let ht=(xo=M.size)!=null?xo:"32px";K.style.height=ht,K.style.width=ht;let kt=(So=M.iconName)!=null?So:"refresh-cw",Dt=(Ao=M.iconColor)!=null?Ao:"";K.innerHTML="";let Bt=ie(kt,"20px",Dt||"",2);if(Bt&&K.appendChild(Bt),Dt?(K.style.color=Dt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),M.backgroundColor?(K.style.backgroundColor=M.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let ke=M.borderWidth||"0px",St=M.borderColor||"transparent";K.style.border=`${ke} solid ${St}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");M.borderRadius?(K.style.borderRadius=M.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),M.paddingX?(K.style.paddingLeft=M.paddingX,K.style.paddingRight=M.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),M.paddingY?(K.style.paddingTop=M.paddingY,K.style.paddingBottom=M.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let ot=(Eo=M.tooltipText)!=null?Eo:"Clear chat",jt=(To=M.showTooltip)!=null?To:!0;if(K.setAttribute("aria-label",ot),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!K)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let Vn=p("div");Vn.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(Vn);let wn=K.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${wn.left+wn.width/2}px`,ke.style.top=`${wn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};je.addEventListener("mouseenter",St),je.addEventListener("mouseleave",Ft),K.addEventListener("focus",St),K.addEventListener("blur",Ft),je._cleanupTooltip=()=>{Ft(),je&&(je.removeEventListener("mouseenter",St),je.removeEventListener("mouseleave",Ft)),K&&(K.removeEventListener("focus",St),K.removeEventListener("blur",Ft))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Ms],zt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Pn.message,Pn.messageAndClick];x=Ls({parsers:Vt,handlers:zt,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),oe=ji(t,x,H),F.updateConfig(t),pn(Qe,F.getMessages(),oe),rn.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),jn(),xn(F.isStreaming());let an=((Mo=t.voiceRecognition)==null?void 0:Mo.enabled)===!0,fs=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(an&&fs)if(!j||!Ze){let M=gs(t.voiceRecognition,t.sendButton);M&&(j=M.micButton,Ze=M.micButtonWrapper,Mt.insertBefore(Ze,ct),j.addEventListener("click",Sn),j.disabled=F.isStreaming())}else{let M=(Lo=t.voiceRecognition)!=null?Lo:{},Me=(ko=t.sendButton)!=null?ko:{},Ge=(Wo=M.iconName)!=null?Wo:"mic",fe=(Io=Me.size)!=null?Io:"40px",Re=(Po=M.iconSize)!=null?Po:fe,ht=parseFloat(Re)||24;j.style.width=Re,j.style.height=Re,j.style.minWidth=Re,j.style.minHeight=Re;let kt=(Bo=(Ho=M.iconColor)!=null?Ho:Me.textColor)!=null?Bo:"currentColor";j.innerHTML="";let Dt=ie(Ge,ht,kt,2);Dt?j.appendChild(Dt):j.textContent="\u{1F3A4}";let Bt=(Ro=M.backgroundColor)!=null?Ro:Me.backgroundColor;Bt?(j.style.backgroundColor=Bt,j.classList.remove("tvw-bg-cw-primary")):(j.style.backgroundColor="",j.classList.add("tvw-bg-cw-primary")),kt?(j.style.color=kt,j.classList.remove("tvw-text-white")):!kt&&!Me.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),M.borderWidth?(j.style.borderWidth=M.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),M.borderColor?j.style.borderColor=M.borderColor:j.style.borderColor="",M.paddingX?(j.style.paddingLeft=M.paddingX,j.style.paddingRight=M.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),M.paddingY?(j.style.paddingTop=M.paddingY,j.style.paddingBottom=M.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let ot=Ze==null?void 0:Ze.querySelector(".tvw-send-button-tooltip"),jt=(Fo=M.tooltipText)!=null?Fo:"Start voice recognition";if((($o=M.showTooltip)!=null?$o:!1)&&jt)if(ot)ot.textContent=jt,ot.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=jt,Ze==null||Ze.insertBefore(St,j)}else ot&&(ot.style.display="none");Ze.style.display="",j.disabled=F.isStreaming()}else j&&Ze&&(Ze.style.display="none",Nt&&qt());if(((Oo=t.attachments)==null?void 0:Oo.enabled)===!0)if(!z||!We){let M=(No=t.attachments)!=null?No:{},Ge=(jo=((Do=t.sendButton)!=null?Do:{}).size)!=null?jo:"40px";he||(he=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),he.style.display="none",ut.insertBefore(he,me)),R||(R=document.createElement("input"),R.type="file",R.accept=((_o=M.allowedTypes)!=null?_o:ln).join(","),R.multiple=((qo=M.maxFiles)!=null?qo:4)>1,R.style.display="none",R.setAttribute("aria-label","Attach files"),ut.insertBefore(R,me)),z=p("div","tvw-send-button-wrapper"),We=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),We.type="button",We.setAttribute("aria-label",(zo=M.buttonTooltipText)!=null?zo:"Attach file");let fe=(Uo=M.buttonIconName)!=null?Uo:"paperclip",Re=Ge,ht=parseFloat(Re)||40,kt=Math.round(ht*.6);We.style.width=Re,We.style.height=Re,We.style.minWidth=Re,We.style.minHeight=Re,We.style.fontSize="18px",We.style.lineHeight="1",We.style.backgroundColor="transparent",We.style.color="var(--cw-primary, #111827)",We.style.border="none",We.style.borderRadius="6px",We.style.transition="background-color 0.15s ease",We.addEventListener("mouseenter",()=>{We.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),We.addEventListener("mouseleave",()=>{We.style.backgroundColor="transparent"});let Dt=ie(fe,kt,"currentColor",1.5);Dt?We.appendChild(Dt):We.textContent="\u{1F4CE}",We.addEventListener("click",jt=>{jt.preventDefault(),R==null||R.click()}),z.appendChild(We);let Bt=(Jo=M.buttonTooltipText)!=null?Jo:"Attach file",ot=p("div","tvw-send-button-tooltip");ot.textContent=Bt,z.appendChild(ot),Wt.append(z),!ue&&R&&he&&(ue=Tn.fromConfig(M),ue.setPreviewsContainer(he),R.addEventListener("change",async()=>{ue&&(R!=null&&R.files)&&(await ue.handleFileSelect(R.files),R.value="")}))}else{z.style.display="";let M=(Ko=t.attachments)!=null?Ko:{};R&&(R.accept=((Yo=M.allowedTypes)!=null?Yo:ln).join(","),R.multiple=((Vo=M.maxFiles)!=null?Vo:4)>1),ue&&ue.updateConfig({allowedTypes:M.allowedTypes,maxFileSize:M.maxFileSize,maxFiles:M.maxFiles})}else z&&(z.style.display="none"),ue&&ue.clearAttachments();let dt=(Xo=t.sendButton)!=null?Xo:{},ws=(Go=dt.useIcon)!=null?Go:!1,Un=(Qo=dt.iconText)!=null?Qo:"\u2191",hn=dt.iconName,fn=(Zo=dt.tooltipText)!=null?Zo:"Send message",Xi=(ei=dt.showTooltip)!=null?ei:!1,Jn=(ti=dt.size)!=null?ti:"40px",vs=dt.backgroundColor,Xt=dt.textColor;if(ws){if(J.style.width=Jn,J.style.height=Jn,J.style.minWidth=Jn,J.style.minHeight=Jn,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",hn){let M=parseFloat(Jn)||24,Me=Xt&&typeof Xt=="string"&&Xt.trim()?Xt.trim():"currentColor",Ge=ie(hn,M,Me,2);Ge?(J.appendChild(Ge),J.style.color=Me):(J.textContent=Un,Xt?J.style.color=Xt:J.classList.add("tvw-text-white"))}else J.textContent=Un,Xt?J.style.color=Xt:J.classList.add("tvw-text-white");J.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",vs?(J.style.backgroundColor=vs,J.classList.remove("tvw-bg-cw-primary")):J.classList.add("tvw-bg-cw-primary")}else J.textContent=(si=(ni=t.copy)==null?void 0:ni.sendButtonLabel)!=null?si:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",vs?(J.style.backgroundColor=vs,J.classList.remove("tvw-bg-cw-accent")):J.classList.add("tvw-bg-cw-accent"),Xt?J.style.color=Xt:J.classList.add("tvw-text-white");dt.borderWidth?(J.style.borderWidth=dt.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),dt.borderColor?J.style.borderColor=dt.borderColor:J.style.borderColor="",dt.paddingX?(J.style.paddingLeft=dt.paddingX,J.style.paddingRight=dt.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),dt.paddingY?(J.style.paddingTop=dt.paddingY,J.style.paddingBottom=dt.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let Kn=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(Xi&&fn)if(Kn)Kn.textContent=fn,Kn.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=fn,ct==null||ct.insertBefore(M,J)}else Kn&&(Kn.style.display="none");let Yn=(ri=t.statusIndicator)!=null?ri:{},Gi=(oi=Yn.visible)!=null?oi:!0;if(ft.style.display=Gi?"":"none",F){let M=F.getStatus(),Me=Ge=>{var fe,Re,ht,kt;return Ge==="idle"?(fe=Yn.idleText)!=null?fe:Pt.idle:Ge==="connecting"?(Re=Yn.connectingText)!=null?Re:Pt.connecting:Ge==="connected"?(ht=Yn.connectedText)!=null?ht:Pt.connected:Ge==="error"?(kt=Yn.errorText)!=null?kt:Pt.error:Pt[Ge]};ft.textContent=Me(M)}},open(){C&&et(!0,"api")},close(){C&&et(!1,"api")},toggle(){C&&et(!y,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(Hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Hn}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()},setMessage(l){return!me||F.isStreaming()?!1:(!y&&C&&et(!0,"system"),me.value=l,me.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let u=(l==null?void 0:l.trim())||me.value.trim();return u?(!y&&C&&et(!0,"system"),me.value="",me.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){return Nt||F.isStreaming()||!zn()?!1:(!y&&C&&et(!0,"system"),Ke.manuallyDeactivated=!1,en(),mn("user"),!0)},stopVoiceRecognition(){return Nt?(Ke.manuallyDeactivated=!0,en(),qt("user"),!0):!1},injectMessage(l){return!y&&C&&et(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!y&&C&&et(!0,"system");let u=F.injectAssistantMessage(l);return O&&(O=!1,W&&(clearTimeout(W),W=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),u},injectUserMessage(l){return!y&&C&&et(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!y&&C&&et(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!y&&C&&et(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!y&&C&&et(!0,"system"),F.injectTestEvent(l)},__pushEventStreamEvent(l){D&&D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!X||!D||Le()},hideEventStream(){ve&&Ne()},isEventStreamVisible(){return ve},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){c(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return C&&y},isVoiceActive(){return Ke.active},getState(){return{open:C&&y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()}},showCSATFeedback(l){!y&&C&&et(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=or({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitCSATFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!y&&C&&et(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=ir({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitNPSFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return F.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return F.submitNPSFeedback(l,u)},destroy(){rt.forEach(l=>l()),Fe.remove(),ne==null||ne.destroy(),ae==null||ae.remove(),Kt&&Y.removeEventListener("click",Kt)}};if((((Cr=r==null?void 0:r.debugTools)!=null?Cr:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:m,getMessages:m.getMessages,getStatus:m.getStatus,getMetadata:m.getPersistentMetadata,updateMetadata:m.updatePersistentMetadata,clearHistory:()=>m.clearChat(),setVoiceActive:b=>b?m.startVoiceRecognition():m.stopVoiceRecognition()};window.AgentWidgetBrowser=u,rt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(X&&typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.showEventStream()},b=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.hideEventStream()};window.addEventListener("persona:showEventStream",u),window.addEventListener("persona:hideEventStream",b),rt.push(()=>{window.removeEventListener("persona:showEventStream",u),window.removeEventListener("persona:hideEventStream",b)})}let P=el(t.persistState);if(P&&C){let l=tl(P.storage),u=`${P.keyPrefix}widget-open`,b=`${P.keyPrefix}widget-voice`,L=`${P.keyPrefix}widget-voice-mode`;if(l){let A=((xr=P.persist)==null?void 0:xr.openState)&&l.getItem(u)==="true",$=((Sr=P.persist)==null?void 0:Sr.voiceState)&&l.getItem(b)==="true",ye=((Ar=P.persist)==null?void 0:Ar.voiceState)&&l.getItem(L)==="true";if(A&&setTimeout(()=>{m.open(),setTimeout(()=>{var ce;if($||ye)m.startVoiceRecognition();else if((ce=P.persist)!=null&&ce.focusInput){let be=e.querySelector("textarea");be&&be.focus()}},100)},0),(Er=P.persist)!=null&&Er.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Tr=P.persist)!=null&&Tr.voiceState&&(s.on("voice:state",ce=>{l.setItem(b,ce.active?"true":"false")}),s.on("user:message",ce=>{l.setItem(L,ce.viaVoice?"true":"false")})),P.clearOnChatClear){let ce=()=>{l.removeItem(u),l.removeItem(b),l.removeItem(L)},be=()=>ce();window.addEventListener("persona:clear-chat",be),rt.push(()=>{window.removeEventListener("persona:clear-chat",be)})}}}return m};var dr={},nl=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},sl=()=>{try{if(typeof dr!="undefined"&&dr.url)return new URL("../widget.css",dr.url).href}catch{}return null},_i=e=>{let n=sl(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},qi=e=>{var g,w,c,h;let n=nl(e.target),r=document.createElement("div");r.className="persona-host";let t=(c=(w=(g=e.config)==null?void 0:g.launcher)==null?void 0:w.enabled)!=null?c:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let f=r.attachShadow({mode:"open"});i=f,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),f.appendChild(s),_i(f)}else i=r,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),_i(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=lr(s,e.config,{debugTools:e.debugTools});(h=e.onReady)==null||h.call(e);let d={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var zi={name:"@runtypelabs/persona",version:"1.44.1",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 Bn=zi.version;function sn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function ol(e){if(e)return{getHeaders:sn(e.getHeaders),onFeedback:sn(e.onFeedback),onCopy:sn(e.onCopy),requestMiddleware:sn(e.requestMiddleware),actionHandlers:sn(e.actionHandlers),actionParsers:sn(e.actionParsers),postprocessMessage:sn(e.postprocessMessage),contextProviders:sn(e.contextProviders),streamParser:sn(e.streamParser)}}var Ui=`({ text, message }: any) => {
|
|
60
|
+
`}if(!I){let fn="max-height: -moz-available !important; max-height: stretch !important;",hn=l?"":"padding-top: 1.25em !important;";Oe.style.cssText+=fn+hn}};vn(),Ts(e,t);let it=[];J&&it.push(()=>{ge!==null&&(cancelAnimationFrame(ge),ge=null),ee==null||ee.destroy(),ee=null,P==null||P.destroy(),P=null,$=null});let Jt=null,Rn=()=>{Jt&&(Jt(),Jt=null),t.colorScheme==="auto"&&(Jt=xi(()=>{Ts(e,t)}))};Rn(),it.push(()=>{Jt&&(Jt(),Jt=null)});let rn=Ri(At),Kt=null,F,on=!1,Gt=!0,cn=0,Fn=0,Qt=null,Zt=!1,yn=0,bn=!1,is=125,as=2e3,ls=5,$n=50,Cn=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},On=(xr=(Cr=t.voiceRecognition)==null?void 0:Cr.autoResume)!=null?xr:!1,Nn=l=>{s.emit("voice:state",{active:Ye.active,source:l,timestamp:Date.now()})},en=()=>{u(l=>({...l,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},ds=()=>{var L,A;if(((L=t.voiceRecognition)==null?void 0:L.enabled)===!1)return;let l=lr(a.voiceState),p=!!l.active,b=Number((A=l.timestamp)!=null?A:0);Ye.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-b<ol&&setTimeout(()=>{Ye.active||(Ye.manuallyDeactivated=!1,mn("restore"))},1e3)},cs=()=>F?ji(F.getMessages()).filter(l=>!l.__skipPersist):[];function Dn(l){if(!(i!=null&&i.save))return;let b={messages:l?ji(l):F?cs():[],metadata:a};try{let L=i.save(b);L instanceof Promise&&L.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(L){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)}}let un=(l=!1)=>{if(!Gt)return;let p=Date.now();Zt&&p<yn&&!l||(Zt&&p>=yn&&(Zt=!1),!(!l&&!on)&&(p-Fn<is||(Fn=p,Qt&&cancelAnimationFrame(Qt),Qt=requestAnimationFrame(()=>{Zt||!Gt||(bn=!0,Ne.scrollTop=Ne.scrollHeight,cn=Ne.scrollTop,requestAnimationFrame(()=>{bn=!1}),Qt=null)}))))},tn=null,us=()=>Oe.querySelector("#persona-scroll-container")||Ne,ps=(l,p=500)=>{let b=l.scrollTop,L=l.clientHeight,A=l.scrollHeight,N=A-b;if(b+L>=A-2||Math.abs(N)<5)return;tn!==null&&(cancelAnimationFrame(tn),tn=null);let de=performance.now(),xe=Se=>1-Math.pow(1-Se,3),Le=Se=>{let Be=l.scrollHeight;Be!==A&&(A=Be,N=A-b);let G=Se-de,I=Math.min(G/p,1),ye=xe(I),Ae=b+N*ye;l.scrollTop=Ae,I<1?tn=requestAnimationFrame(Le):(l.scrollTop=l.scrollHeight,tn=null)};tn=requestAnimationFrame(Le)},gs=l=>{let p=new Map;l.forEach(b=>{let L=Cn.get(b.id);p.set(b.id,{streaming:b.streaming,role:b.role}),!L&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(L!=null&&L.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b)}),Cn.clear(),p.forEach((b,L)=>{Cn.set(L,b)})},pn=(l,p,b)=>{var Le,Se,Be,G;let L=document.createElement("div"),N=(()=>{var ye;let I=o.find(Ae=>Ae.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((ye=t.loadingIndicator)!=null&&ye.render)return t.loadingIndicator.render})();p.forEach(I=>{var mt,It;let ye=null,Ae=o.find(V=>!!(I.variant==="reasoning"&&V.renderReasoning||I.variant==="tool"&&V.renderToolCall||!I.variant&&V.renderMessage)),Xe=(mt=t.layout)==null?void 0:mt.messages;if(Ae)if(I.variant==="reasoning"&&I.reasoning&&Ae.renderReasoning){if(!U)return;ye=Ae.renderReasoning({message:I,defaultRenderer:()=>Ks(I),config:t})}else if(I.variant==="tool"&&I.toolCall&&Ae.renderToolCall){if(!re)return;ye=Ae.renderToolCall({message:I,defaultRenderer:()=>Ys(I,t),config:t})}else Ae.renderMessage&&(ye=Ae.renderMessage({message:I,defaultRenderer:()=>{let V=ns(I,b,Xe,t.messageActions,lt,{loadingIndicatorRenderer:N,widgetConfig:t});return I.role!=="user"&&Xs(V,I,t,F),V},config:t}));if(!ye&&I.role==="assistant"&&!I.variant&&t.enableComponentStreaming!==!1&&rr(I)){let qe=or(I);if(qe){let Vt=sr(qe,{config:t,message:I,transform:b});if(Vt){let zt=document.createElement("div");if(zt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),zt.id=`bubble-${I.id}`,zt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let an=document.createElement("div");an.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",an.innerHTML=b({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),zt.appendChild(an)}zt.appendChild(Vt),ye=zt}}}if(!ye)if(I.variant==="reasoning"&&I.reasoning){if(!U)return;ye=Ks(I)}else if(I.variant==="tool"&&I.toolCall){if(!re)return;ye=Ys(I,t)}else{let V=(It=t.layout)==null?void 0:It.messages;V!=null&&V.renderUserMessage&&I.role==="user"?ye=V.renderUserMessage({message:I,config:t,streaming:!!I.streaming}):V!=null&&V.renderAssistantMessage&&I.role==="assistant"?ye=V.renderAssistantMessage({message:I,config:t,streaming:!!I.streaming}):ye=ns(I,b,V,t.messageActions,lt,{loadingIndicatorRenderer:N,widgetConfig:t}),I.role!=="user"&&ye&&Xs(ye,I,t,F)}let Re=document.createElement("div");Re.className="tvw-flex",Re.id=`wrapper-${I.id}`,Re.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Re.classList.add("tvw-justify-end"),Re.appendChild(ye),L.appendChild(Re)});let Ce=p.some(I=>I.role==="assistant"&&I.streaming),de=p[p.length-1],xe=(de==null?void 0:de.role)==="assistant"&&!de.streaming;if(on&&p.some(I=>I.role==="user")&&!Ce&&!xe){let I={config:t,streaming:!0,location:"standalone",defaultRenderer:Ln},ye=o.find(Xe=>Xe.renderLoadingIndicator),Ae=null;if(ye!=null&&ye.renderLoadingIndicator&&(Ae=ye.renderLoadingIndicator(I)),Ae===null&&((Le=t.loadingIndicator)!=null&&Le.render)&&(Ae=t.loadingIndicator.render(I)),Ae===null&&(Ae=Ln()),Ae){let Xe=document.createElement("div"),Re=((Se=t.loadingIndicator)==null?void 0:Se.showBubble)!==!1;Xe.className=Re?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Xe.setAttribute("data-typing-indicator","true"),Xe.appendChild(Ae);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Xe),L.appendChild(mt)}}if(!on&&p.length>0){let I=p[p.length-1],ye={config:t,lastMessage:I,messageCount:p.length},Ae=o.find(Re=>Re.renderIdleIndicator),Xe=null;if(Ae!=null&&Ae.renderIdleIndicator&&(Xe=Ae.renderIdleIndicator(ye)),Xe===null&&((Be=t.loadingIndicator)!=null&&Be.renderIdle)&&(Xe=t.loadingIndicator.renderIdle(ye)),Xe){let Re=document.createElement("div"),mt=((G=t.loadingIndicator)==null?void 0:G.showBubble)!==!1;Re.className=mt?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Re.setAttribute("data-idle-indicator","true"),Re.appendChild(Xe);let It=document.createElement("div");It.className="tvw-flex",It.id="wrapper-idle-indicator",It.setAttribute("data-wrapper-id","idle-indicator"),It.appendChild(Re),L.appendChild(It)}}Si(l,L),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=us();ps(I)})})},gn=()=>{C&&(y?(Oe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Ee.classList.remove("tvw-scale-95","tvw-opacity-0"),Ee.classList.add("tvw-scale-100","tvw-opacity-100"),ae?ae.element.style.display="none":he&&(he.style.display="none")):(Oe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Ee.classList.remove("tvw-scale-100","tvw-opacity-100"),Ee.classList.add("tvw-scale-95","tvw-opacity-0"),ae?ae.element.style.display="":he&&(he.style.display="")))},et=(l,p="user")=>{if(!C||y===l)return;let b=y;y=l,gn(),y&&(tt(),un(!0));let L={open:y,source:p,timestamp:Date.now()};y&&!b?s.emit("widget:opened",L):!y&&b&&s.emit("widget:closed",L),s.emit("widget:state",{open:y,launcherEnabled:C,voiceActive:Ye.active,streaming:F.isStreaming()})},xn=l=>{Y.disabled=l,_&&(_.disabled=l),rn.buttons.forEach(p=>{p.disabled=l})},_n=()=>{var A,N,Ce,de,xe,Le,Se,Be,G,I,ye,Ae,Xe,Re;Ot.textContent=(N=(A=t.copy)==null?void 0:A.welcomeTitle)!=null?N:"Hello \u{1F44B}",wt.textContent=(de=(Ce=t.copy)==null?void 0:Ce.welcomeSubtitle)!=null?de:"Ask anything about your account or products.",ue.placeholder=(Le=(xe=t.copy)==null?void 0:xe.inputPlaceholder)!=null?Le:"How can I help...",((Be=(Se=t.sendButton)==null?void 0:Se.useIcon)!=null?Be:!1)||(Y.textContent=(I=(G=t.copy)==null?void 0:G.sendButtonLabel)!=null?I:"Send");let p=(Ae=(ye=t.theme)==null?void 0:ye.inputFontFamily)!=null?Ae:"sans-serif",b=(Re=(Xe=t.theme)==null?void 0:Xe.inputFontWeight)!=null?Re:"400",L=mt=>{switch(mt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};ue.style.fontFamily=L(p),ue.style.fontWeight=b};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{u(p=>({...p,sessionId:l}))}}),F=new Qn(t,{onMessagesChanged(l){pn(Qe,l,oe),F&&(l.some(A=>A.role==="user")?rn.render([],F,ue,l):rn.render(t.suggestionChips,F,ue,l,t.suggestionChipsConfig)),un(!on),gs(l);let p=[...l].reverse().find(L=>L.role==="user"),b=Ye.lastUserMessageId;p&&p.id!==b&&(Ye.lastUserMessageId=p.id,s.emit("user:message",p)),Ye.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Dn(l)},onStatusChanged(l){var L;let p=(L=t.statusIndicator)!=null?L:{},b=A=>{var N,Ce,de,xe;return A==="idle"?(N=p.idleText)!=null?N:Pt.idle:A==="connecting"?(Ce=p.connectingText)!=null?Ce:Pt.connecting:A==="connected"?(de=p.connectedText)!=null?de:Pt.connected:A==="error"?(xe=p.errorText)!=null?xe:Pt.error:Pt[A]};ht.textContent=b(l)},onStreamingChanged(l){on=l,xn(l),F&&pn(Qe,F.getMessages(),oe),l||un(!0)}}),t.clientToken&&F.initClientSession().catch(l=>{t.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),P&&F.setSSEEventCallback((l,p)=>{P==null||P.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),d&&d.then(l=>{var p;l&&(l.metadata&&(a=lr(l.metadata),S.syncFromMetadata()),(p=l.messages)!=null&&p.length&&F.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let jn=l=>{var A;l.preventDefault();let p=ue.value.trim(),b=(A=ce==null?void 0:ce.hasAttachments())!=null?A:!1;if(!p&&!b)return;let L;b&&(L=[],L.push(...ce.getContentParts()),p&&L.push(zs(p))),ue.value="",ue.style.height="auto",F.sendMessage(p,{contentParts:L}),b&&ce.clearAttachments()},qn=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Y.click())},zn=async l=>{var b;if(((b=t.attachments)==null?void 0:b.enabled)!==!0||!ce)return;let p=al(l.clipboardData);p.length!==0&&(l.preventDefault(),await ce.handleFiles(p))},Ht=null,Nt=!1,nn=null,Yt=null,Un=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,mn=(l="user")=>{var N,Ce,de,xe;if(Nt||F.isStreaming())return;let p=Un();if(!p)return;Ht=new p;let L=(Ce=((N=t.voiceRecognition)!=null?N:{}).pauseDuration)!=null?Ce:2e3;Ht.continuous=!0,Ht.interimResults=!0,Ht.lang="en-US";let A=ue.value;Ht.onresult=Le=>{let Se="",Be="";for(let I=0;I<Le.results.length;I++){let ye=Le.results[I],Ae=ye[0].transcript;ye.isFinal?Se+=Ae+" ":Be=Ae}let G=A+Se+Be;ue.value=G,nn&&clearTimeout(nn),(Se||Be)&&(nn=window.setTimeout(()=>{let I=ue.value.trim();I&&Ht&&Nt&&(qt(),ue.value="",ue.style.height="auto",F.sendMessage(I,{viaVoice:!0}))},L))},Ht.onerror=Le=>{Le.error!=="no-speech"&&qt()},Ht.onend=()=>{if(Nt){let Le=ue.value.trim();Le&&Le!==A.trim()&&(ue.value="",ue.style.height="auto",F.sendMessage(Le,{viaVoice:!0})),qt()}};try{if(Ht.start(),Nt=!0,Ye.active=!0,l!=="system"&&(Ye.manuallyDeactivated=!1),Nn(l),en(),_){Yt={backgroundColor:_.style.backgroundColor,color:_.style.color,borderColor:_.style.borderColor};let Le=(de=t.voiceRecognition)!=null?de:{},Se=(xe=Le.recordingBackgroundColor)!=null?xe:"#ef4444",Be=Le.recordingIconColor,G=Le.recordingBorderColor;if(_.classList.add("tvw-voice-recording"),_.style.backgroundColor=Se,Be){_.style.color=Be;let I=_.querySelector("svg");I&&I.setAttribute("stroke",Be)}G&&(_.style.borderColor=G),_.setAttribute("aria-label","Stop voice recognition")}}catch{qt("system")}},qt=(l="user")=>{if(Nt){if(Nt=!1,nn&&(clearTimeout(nn),nn=null),Ht){try{Ht.stop()}catch{}Ht=null}if(Ye.active=!1,Nn(l),en(),_){if(_.classList.remove("tvw-voice-recording"),Yt){_.style.backgroundColor=Yt.backgroundColor,_.style.color=Yt.color,_.style.borderColor=Yt.borderColor;let p=_.querySelector("svg");p&&p.setAttribute("stroke",Yt.color||"currentColor"),Yt=null}_.setAttribute("aria-label","Start voice recognition")}}},ms=(l,p)=>{var Ae,Xe,Re,mt,It,V,qe;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let L=g("div","tvw-send-button-wrapper"),A=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let N=(Ae=l==null?void 0:l.iconName)!=null?Ae:"mic",Ce=(Xe=p==null?void 0:p.size)!=null?Xe:"40px",de=(Re=l==null?void 0:l.iconSize)!=null?Re:Ce,xe=parseFloat(de)||24,Le=(mt=l==null?void 0:l.backgroundColor)!=null?mt:p==null?void 0:p.backgroundColor,Se=(It=l==null?void 0:l.iconColor)!=null?It:p==null?void 0:p.textColor;A.style.width=de,A.style.height=de,A.style.minWidth=de,A.style.minHeight=de,A.style.fontSize="18px",A.style.lineHeight="1";let Be=Se||"currentColor",G=ie(N,xe,Be,1.5);G?(A.appendChild(G),A.style.color=Be):(A.textContent="\u{1F3A4}",A.style.color=Be),Le?A.style.backgroundColor=Le:A.classList.add("tvw-bg-cw-primary"),Se?A.style.color=Se:!Se&&!(p!=null&&p.textColor)&&A.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(A.style.borderWidth=l.borderWidth,A.style.borderStyle="solid"),l!=null&&l.borderColor&&(A.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(A.style.paddingLeft=l.paddingX,A.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(A.style.paddingTop=l.paddingY,A.style.paddingBottom=l.paddingY),L.appendChild(A);let I=(V=l==null?void 0:l.tooltipText)!=null?V:"Start voice recognition";if(((qe=l==null?void 0:l.showTooltip)!=null?qe:!1)&&I){let Vt=g("div","tvw-send-button-tooltip");Vt.textContent=I,L.appendChild(Vt)}return{micButton:A,micButtonWrapper:L}},Sn=()=>{if(Nt){let l=ue.value.trim();Ye.manuallyDeactivated=!0,en(),qt("user"),l&&(ue.value="",ue.style.height="auto",F.sendMessage(l))}else Ye.manuallyDeactivated=!1,en(),mn("user")};_&&(_.addEventListener("click",Sn),it.push(()=>{qt("system"),_&&_.removeEventListener("click",Sn)}));let fs=s.on("assistant:complete",()=>{On&&(Ye.active||Ye.manuallyDeactivated||On==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{!Ye.active&&!Ye.manuallyDeactivated&&mn("auto")},600))});it.push(fs);let D=s.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});it.push(D);let Te=()=>{et(!y,"user")},ae=null,he=null;if(C){let l=o.find(p=>p.renderLauncher);if(l!=null&&l.renderLauncher){let p=l.renderLauncher({config:t,defaultRenderer:()=>Zn(t,Te).element,onToggle:Te});p&&(he=p)}he||(ae=Zn(t,Te))}ae?e.appendChild(ae.element):he&&e.appendChild(he),gn(),rn.render(t.suggestionChips,F,ue,void 0,t.suggestionChipsConfig),_n(),xn(F.isStreaming()),un(!0),ds();let tt=()=>{var b,L,A,N,Ce,de,xe,Le;let l=(L=(b=t.launcher)==null?void 0:b.sidebarMode)!=null?L:!1,p=l||((N=(A=t.launcher)==null?void 0:A.fullHeight)!=null?N:!1);if(!C){Ee.style.height="",Ee.style.width="";return}if(!l){let Se=(de=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.width)!=null?de:t==null?void 0:t.launcherWidth,Be=Se!=null?Se:"min(400px, calc(100vw - 24px))";Ee.style.width=Be,Ee.style.maxWidth=Be}if(!p){let Se=window.innerHeight,Be=64,G=(Le=(xe=t.launcher)==null?void 0:xe.heightOffset)!=null?Le:0,I=Math.max(200,Se-Be),ye=Math.min(640,I),Ae=Math.max(200,ye-G);Ee.style.height=`${Ae}px`}};tt(),window.addEventListener("resize",tt),it.push(()=>window.removeEventListener("resize",tt)),cn=Ne.scrollTop;let Et=()=>{let l=Ne.scrollTop,p=Ne.scrollHeight,b=Ne.clientHeight,L=p-l-b,A=Math.abs(l-cn);if(cn=l,!bn&&!(A<=ls)){if(!Gt&&L<$n){Zt=!1,Gt=!0;return}Gt&&L>$n&&(Zt=!0,yn=Date.now()+as,Gt=!1)}};Ne.addEventListener("scroll",Et,{passive:!0}),it.push(()=>Ne.removeEventListener("scroll",Et)),it.push(()=>{Qt&&cancelAnimationFrame(Qt)});let nt=()=>{X&&(Kt&&(X.removeEventListener("click",Kt),Kt=null),C?(X.style.display="",Kt=()=>{y=!1,gn()},X.addEventListener("click",Kt)):X.style.display="none")};nt(),(()=>{let{clearChatButton:l}=te;l&&l.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(Hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Hn}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",L)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}a={},S.syncFromMetadata(),P==null||P.clear(),ee==null||ee.update()})})(),pt.addEventListener("submit",jn),ue.addEventListener("keydown",qn),ue.addEventListener("paste",zn),it.push(()=>{pt.removeEventListener("submit",jn),ue.removeEventListener("keydown",qn),ue.removeEventListener("paste",zn)}),it.push(()=>{F.cancel()}),ae?it.push(()=>{ae==null||ae.destroy()}):he&&it.push(()=>{he==null||he.remove()});let we={update(l){var kr,Wr,Ir,Pr,Hr,Br,Rr,Fr,$r,Or,Nr,Dr,_r,jr,qr,zr,Ur,Jr,Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,fo,ho,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,Lo,ko,Wo,Io,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,_o,jo,qo,zo,Uo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai;let p=t.toolCall,b=t.colorScheme;t={...t,...l},vn(),Ts(e,t),t.colorScheme!==b&&Rn();let L=Ms.getForInstance(t.plugins);o.length=0,o.push(...L),C=(Wr=(kr=t.launcher)==null?void 0:kr.enabled)!=null?Wr:!0,E=(Pr=(Ir=t.launcher)==null?void 0:Ir.autoExpand)!=null?Pr:!1,U=(Br=(Hr=t.features)==null?void 0:Hr.showReasoning)!=null?Br:!0,re=(Fr=(Rr=t.features)==null?void 0:Rr.showToolCalls)!=null?Fr:!0;let A=J;if(J=(Or=($r=t.features)==null?void 0:$r.showEventStreamToggle)!=null?Or:!1,J&&!A){if(P||($=new rs(pe),P=new ss(Z,$),$.open().then(()=>P==null?void 0:P.restore()).catch(()=>{}),F.setSSEEventCallback((M,ke)=>{P.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:M,timestamp:Date.now(),payload:JSON.stringify(ke)})})),!j&&Q){let M=(Dr=(Nr=t.features)==null?void 0:Nr.eventStream)==null?void 0:Dr.classNames,ke="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(M!=null&&M.toggleButton?" "+M.toggleButton:"");j=g("button",ke),j.style.width="28px",j.style.height="28px",j.type="button",j.setAttribute("aria-label","Event Stream"),j.title="Event Stream";let Ge=ie("activity","18px","currentColor",1.5);Ge&&j.appendChild(Ge);let ve=te.clearChatButtonWrapper,$e=te.closeButtonWrapper,ft=ve||$e;ft&&ft.parentNode===Q?Q.insertBefore(j,ft):Q.appendChild(j),j.addEventListener("click",()=>{be?_e():We()})}}else!J&&A&&(_e(),j&&(j.remove(),j=null),P==null||P.clear(),$==null||$.destroy(),P=null,$=null);if(((_r=t.launcher)==null?void 0:_r.enabled)===!1&&ae&&(ae.destroy(),ae=null),((jr=t.launcher)==null?void 0:jr.enabled)===!1&&he&&(he.remove(),he=null),((qr=t.launcher)==null?void 0:qr.enabled)!==!1&&!ae&&!he){let M=o.find(ke=>ke.renderLauncher);if(M!=null&&M.renderLauncher){let ke=M.renderLauncher({config:t,defaultRenderer:()=>Zn(t,Te).element,onToggle:Te});ke&&(he=ke,e.appendChild(he))}he||(ae=Zn(t,Te),e.appendChild(ae.element))}ae&&ae.update(t),vt&&((zr=t.launcher)==null?void 0:zr.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((Ur=t.launcher)==null?void 0:Ur.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let N=(Jr=t.layout)==null?void 0:Jr.header;if((N==null?void 0:N.layout)!==K&&Q){let M=N?es(t,N,{showClose:C,onClose:()=>et(!1,"user")}):dn({config:t,showClose:C,onClose:()=>et(!1,"user")});Q.replaceWith(M.header),Q=M.header,He=M.iconHolder,vt=M.headerTitle,yt=M.headerSubtitle,X=M.closeButton,K=N==null?void 0:N.layout}else if(N&&(He&&(He.style.display=N.showIcon===!1?"none":""),vt&&(vt.style.display=N.showTitle===!1?"none":""),yt&&(yt.style.display=N.showSubtitle===!1?"none":""),X&&(X.style.display=N.showCloseButton===!1?"none":""),te.clearChatButtonWrapper)){let M=N.showClearChat;if(M!==void 0){te.clearChatButtonWrapper.style.display=M?"":"none";let{closeButtonWrapper:ke}=te;ke&&!ke.classList.contains("tvw-absolute")&&(M?ke.classList.remove("tvw-ml-auto"):ke.classList.add("tvw-ml-auto"))}}let de=((Kr=t.layout)==null?void 0:Kr.showHeader)!==!1;Q&&(Q.style.display=de?"":"none");let xe=((Yr=t.layout)==null?void 0:Yr.showFooter)!==!1;De&&(De.style.display=xe?"":"none"),C!==k?C?et(E,"auto"):(y=!0,gn()):E!==x&&et(E,"auto"),x=E,k=C,tt(),nt(),JSON.stringify(l.toolCall)!==JSON.stringify(p)&&F&&pn(Qe,F.getMessages(),oe);let G=(Vr=t.launcher)!=null?Vr:{},I=(Xr=G.headerIconHidden)!=null?Xr:!1,ye=(Qr=(Gr=t.layout)==null?void 0:Gr.header)==null?void 0:Qr.showIcon,Ae=I||ye===!1,Xe=G.headerIconName,Re=(Zr=G.headerIconSize)!=null?Zr:"48px";if(He){let M=me.querySelector(".tvw-border-b-cw-divider"),ke=M==null?void 0:M.querySelector(".tvw-flex-col");if(Ae)He.style.display="none",M&&ke&&!M.contains(ke)&&M.insertBefore(ke,M.firstChild);else{if(He.style.display="",He.style.height=Re,He.style.width=Re,M&&ke&&(M.contains(He)?He.nextSibling!==ke&&(He.remove(),M.insertBefore(He,ke)):M.insertBefore(He,ke)),Xe){let ve=parseFloat(Re)||24,$e=ie(Xe,ve*.6,"#ffffff",2);$e?He.replaceChildren($e):He.textContent=(eo=G.agentIconText)!=null?eo:"\u{1F4AC}"}else if(G.iconUrl){let ve=He.querySelector("img");if(ve)ve.src=G.iconUrl,ve.style.height=Re,ve.style.width=Re;else{let $e=document.createElement("img");$e.src=G.iconUrl,$e.alt="",$e.className="tvw-rounded-xl tvw-object-cover",$e.style.height=Re,$e.style.width=Re,He.replaceChildren($e)}}else{let ve=He.querySelector("svg"),$e=He.querySelector("img");(ve||$e)&&He.replaceChildren(),He.textContent=(to=G.agentIconText)!=null?to:"\u{1F4AC}"}let Ge=He.querySelector("img");Ge&&(Ge.style.height=Re,Ge.style.width=Re)}}let mt=(so=(no=t.layout)==null?void 0:no.header)==null?void 0:so.showTitle,It=(oo=(ro=t.layout)==null?void 0:ro.header)==null?void 0:oo.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=It===!1?"none":""),X){((ao=(io=t.layout)==null?void 0:io.header)==null?void 0:ao.showCloseButton)===!1?X.style.display="none":X.style.display="";let ke=(lo=G.closeButtonSize)!=null?lo:"32px",Ge=(co=G.closeButtonPlacement)!=null?co:"inline";X.style.height=ke,X.style.width=ke;let{closeButtonWrapper:ve}=te,$e=Ge==="top-right",ft=ve==null?void 0:ve.classList.contains("tvw-absolute");if(ve&&$e!==ft)if(ve.remove(),$e)ve.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",me.style.position="relative",me.appendChild(ve);else{let Ie=(po=(uo=G.clearChat)==null?void 0:uo.placement)!=null?po:"inline",St=(mo=(go=G.clearChat)==null?void 0:go.enabled)!=null?mo:!0;ve.className=St&&Ie==="inline"?"":"tvw-ml-auto";let Ft=me.querySelector(".tvw-border-b-cw-divider");Ft&&Ft.appendChild(ve)}if(G.closeButtonColor?(X.style.color=G.closeButtonColor,X.classList.remove("tvw-text-cw-muted")):(X.style.color="",X.classList.add("tvw-text-cw-muted")),G.closeButtonBackgroundColor?(X.style.backgroundColor=G.closeButtonBackgroundColor,X.classList.remove("hover:tvw-bg-gray-100")):(X.style.backgroundColor="",X.classList.add("hover:tvw-bg-gray-100")),G.closeButtonBorderWidth||G.closeButtonBorderColor){let Ie=G.closeButtonBorderWidth||"0px",St=G.closeButtonBorderColor||"transparent";X.style.border=`${Ie} solid ${St}`,X.classList.remove("tvw-border-none")}else X.style.border="",X.classList.add("tvw-border-none");G.closeButtonBorderRadius?(X.style.borderRadius=G.closeButtonBorderRadius,X.classList.remove("tvw-rounded-full")):(X.style.borderRadius="",X.classList.add("tvw-rounded-full")),G.closeButtonPaddingX?(X.style.paddingLeft=G.closeButtonPaddingX,X.style.paddingRight=G.closeButtonPaddingX):(X.style.paddingLeft="",X.style.paddingRight=""),G.closeButtonPaddingY?(X.style.paddingTop=G.closeButtonPaddingY,X.style.paddingBottom=G.closeButtonPaddingY):(X.style.paddingTop="",X.style.paddingBottom="");let kt=(fo=G.closeButtonIconName)!=null?fo:"x",Dt=(ho=G.closeButtonIconText)!=null?ho:"\xD7";X.innerHTML="";let Bt=ie(kt,"20px",G.closeButtonColor||"",2);Bt?X.appendChild(Bt):X.textContent=Dt;let at=(wo=G.closeButtonTooltipText)!=null?wo:"Close chat",_t=(vo=G.closeButtonShowTooltip)!=null?vo:!0;if(X.setAttribute("aria-label",at),ve&&(ve._cleanupTooltip&&(ve._cleanupTooltip(),delete ve._cleanupTooltip),_t&&at)){let Ie=null,St=()=>{if(Ie||!X)return;Ie=g("div","tvw-clear-chat-tooltip"),Ie.textContent=at;let Xn=g("div");Xn.className="tvw-clear-chat-tooltip-arrow",Ie.appendChild(Xn);let wn=X.getBoundingClientRect();Ie.style.position="fixed",Ie.style.left=`${wn.left+wn.width/2}px`,Ie.style.top=`${wn.top-8}px`,Ie.style.transform="translate(-50%, -100%)",document.body.appendChild(Ie)},Ft=()=>{Ie&&Ie.parentNode&&(Ie.parentNode.removeChild(Ie),Ie=null)};ve.addEventListener("mouseenter",St),ve.addEventListener("mouseleave",Ft),X.addEventListener("focus",St),X.addEventListener("blur",Ft),ve._cleanupTooltip=()=>{Ft(),ve&&(ve.removeEventListener("mouseenter",St),ve.removeEventListener("mouseleave",Ft)),X&&(X.removeEventListener("focus",St),X.removeEventListener("blur",Ft))}}}let{clearChatButton:V,clearChatButtonWrapper:qe}=te;if(V){let M=(yo=G.clearChat)!=null?yo:{},ke=(bo=M.enabled)!=null?bo:!0,Ge=(xo=(Co=t.layout)==null?void 0:Co.header)==null?void 0:xo.showClearChat,ve=Ge!==void 0?Ge:ke,$e=(So=M.placement)!=null?So:"inline";if(qe){qe.style.display=ve?"":"none";let{closeButtonWrapper:ft}=te;ft&&!ft.classList.contains("tvw-absolute")&&(ve?ft.classList.remove("tvw-ml-auto"):ft.classList.add("tvw-ml-auto"));let kt=$e==="top-right",Dt=qe.classList.contains("tvw-absolute");if(kt!==Dt&&ve){if(qe.remove(),kt)qe.className="tvw-absolute tvw-top-4 tvw-z-50",qe.style.right="48px",me.style.position="relative",me.appendChild(qe);else{qe.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",qe.style.right="";let at=me.querySelector(".tvw-border-b-cw-divider"),_t=te.closeButtonWrapper;at&&_t&&_t.parentElement===at?at.insertBefore(qe,_t):at&&at.appendChild(qe)}let Bt=te.closeButtonWrapper;Bt&&!Bt.classList.contains("tvw-absolute")&&(kt?Bt.classList.add("tvw-ml-auto"):Bt.classList.remove("tvw-ml-auto"))}}if(ve){let ft=(Ao=M.size)!=null?Ao:"32px";V.style.height=ft,V.style.width=ft;let kt=(Eo=M.iconName)!=null?Eo:"refresh-cw",Dt=(To=M.iconColor)!=null?To:"";V.innerHTML="";let Bt=ie(kt,"20px",Dt||"",2);if(Bt&&V.appendChild(Bt),Dt?(V.style.color=Dt,V.classList.remove("tvw-text-cw-muted")):(V.style.color="",V.classList.add("tvw-text-cw-muted")),M.backgroundColor?(V.style.backgroundColor=M.backgroundColor,V.classList.remove("hover:tvw-bg-gray-100")):(V.style.backgroundColor="",V.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let Ie=M.borderWidth||"0px",St=M.borderColor||"transparent";V.style.border=`${Ie} solid ${St}`,V.classList.remove("tvw-border-none")}else V.style.border="",V.classList.add("tvw-border-none");M.borderRadius?(V.style.borderRadius=M.borderRadius,V.classList.remove("tvw-rounded-full")):(V.style.borderRadius="",V.classList.add("tvw-rounded-full")),M.paddingX?(V.style.paddingLeft=M.paddingX,V.style.paddingRight=M.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),M.paddingY?(V.style.paddingTop=M.paddingY,V.style.paddingBottom=M.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let at=(Mo=M.tooltipText)!=null?Mo:"Clear chat",_t=(Lo=M.showTooltip)!=null?Lo:!0;if(V.setAttribute("aria-label",at),qe&&(qe._cleanupTooltip&&(qe._cleanupTooltip(),delete qe._cleanupTooltip),_t&&at)){let Ie=null,St=()=>{if(Ie||!V)return;Ie=g("div","tvw-clear-chat-tooltip"),Ie.textContent=at;let Xn=g("div");Xn.className="tvw-clear-chat-tooltip-arrow",Ie.appendChild(Xn);let wn=V.getBoundingClientRect();Ie.style.position="fixed",Ie.style.left=`${wn.left+wn.width/2}px`,Ie.style.top=`${wn.top-8}px`,Ie.style.transform="translate(-50%, -100%)",document.body.appendChild(Ie)},Ft=()=>{Ie&&Ie.parentNode&&(Ie.parentNode.removeChild(Ie),Ie=null)};qe.addEventListener("mouseenter",St),qe.addEventListener("mouseleave",Ft),V.addEventListener("focus",St),V.addEventListener("blur",Ft),qe._cleanupTooltip=()=>{Ft(),qe&&(qe.removeEventListener("mouseenter",St),qe.removeEventListener("mouseleave",Ft)),V&&(V.removeEventListener("focus",St),V.removeEventListener("blur",Ft))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Ls],zt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[Pn.message,Pn.messageAndClick];S=ks({parsers:Vt,handlers:zt,getSessionMetadata:v,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),oe=qi(t,S,H),F.updateConfig(t),pn(Qe,F.getMessages(),oe),rn.render(t.suggestionChips,F,ue,void 0,t.suggestionChipsConfig),_n(),xn(F.isStreaming());let an=((ko=t.voiceRecognition)==null?void 0:ko.enabled)===!0,hs=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(an&&hs)if(!_||!Ze){let M=ms(t.voiceRecognition,t.sendButton);M&&(_=M.micButton,Ze=M.micButtonWrapper,Mt.insertBefore(Ze,ut),_.addEventListener("click",Sn),_.disabled=F.isStreaming())}else{let M=(Wo=t.voiceRecognition)!=null?Wo:{},ke=(Io=t.sendButton)!=null?Io:{},Ge=(Po=M.iconName)!=null?Po:"mic",ve=(Ho=ke.size)!=null?Ho:"40px",$e=(Bo=M.iconSize)!=null?Bo:ve,ft=parseFloat($e)||24;_.style.width=$e,_.style.height=$e,_.style.minWidth=$e,_.style.minHeight=$e;let kt=(Fo=(Ro=M.iconColor)!=null?Ro:ke.textColor)!=null?Fo:"currentColor";_.innerHTML="";let Dt=ie(Ge,ft,kt,2);Dt?_.appendChild(Dt):_.textContent="\u{1F3A4}";let Bt=($o=M.backgroundColor)!=null?$o:ke.backgroundColor;Bt?(_.style.backgroundColor=Bt,_.classList.remove("tvw-bg-cw-primary")):(_.style.backgroundColor="",_.classList.add("tvw-bg-cw-primary")),kt?(_.style.color=kt,_.classList.remove("tvw-text-white")):!kt&&!ke.textColor&&(_.style.color="",_.classList.add("tvw-text-white")),M.borderWidth?(_.style.borderWidth=M.borderWidth,_.style.borderStyle="solid"):(_.style.borderWidth="",_.style.borderStyle=""),M.borderColor?_.style.borderColor=M.borderColor:_.style.borderColor="",M.paddingX?(_.style.paddingLeft=M.paddingX,_.style.paddingRight=M.paddingX):(_.style.paddingLeft="",_.style.paddingRight=""),M.paddingY?(_.style.paddingTop=M.paddingY,_.style.paddingBottom=M.paddingY):(_.style.paddingTop="",_.style.paddingBottom="");let at=Ze==null?void 0:Ze.querySelector(".tvw-send-button-tooltip"),_t=(Oo=M.tooltipText)!=null?Oo:"Start voice recognition";if(((No=M.showTooltip)!=null?No:!1)&&_t)if(at)at.textContent=_t,at.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=_t,Ze==null||Ze.insertBefore(St,_)}else at&&(at.style.display="none");Ze.style.display="",_.disabled=F.isStreaming()}else _&&Ze&&(Ze.style.display="none",Nt&&qt());if(((Do=t.attachments)==null?void 0:Do.enabled)===!0)if(!z||!Pe){let M=(_o=t.attachments)!=null?_o:{},Ge=(qo=((jo=t.sendButton)!=null?jo:{}).size)!=null?qo:"40px";fe||(fe=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),fe.style.display="none",pt.insertBefore(fe,ue)),B||(B=document.createElement("input"),B.type="file",B.accept=((zo=M.allowedTypes)!=null?zo:ln).join(","),B.multiple=((Uo=M.maxFiles)!=null?Uo:4)>1,B.style.display="none",B.setAttribute("aria-label","Attach files"),pt.insertBefore(B,ue)),z=g("div","tvw-send-button-wrapper"),Pe=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),Pe.type="button",Pe.setAttribute("aria-label",(Jo=M.buttonTooltipText)!=null?Jo:"Attach file");let ve=(Ko=M.buttonIconName)!=null?Ko:"paperclip",$e=Ge,ft=parseFloat($e)||40,kt=Math.round(ft*.6);Pe.style.width=$e,Pe.style.height=$e,Pe.style.minWidth=$e,Pe.style.minHeight=$e,Pe.style.fontSize="18px",Pe.style.lineHeight="1",Pe.style.backgroundColor="transparent",Pe.style.color="var(--cw-primary, #111827)",Pe.style.border="none",Pe.style.borderRadius="6px",Pe.style.transition="background-color 0.15s ease",Pe.addEventListener("mouseenter",()=>{Pe.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),Pe.addEventListener("mouseleave",()=>{Pe.style.backgroundColor="transparent"});let Dt=ie(ve,kt,"currentColor",1.5);Dt?Pe.appendChild(Dt):Pe.textContent="\u{1F4CE}",Pe.addEventListener("click",_t=>{_t.preventDefault(),B==null||B.click()}),z.appendChild(Pe);let Bt=(Yo=M.buttonTooltipText)!=null?Yo:"Attach file",at=g("div","tvw-send-button-tooltip");at.textContent=Bt,z.appendChild(at),Wt.append(z),!ce&&B&&fe&&(ce=Tn.fromConfig(M),ce.setPreviewsContainer(fe),B.addEventListener("change",async()=>{ce&&(B!=null&&B.files)&&(await ce.handleFileSelect(B.files),B.value="")}))}else{z.style.display="";let M=(Vo=t.attachments)!=null?Vo:{};B&&(B.accept=((Xo=M.allowedTypes)!=null?Xo:ln).join(","),B.multiple=((Go=M.maxFiles)!=null?Go:4)>1),ce&&ce.updateConfig({allowedTypes:M.allowedTypes,maxFileSize:M.maxFileSize,maxFiles:M.maxFiles})}else z&&(z.style.display="none"),ce&&ce.clearAttachments();let ct=(Qo=t.sendButton)!=null?Qo:{},ws=(Zo=ct.useIcon)!=null?Zo:!1,Jn=(ei=ct.iconText)!=null?ei:"\u2191",fn=ct.iconName,hn=(ti=ct.tooltipText)!=null?ti:"Send message",Qi=(ni=ct.showTooltip)!=null?ni:!1,Kn=(si=ct.size)!=null?si:"40px",vs=ct.backgroundColor,Xt=ct.textColor;if(ws){if(Y.style.width=Kn,Y.style.height=Kn,Y.style.minWidth=Kn,Y.style.minHeight=Kn,Y.style.fontSize="18px",Y.style.lineHeight="1",Y.innerHTML="",fn){let M=parseFloat(Kn)||24,ke=Xt&&typeof Xt=="string"&&Xt.trim()?Xt.trim():"currentColor",Ge=ie(fn,M,ke,2);Ge?(Y.appendChild(Ge),Y.style.color=ke):(Y.textContent=Jn,Xt?Y.style.color=Xt:Y.classList.add("tvw-text-white"))}else Y.textContent=Jn,Xt?Y.style.color=Xt:Y.classList.add("tvw-text-white");Y.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",vs?(Y.style.backgroundColor=vs,Y.classList.remove("tvw-bg-cw-primary")):Y.classList.add("tvw-bg-cw-primary")}else Y.textContent=(oi=(ri=t.copy)==null?void 0:ri.sendButtonLabel)!=null?oi:"Send",Y.style.width="",Y.style.height="",Y.style.minWidth="",Y.style.minHeight="",Y.style.fontSize="",Y.style.lineHeight="",Y.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",vs?(Y.style.backgroundColor=vs,Y.classList.remove("tvw-bg-cw-accent")):Y.classList.add("tvw-bg-cw-accent"),Xt?Y.style.color=Xt:Y.classList.add("tvw-text-white");ct.borderWidth?(Y.style.borderWidth=ct.borderWidth,Y.style.borderStyle="solid"):(Y.style.borderWidth="",Y.style.borderStyle=""),ct.borderColor?Y.style.borderColor=ct.borderColor:Y.style.borderColor="",ct.paddingX?(Y.style.paddingLeft=ct.paddingX,Y.style.paddingRight=ct.paddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),ct.paddingY?(Y.style.paddingTop=ct.paddingY,Y.style.paddingBottom=ct.paddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let Yn=ut==null?void 0:ut.querySelector(".tvw-send-button-tooltip");if(Qi&&hn)if(Yn)Yn.textContent=hn,Yn.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=hn,ut==null||ut.insertBefore(M,Y)}else Yn&&(Yn.style.display="none");let Vn=(ii=t.statusIndicator)!=null?ii:{},Zi=(ai=Vn.visible)!=null?ai:!0;if(ht.style.display=Zi?"":"none",F){let M=F.getStatus(),ke=Ge=>{var ve,$e,ft,kt;return Ge==="idle"?(ve=Vn.idleText)!=null?ve:Pt.idle:Ge==="connecting"?($e=Vn.connectingText)!=null?$e:Pt.connecting:Ge==="connected"?(ft=Vn.connectedText)!=null?ft:Pt.connected:Ge==="error"?(kt=Vn.errorText)!=null?kt:Pt.error:Pt[Ge]};ht.textContent=ke(M)}},open(){C&&et(!0,"api")},close(){C&&et(!1,"api")},toggle(){C&&et(!y,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(Hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Hn}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.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(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}a={},S.syncFromMetadata(),P==null||P.clear(),ee==null||ee.update()},setMessage(l){return!ue||F.isStreaming()?!1:(!y&&C&&et(!0,"system"),ue.value=l,ue.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let p=(l==null?void 0:l.trim())||ue.value.trim();return p?(!y&&C&&et(!0,"system"),ue.value="",ue.style.height="auto",F.sendMessage(p),!0):!1},startVoiceRecognition(){return Nt||F.isStreaming()||!Un()?!1:(!y&&C&&et(!0,"system"),Ye.manuallyDeactivated=!1,en(),mn("user"),!0)},stopVoiceRecognition(){return Nt?(Ye.manuallyDeactivated=!0,en(),qt("user"),!0):!1},injectMessage(l){return!y&&C&&et(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!y&&C&&et(!0,"system");let p=F.injectAssistantMessage(l);return R&&(R=!1,W&&(clearTimeout(W),W=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),p},injectUserMessage(l){return!y&&C&&et(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!y&&C&&et(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!y&&C&&et(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!y&&C&&et(!0,"system"),F.injectTestEvent(l)},__pushEventStreamEvent(l){P&&P.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||!P||We()},hideEventStream(){be&&_e()},isEventStreamVisible(){return be},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){u(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return C&&y},isVoiceActive(){return Ye.active},getState(){return{open:C&&y,launcherEnabled:C,voiceActive:Ye.active,streaming:F.isStreaming()}},showCSATFeedback(l){!y&&C&&et(!0,"system");let p=Qe.querySelector(".tvw-feedback-container");p&&p.remove();let b=ir({onSubmit:async(L,A)=>{var N;F.isClientTokenMode()&&await F.submitCSATFeedback(L,A),(N=l==null?void 0:l.onSubmit)==null||N.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!y&&C&&et(!0,"system");let p=Qe.querySelector(".tvw-feedback-container");p&&p.remove();let b=ar({onSubmit:async(L,A)=>{var N;F.isClientTokenMode()&&await F.submitNPSFeedback(L,A),(N=l==null?void 0:l.onSubmit)==null||N.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return F.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return F.submitNPSFeedback(l,p)},destroy(){it.forEach(l=>l()),Oe.remove(),ae==null||ae.destroy(),he==null||he.remove(),Kt&&X.removeEventListener("click",Kt)}};if((((Sr=r==null?void 0:r.debugTools)!=null?Sr:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:we,getMessages:we.getMessages,getStatus:we.getStatus,getMetadata:we.getPersistentMetadata,updateMetadata:we.updatePersistentMetadata,clearHistory:()=>we.clearChat(),setVoiceActive:b=>b?we.startVoiceRecognition():we.stopVoiceRecognition()};window.AgentWidgetBrowser=p,it.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(J&&typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),p=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&we.showEventStream()},b=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&we.hideEventStream()};window.addEventListener("persona:showEventStream",p),window.addEventListener("persona:hideEventStream",b),it.push(()=>{window.removeEventListener("persona:showEventStream",p),window.removeEventListener("persona:hideEventStream",b)})}let w=ll(t.persistState);if(w&&C){let l=dl(w.storage),p=`${w.keyPrefix}widget-open`,b=`${w.keyPrefix}widget-voice`,L=`${w.keyPrefix}widget-voice-mode`;if(l){let A=((Ar=w.persist)==null?void 0:Ar.openState)&&l.getItem(p)==="true",N=((Er=w.persist)==null?void 0:Er.voiceState)&&l.getItem(b)==="true",Ce=((Tr=w.persist)==null?void 0:Tr.voiceState)&&l.getItem(L)==="true";if(A&&setTimeout(()=>{we.open(),setTimeout(()=>{var de;if(N||Ce)we.startVoiceRecognition();else if((de=w.persist)!=null&&de.focusInput){let xe=e.querySelector("textarea");xe&&xe.focus()}},100)},0),(Mr=w.persist)!=null&&Mr.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Lr=w.persist)!=null&&Lr.voiceState&&(s.on("voice:state",de=>{l.setItem(b,de.active?"true":"false")}),s.on("user:message",de=>{l.setItem(L,de.viaVoice?"true":"false")})),w.clearOnChatClear){let de=()=>{l.removeItem(p),l.removeItem(b),l.removeItem(L)},xe=()=>de();window.addEventListener("persona:clear-chat",xe),it.push(()=>{window.removeEventListener("persona:clear-chat",xe)})}}}return we};var cr={},cl=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},ul=()=>{try{if(typeof cr!="undefined"&&cr.url)return new URL("../widget.css",cr.url).href}catch{}return null},zi=e=>{let n=ul(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},Ui=e=>{var c,v,u,m;let n=cl(e.target),r=document.createElement("div");r.className="persona-host";let t=(u=(v=(c=e.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?u:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let h=r.attachShadow({mode:"open"});i=h,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),h.appendChild(s),zi(h)}else i=r,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),zi(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=dr(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var Ji={name:"@runtypelabs/persona",version:"1.44.2",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 Bn=Ji.version;function sn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function gl(e){if(e)return{getHeaders:sn(e.getHeaders),onFeedback:sn(e.onFeedback),onCopy:sn(e.onCopy),requestMiddleware:sn(e.requestMiddleware),actionHandlers:sn(e.actionHandlers),actionParsers:sn(e.actionParsers),postprocessMessage:sn(e.postprocessMessage),contextProviders:sn(e.contextProviders),streamParser:sn(e.streamParser)}}var Ki=`({ 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 Qi}from"marked";var Zi=e=>{if(e)return e},ys=e=>{var o,s;let n=
|
|
|
70
70
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
71
71
|
} catch (e) { return null; }
|
|
72
72
|
return null;
|
|
73
|
-
}`,
|
|
73
|
+
}`,Yi=`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 Qi}from"marked";var Zi=e=>{if(e)return e},ys=e=>{var o,s;let n=
|
|
|
83
83
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
84
84
|
} catch (e) { return null; }
|
|
85
85
|
return null;
|
|
86
|
-
}`,
|
|
86
|
+
}`,Vi=`(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 Qi}from"marked";var Zi=e=>{if(e)return e},ys=e=>{var o,s;let n=
|
|
|
100
100
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
101
101
|
window.location.href = targetUrl;
|
|
102
102
|
return { handled: true, displayText: text };
|
|
103
|
-
}`,
|
|
103
|
+
}`,Xi=`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 Qi}from"marked";var Zi=e=>{if(e)return e},ys=e=>{var o,s;let n=
|
|
|
117
117
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
118
118
|
window.location.href = targetUrl;
|
|
119
119
|
return { handled: true, displayText: text };
|
|
120
|
-
}`,
|
|
120
|
+
}`,ml=`(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
|
-
}`,
|
|
126
|
+
}`,fl=`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
|
|
133
|
-
`)}function
|
|
134
|
-
`)}function pl(e,n){let r=n==null?void 0:n.hooks,t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),e.theme&&(t.push(" theme: {"),Object.entries(e.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...Ws(e," ")),t.push(...Is(e," ",r)),t.push(...Ps(e," ")),t.push(...Hs(e," ")),r!=null&&r.getHeaders&&t.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&t.push(` contextProviders: ${r.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?t.push(` streamParser: ${r.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${il}),`)),r!=null&&r.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${Ui}`),t.push(" ],")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Parser for markdown-wrapped JSON"),t.push(` ${Ui}`),t.push(" ],")),r!=null&&r.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${r.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${Ki}`),t.push(" ],")):(t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(` ${Ki}`),t.push(" ],")),r!=null&&r.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),t.push(" const merged = customResult || payload;"),t.push(" return {"),t.push(" ...merged,"),t.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),t.push(" };"),t.push(" }")):(t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }")),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('persona:message', handleMessage);"),t.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('persona:message', handleMessage);"),t.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
|
|
135
|
-
`)}function
|
|
136
|
-
`)}function
|
|
132
|
+
}`;function hl(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function Ws(e){var n,r;return(r=(n=e.parserType)!=null?n:hl(e.streamParser))!=null?r:"plain"}function Is(e,n){let r=[];return e.toolCall&&(r.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([t,o])=>{typeof o=="string"&&r.push(`${n} ${t}: "${o}",`)}),r.push(`${n}},`)),r}function Ps(e,n,r){let t=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||s)&&(t.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?t.push(`${n} ${i}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${i}: ${a},`))}),r!=null&&r.onFeedback&&t.push(`${n} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&t.push(`${n} onCopy: ${r.onCopy},`),t.push(`${n}},`)),t}function Hs(e,n){let r=[];if(e.markdown){let t=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(t||o)&&(r.push(`${n}markdown: {`),t&&(r.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`)}),r.push(`${n} },`)),o&&r.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${n}},`))}return r}function Bs(e,n){let r=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(t||o)&&(r.push(`${n}layout: {`),t&&(r.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),o&&(r.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${n} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?r.push(`${n} ${a}: "${d}",`):typeof d=="boolean"&&r.push(`${n} ${a}: ${d},`)}),r.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(r.push(`${n} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?r.push(`${n} ${d}: "${c}",`):typeof c=="boolean"&&r.push(`${n} ${d}: ${c},`))}),r.push(`${n} },`)):typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),r.push(`${n}},`))}return r}function ur(e,n){let r=[];return e&&(e.getHeaders&&r.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${n}streamParser: ${e.streamParser},`)),r}function wl(e,n="esm",r){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let o=r?{...r,hooks:gl(r.hooks)}:void 0;return n==="esm"?vl(t,o):n==="script-installer"?Cl(t):n==="script-advanced"?Sl(t,o):n==="react-component"?yl(t,o):n==="react-advanced"?bl(t,o):xl(t,o)}function vl(e,n){let r=n==null?void 0:n.hooks,t=Ws(e),o=t!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Is(e," ")),s.push(...Ps(e," ",r)),s.push(...Hs(e," ")),s.push(...Bs(e," ")),s.push(...ur(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
133
|
+
`)}function yl(e,n){let r=n==null?void 0:n.hooks,t=Ws(e),o=t!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Is(e," ")),s.push(...Ps(e," ",r)),s.push(...Hs(e," ")),s.push(...Bs(e," ")),s.push(...ur(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
|
|
134
|
+
`)}function bl(e,n){let r=n==null?void 0:n.hooks,t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),e.theme&&(t.push(" theme: {"),Object.entries(e.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...Is(e," ")),t.push(...Ps(e," ",r)),t.push(...Hs(e," ")),t.push(...Bs(e," ")),r!=null&&r.getHeaders&&t.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&t.push(` contextProviders: ${r.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?t.push(` streamParser: ${r.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${ml}),`)),r!=null&&r.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${Ki}`),t.push(" ],")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Parser for markdown-wrapped JSON"),t.push(` ${Ki}`),t.push(" ],")),r!=null&&r.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${r.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${Vi}`),t.push(" ],")):(t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(` ${Vi}`),t.push(" ],")),r!=null&&r.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),t.push(" const merged = customResult || payload;"),t.push(" return {"),t.push(" ...merged,"),t.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),t.push(" };"),t.push(" }")):(t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }")),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('persona:message', handleMessage);"),t.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('persona:message', handleMessage);"),t.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
|
|
135
|
+
`)}function Gi(e){var o;let n=Ws(e),r=n!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.clientToken&&(t.clientToken=e.clientToken),e.flowId&&(t.flowId=e.flowId),r&&(t.parserType=n),e.theme&&(t.theme=e.theme),e.launcher&&(t.launcher=e.launcher),e.copy&&(t.copy=e.copy),e.sendButton&&(t.sendButton=e.sendButton),e.voiceRecognition&&(t.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(t.statusIndicator=e.statusIndicator),e.features&&(t.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(t.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(t.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(t.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(t.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(t.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(t.markdown=s)}if(e.layout){let s={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,d])=>{a!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,d])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(a==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([v,u])=>{v!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(c[v]=u)}),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&&(t.layout=s)}return t}function Cl(e){let n=Gi(e),r=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Bn}/dist/install.global.js" data-config='${r}'></script>`}function xl(e,n){let r=n==null?void 0:n.hooks,t=Ws(e),o=t!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Bn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Bn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Is(e," ")),s.push(...Ps(e," ",r)),s.push(...Hs(e," ")),s.push(...Bs(e," ")),s.push(...ur(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
|
|
136
|
+
`)}function Sl(e,n){let r=n==null?void 0:n.hooks,t=Gi(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
|
|
137
137
|
`).map((i,a)=>a===0?i:" "+i).join(`
|
|
138
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Bn}/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(${
|
|
139
|
-
`)}var
|
|
138
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Bn}/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(${fl});`),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(` ${Yi}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Yi}`),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(` ${Xi}`),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(` ${Xi}`),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 Nc=Ui;export{An as AgentWidgetClient,Qn as AgentWidgetSession,Tn as AttachmentManager,Ni as DEFAULT_DARK_THEME,Oi as DEFAULT_LIGHT_THEME,rt as DEFAULT_WIDGET_CONFIG,Bn as VERSION,Mn as attachHeaderToContainer,ts as buildComposer,Ai as buildDefaultHeader,Ti as buildExpandedHeader,dn as buildHeader,es as buildHeaderWithLayout,Ei as buildMinimalHeader,os as componentRegistry,ks as createActionManager,dr as createAgentExperience,Ra as createBubbleWithLayout,ir as createCSATFeedback,sl as createComponentMiddleware,nr as createComponentStreamParser,sa as createDirectivePostprocessor,la as createFlexibleJsonStreamParser,ha as createImagePart,_s as createJsonStreamParser,er as createLocalStorageAdapter,ys as createMarkdownProcessor,bs as createMarkdownProcessorFromConfig,Pi as createMessageActions,ar as createNPSFeedback,Ns as createPlainTextParser,Ds as createRegexJsonParser,ns as createStandardBubble,zs as createTextPart,Ln as createTypingIndicator,js as createXmlParser,Nc as default,Pn as defaultActionHandlers,Ls as defaultJsonActionParser,ra as directivePostprocessor,$s as escapeHtml,or as extractComponentDirectiveFromMessage,wa as fileToImagePart,En as generateAssistantMessageId,wl as generateCodeSnippet,ua as generateMessageId,Gn as generateUserMessageId,ga as getDisplayText,Mi as getHeaderLayout,fa as getImageParts,rr as hasComponentDirective,ma as hasImages,Js as headerLayouts,Ui as initAgentWidget,nl as isComponentDirectiveType,di as markdownPostprocessor,Qs as mergeWithDefaults,pa as normalizeContent,Ms as pluginRegistry,sr as renderComponentDirective,Ii as renderLoadingIndicatorWithFallback,va as validateImageFile};
|
|
140
140
|
//# sourceMappingURL=index.js.map
|