@runtypelabs/persona 1.44.0 → 1.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4,7 +4,7 @@
4
4
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},ks=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ws=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Is=()=>{var n;let e=La();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Ps=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=(0,sn.parse)(r,sn.STR|sn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Ls(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Ls(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Li=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Ls(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ls(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let a=(0,sn.parse)(s,sn.STR|sn.OBJ),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Hs=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var ka="https://api.runtype.com/v1/dispatch",ki="https://api.runtype.com",sr=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Wa(e){switch(e){case"json":return Ps;case"regex-json":return Is;case"xml":return Hs;case"plain":default:return Ws}}var yn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,t,o;this.apiUrl=(r=n.apiUrl)!=null?r:ka,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Wa(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var t;let r=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(r=(n=this.config).onSessionInit)==null||r.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"nps",rating:n,comment:r})}async dispatch(n,r){return this.isAgentMode()?this.dispatchAgent(n,r):this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let f=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:f}),f}let g=await this.buildPayload(n.messages),w=g.metadata?Object.fromEntries(Object.entries(g.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,c={sessionId:d.sessionId,messages:n.messages.filter(sr).map(f=>{var x,C,E;return{id:f.id,role:f.role,content:(E=(C=(x=f.contentParts)!=null?x:f.llmContent)!=null?C:f.rawContent)!=null?E:f.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...w&&Object.keys(w).length>0&&{metadata:w},...g.context&&{context:g.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c);let h=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c),signal:t.signal});if(!h.ok){let f=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let C=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:C}),C}if(h.status===429){let C=new Error(f.hint||"Message limit reached for this session.");throw r({type:"error",error:C}),C}let x=new Error(f.error||"Failed to send message");throw r({type:"error",error:x}),x}if(!h.body){let f=new Error("No response body received");throw r({type:"error",error:f}),f}r({type:"status",status:"connected"});try{await this.streamResponse(h.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let g=d instanceof Error?d:new Error(String(d));throw!g.message.includes("Session expired")&&!g.message.includes("Message limit")&&r({type:"error",error:g}),g}}async dispatchProxy(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(sr).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),t={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}return t}async buildPayload(n){let t={messages:n.slice().filter(sr).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(n,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,t){var pe,Ue,it,Tt,$t,Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt,Q,Oe,bt,Wt,Mt,j,Ze,We,z,R,he,ue,te,Le,Ne,q,de,Be,Je,st,Tn,rt,Jt,qn,an,Kt,F,ln,Gt,un,zn,Qt,Zt,Mn,Ln,ps,gs,ms,Un,kn,Ke,Jn,Kn,en,hs,fs,Yn,pn,tn,ws,vs,ys,Zs,gn,mn,tt,Wn,Vn,Xn,Gn,Ht,Nt,nn,Yt,Qn,hn,qt,bs,In,Cs,xs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,g=()=>a+d++,w=B=>{let ne=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,ae=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Xe=B.tools?B.tools.map(pt=>({...pt,chunks:pt.chunks?[...pt.chunks]:void 0})):void 0;return{...B,reasoning:ne,toolCall:ae,tools:Xe}},c=B=>{r({type:"message",message:w(B)})},h=null,f={current:null},x=new Map,C=new Map,E={lastId:null,byStep:new Map},S={lastId:null,byCall:new Map},k=B=>{if(B==null)return null;try{return String(B)}catch{return null}},V=B=>{var ne,ae,Xe,pt,Et;return k((Et=(pt=(Xe=(ae=(ne=B.stepId)!=null?ne:B.step_id)!=null?ae:B.step)!=null?Xe:B.parentId)!=null?pt:B.flowStepId)!=null?Et:B.flow_step_id)},y=B=>{var ne,ae,Xe,pt,Et,at,m;return k((m=(at=(Et=(pt=(Xe=(ae=(ne=B.callId)!=null?ne:B.call_id)!=null?ae:B.requestId)!=null?Xe:B.request_id)!=null?pt:B.toolCallId)!=null?Et:B.tool_call_id)!=null?at:B.stepId)!=null?m:B.step_id)},O=()=>h||(h={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g()},c(h),h),W=(B,ne)=>{E.lastId=ne,B&&E.byStep.set(B,ne)},H=(B,ne)=>{var Et;let ae=(Et=B.reasoningId)!=null?Et:B.id,Xe=V(B);if(ae){let at=String(ae);return W(Xe,at),at}if(Xe){let at=E.byStep.get(Xe);if(at)return E.lastId=at,at}if(E.lastId&&!ne)return E.lastId;if(!ne)return null;let pt=`reason-${g()}`;return W(Xe,pt),pt},oe=B=>{let ne=x.get(B);if(ne)return ne;let ae={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:B,status:"streaming",chunks:[]}};return x.set(B,ae),c(ae),ae},_=(B,ne)=>{S.lastId=ne,B&&S.byCall.set(B,ne)},le=(B,ne)=>{var Et;let ae=(Et=B.toolId)!=null?Et:B.id,Xe=y(B);if(ae){let at=String(ae);return _(Xe,at),at}if(Xe){let at=S.byCall.get(Xe);if(at)return S.lastId=at,at}if(S.lastId&&!ne)return S.lastId;if(!ne)return null;let pt=`tool-${g()}`;return _(Xe,pt),pt},X=B=>{let ne=C.get(B);if(ne)return ne;let ae={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:B,status:"pending"}};return C.set(B,ae),c(ae),ae},U=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let ne=Number(B);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let ae=Date.parse(B);if(!Number.isNaN(ae))return ae}return Date.now()},Se=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},N=new Map,re=new Map,D=null,Z=new Map,ve=(pe=this.config.iterationDisplay)!=null?pe:"separate";for(;;){let{done:B,value:ne}=await o.read();if(B)break;i+=s.decode(ne,{stream:!0});let ae=i.split(`
5
5
 
6
6
  `);i=(Ue=ae.pop())!=null?Ue:"";for(let Xe of ae){let pt=Xe.split(`
7
- `),Et="message",at="";for(let P of pt)P.startsWith("event:")?Et=P.replace("event:","").trim():P.startsWith("data:")&&(at+=P.replace("data:","").trim());if(!at)continue;let m;try{m=JSON.parse(at)}catch(P){r({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let _e=Et!=="message"?Et:(it=m.type)!=null?it:"message";if((Tt=this.onSSEEvent)==null||Tt.call(this,_e,m),this.parseSSEEvent){f.current=h;let P=await this.handleCustomSSEEvent(m,r,f,c,g);if(f.current&&!h&&(h=f.current),P)continue}if(_e==="reason_start"){let P=($t=H(m,!0))!=null?$t:`reason-${g()}`,v=oe(P);v.reasoning=(Fe=v.reasoning)!=null?Fe:{id:P,status:"streaming",chunks:[]},v.reasoning.startedAt=(ee=v.reasoning.startedAt)!=null?ee:U((Ae=m.startedAt)!=null?Ae:m.timestamp),v.reasoning.completedAt=void 0,v.reasoning.durationMs=void 0,v.streaming=!0,v.reasoning.status="streaming",c(v)}else if(_e==="reason_chunk"||_e==="reason_delta"){let P=($e=(ge=H(m,!1))!=null?ge:H(m,!0))!=null?$e:`reason-${g()}`,v=oe(P);v.reasoning=(Qe=v.reasoning)!=null?Qe:{id:P,status:"streaming",chunks:[]},v.reasoning.startedAt=(me=v.reasoning.startedAt)!=null?me:U((At=m.startedAt)!=null?At:m.timestamp);let T=(ut=(ct=(J=m.reasoningText)!=null?J:m.text)!=null?ct:m.delta)!=null?ut:"";if(T&&m.hidden!==!0&&v.reasoning.chunks.push(String(T)),v.reasoning.status=m.done?"complete":"streaming",m.done){v.reasoning.completedAt=U((ft=m.completedAt)!=null?ft:m.timestamp);let se=(Ot=v.reasoning.startedAt)!=null?Ot:Date.now();v.reasoning.durationMs=Math.max(0,((wt=v.reasoning.completedAt)!=null?wt:Date.now())-se)}v.streaming=v.reasoning.status!=="complete",c(v)}else if(_e==="reason_complete"){let P=(Ie=(Y=H(m,!1))!=null?Y:H(m,!0))!=null?Ie:`reason-${g()}`,v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U((vt=m.completedAt)!=null?vt:m.timestamp);let se=(yt=v.reasoning.startedAt)!=null?yt:Date.now();v.reasoning.durationMs=Math.max(0,((Q=v.reasoning.completedAt)!=null?Q:Date.now())-se),v.streaming=!1,c(v)}let T=V(m);T&&E.byStep.delete(T)}else if(_e==="tool_start"){let P=(Oe=le(m,!0))!=null?Oe:`tool-${g()}`,v=X(P),T=(bt=v.toolCall)!=null?bt:{id:P,status:"pending"};T.name=(Wt=m.toolName)!=null?Wt:T.name,T.status="running",m.args!==void 0?T.args=m.args:m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=(j=T.startedAt)!=null?j:U((Mt=m.startedAt)!=null?Mt:m.timestamp),T.completedAt=void 0,T.durationMs=void 0,v.toolCall=T,v.streaming=!0;let se=m.agentContext;(se||m.executionId)&&(v.agentMetadata={executionId:(Ze=se==null?void 0:se.executionId)!=null?Ze:m.executionId,iteration:(We=se==null?void 0:se.iteration)!=null?We:m.iteration}),c(v)}else if(_e==="tool_chunk"||_e==="tool_delta"){let P=(R=(z=le(m,!1))!=null?z:le(m,!0))!=null?R:`tool-${g()}`,v=X(P),T=(he=v.toolCall)!=null?he:{id:P,status:"running"};T.startedAt=(te=T.startedAt)!=null?te:U((ue=m.startedAt)!=null?ue:m.timestamp);let se=(q=(Ne=(Le=m.text)!=null?Le:m.delta)!=null?Ne:m.message)!=null?q:"";se&&(T.chunks=(de=T.chunks)!=null?de:[],T.chunks.push(String(se))),T.status="running",v.toolCall=T,v.streaming=!0;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(st=v.agentMetadata)!=null?st:{executionId:(Be=Ee==null?void 0:Ee.executionId)!=null?Be:m.executionId,iteration:(Je=Ee==null?void 0:Ee.iteration)!=null?Je:m.iteration}),c(v)}else if(_e==="tool_complete"){let P=(rt=(Tn=le(m,!1))!=null?Tn:le(m,!0))!=null?rt:`tool-${g()}`,v=X(P),T=(Jt=v.toolCall)!=null?Jt:{id:P,status:"running"};T.status="complete",m.result!==void 0&&(T.result=m.result),typeof m.duration=="number"&&(T.duration=m.duration),T.completedAt=U((qn=m.completedAt)!=null?qn:m.timestamp);let se=(an=m.duration)!=null?an:m.executionTime;if(typeof se=="number")T.durationMs=se;else{let Lt=(Kt=T.startedAt)!=null?Kt:Date.now();T.durationMs=Math.max(0,((F=T.completedAt)!=null?F:Date.now())-Lt)}v.toolCall=T,v.streaming=!1;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(un=v.agentMetadata)!=null?un:{executionId:(ln=Ee==null?void 0:Ee.executionId)!=null?ln:m.executionId,iteration:(Gt=Ee==null?void 0:Ee.iteration)!=null?Gt:m.iteration}),c(v);let Ye=y(m);Ye&&S.byCall.delete(Ye)}else if(_e==="step_chunk"||_e==="step_delta"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=O(),se=(Mn=(Zt=(Qt=(zn=m.text)!=null?zn:m.delta)!=null?Qt:m.content)!=null?Zt:m.chunk)!=null?Mn:"";if(se){let Ye=((Ln=re.get(T.id))!=null?Ln:"")+se;T.rawContent=Ye,N.has(T.id)||N.set(T.id,this.createStreamParser());let Lt=N.get(T.id),nt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(nt&&re.set(T.id,Ye),Lt.__isPlainTextParser===!0){T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T);continue}let gt=Lt.processChunk(Ye);if(gt instanceof Promise)gt.then(De=>{var lt;let qe=typeof De=="string"?De:(lt=De==null?void 0:De.text)!=null?lt:null;if(qe!==null&&qe.trim()!==""){let ze=h;ze&&ze.id===T.id&&(ze.content=qe,c(ze))}else if(!nt&&!Ye.trim().startsWith("<")){let ze=h;ze&&ze.id===T.id&&(ze.content+=se,re.delete(ze.id),N.delete(ze.id),ze.rawContent=void 0,c(ze))}}).catch(()=>{T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T)});else{let De=typeof gt=="string"?gt:(ps=gt==null?void 0:gt.text)!=null?ps:null;De!==null&&De.trim()!==""?(T.content=De,c(T)):!nt&&!Ye.trim().startsWith("<")&&(T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T))}}if(m.isComplete){let Ee=(ms=(gs=m.result)==null?void 0:gs.response)!=null?ms:T.content;if(Ee){let Ye=re.get(T.id),Lt=Ye!=null?Ye:Se(Ee);T.rawContent=Lt;let nt=N.get(T.id),Ct=null,gt=!1;if(nt&&(Ct=nt.getExtractedText(),Ct===null&&(Ct=ks(Lt)),Ct===null)){let De=nt.processChunk(Lt);De instanceof Promise?(gt=!0,De.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===T.id&&(xt.content=lt,xt.streaming=!1,N.delete(xt.id),re.delete(xt.id),c(xt))}})):Ct=typeof De=="string"?De:(Un=De==null?void 0:De.text)!=null?Un:null}if(!gt){Ct!==null&&Ct.trim()!==""?T.content=Ct:re.has(T.id)||(T.content=Se(Ee));let De=N.get(T.id);if(De){let qe=(kn=De.close)==null?void 0:kn.call(De);qe instanceof Promise&&qe.catch(()=>{}),N.delete(T.id)}re.delete(T.id),T.streaming=!1,c(T)}}}}else if(_e==="step_complete"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=(Ke=m.result)==null?void 0:Ke.response,se=O();if(T!=null){let Ee=N.get(se.id),Ye=!1,Lt=!1;if(Ee){let nt=Ee.getExtractedText(),Ct=re.get(se.id),gt=Ct!=null?Ct:Se(T);if(se.rawContent=gt,nt!==null&&nt.trim()!=="")se.content=nt,Ye=!0;else{let De=ks(gt);if(De!==null)se.content=De,Ye=!0;else{let qe=Ee.processChunk(gt);if(qe instanceof Promise)Lt=!0,qe.then(lt=>{var xt;let ze=typeof lt=="string"?lt:(xt=lt==null?void 0:lt.text)!=null?xt:null;if(ze!==null&&ze.trim()!==""){let Rt=h;Rt&&Rt.id===se.id&&(Rt.content=ze,Rt.streaming=!1,N.delete(Rt.id),re.delete(Rt.id),c(Rt))}else{let Rt=Ee.getExtractedText(),_t=h;_t&&_t.id===se.id&&(Rt!==null&&Rt.trim()!==""?_t.content=Rt:re.has(_t.id)||(_t.content=Se(T)),_t.streaming=!1,N.delete(_t.id),re.delete(_t.id),c(_t))}});else{let lt=typeof qe=="string"?qe:(Jn=qe==null?void 0:qe.text)!=null?Jn:null;if(lt!==null&&lt.trim()!=="")se.content=lt,Ye=!0;else{let ze=Ee.getExtractedText();ze!==null&&ze.trim()!==""&&(se.content=ze,Ye=!0)}}}}}if(!Lt){if(!se.rawContent){let nt=re.get(se.id);se.rawContent=nt!=null?nt:Se(T)}if(!Ye&&!re.has(se.id)&&(se.content=Se(T)),Ee){let nt=(Kn=Ee.close)==null?void 0:Kn.call(Ee);nt instanceof Promise&&nt.catch(()=>{})}N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}}else N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}else if(_e==="flow_complete"){let P=(en=m.result)==null?void 0:en.response;if(P!=null){let v=O(),T=re.get(v.id),se=T!=null?T:Se(P);v.rawContent=se;let Ee=Se(P),Ye=N.get(v.id);if(Ye){let Ct=ks(se);if(Ct!==null)Ee=Ct;else{let gt=Ye.processChunk(se);gt instanceof Promise&&gt.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===v.id&&(xt.content=lt,xt.streaming=!1,c(xt))}});let De=Ye.getExtractedText();De!==null&&(Ee=De)}}N.delete(v.id),re.delete(v.id);let Lt=Ee!==v.content,nt=v.streaming!==!1;Lt&&(v.content=Ee),v.streaming=!1,(Lt||nt)&&c(v)}else if(h!==null){let v=h;N.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,c(v))}r({type:"status",status:"idle"})}else if(_e==="agent_start")D={executionId:m.executionId,agentId:(hs=m.agentId)!=null?hs:"virtual",agentName:(fs=m.agentName)!=null?fs:"",status:"running",currentIteration:0,maxIterations:(Yn=m.maxIterations)!=null?Yn:1,startedAt:U(m.startedAt)};else if(_e==="agent_iteration_start"){if(D&&(D.currentIteration=m.iteration),ve==="separate"&&m.iteration>1){let P=h;P&&(P.streaming=!1,c(P),Z.set(m.iteration-1,P),h=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(m.contentType==="text"){let P=O();P.content+=(pn=m.delta)!=null?pn:"",P.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:D==null?void 0:D.agentName},c(P)}else if(m.contentType==="thinking"){let P=(tn=m.turnId)!=null?tn:`agent-think-${m.iteration}`,v=oe(P);v.reasoning=(ws=v.reasoning)!=null?ws:{id:P,status:"streaming",chunks:[]},v.reasoning.chunks.push((vs=m.delta)!=null?vs:""),v.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},c(v)}else if(m.contentType==="tool_input"){let P=(ys=m.toolCallId)!=null?ys:S.lastId;if(P){let v=C.get(P);v!=null&&v.toolCall&&(v.toolCall.chunks=(Zs=v.toolCall.chunks)!=null?Zs:[],v.toolCall.chunks.push((gn=m.delta)!=null?gn:""),c(v))}}}else if(_e==="agent_turn_complete"){let P=m.turnId;if(P){let v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U(m.completedAt);let T=(mn=v.reasoning.startedAt)!=null?mn:Date.now();v.reasoning.durationMs=Math.max(0,((tt=v.reasoning.completedAt)!=null?tt:Date.now())-T),v.streaming=!1,c(v)}}}else if(_e==="agent_tool_start"){let P=(Wn=m.toolCallId)!=null?Wn:`agent-tool-${g()}`;_(y(m),P);let v=X(P),T=(Vn=v.toolCall)!=null?Vn:{id:P,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};T.name=(Xn=m.toolName)!=null?Xn:T.name,T.status="running",m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=U((Gn=m.startedAt)!=null?Gn:m.timestamp),v.toolCall=T,v.streaming=!0,v.agentMetadata={executionId:m.executionId,iteration:m.iteration},c(v)}else if(_e==="agent_tool_delta"){let P=(Ht=m.toolCallId)!=null?Ht:S.lastId;if(P){let v=(Nt=C.get(P))!=null?Nt:X(P);v.toolCall&&(v.toolCall.chunks=(nn=v.toolCall.chunks)!=null?nn:[],v.toolCall.chunks.push((Yt=m.delta)!=null?Yt:""),v.toolCall.status="running",v.streaming=!0,c(v))}}else if(_e==="agent_tool_complete"){let P=(Qn=m.toolCallId)!=null?Qn:S.lastId;if(P){let v=(hn=C.get(P))!=null?hn:X(P);if(v.toolCall){v.toolCall.status="complete",m.result!==void 0&&(v.toolCall.result=m.result),typeof m.executionTime=="number"&&(v.toolCall.durationMs=m.executionTime),v.toolCall.completedAt=U((qt=m.completedAt)!=null?qt:m.timestamp),v.streaming=!1,c(v);let T=y(m);T&&S.byCall.delete(T)}}}else if(_e!=="agent_iteration_complete")if(_e==="agent_reflection"||_e==="agent_reflect"){let P=`agent-reflection-${m.executionId}-${m.iteration}`,v={id:P,role:"assistant",content:(bs=m.reflection)!=null?bs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:g(),reasoning:{id:P,status:"complete",chunks:[(In=m.reflection)!=null?In:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};c(v)}else if(_e==="agent_complete"){D&&(D.status=m.success?"complete":"error",D.completedAt=U(m.completedAt),D.stopReason=m.stopReason);let P=h;P&&(P.streaming=!1,c(P)),r({type:"status",status:"idle"})}else if(_e==="agent_error"){let P=typeof m.error=="string"?m.error:(xs=(Cs=m.error)==null?void 0:Cs.message)!=null?xs:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",P):r({type:"error",error:new Error(P)})}else _e==="agent_ping"||_e==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}};function Wi(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Pn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function bn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Hn=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,t,o,s,i,a,d;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(t=n.message.agentMetadata.agentName)!=null?t:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new yn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(r=(n=this.callbacks).onError)==null||r.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new yn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:t,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:g=!1}=n,c={id:i!=null?i:r==="user"?Pn():r==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:g,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(c),c}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let t of n){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:g,sequence:w,streaming:c=!1}=t,f={id:d!=null?d:o==="user"?Pn():o==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:g!=null?g:new Date().toISOString(),sequence:w!=null?w:this.nextSequence(),streaming:c,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(f)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var g,w,c,h,f;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(g=this.abortController)==null||g.abort();let o=Pn(),s=bn(),i={id:o,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(c=(w=this.callbacks).onError)==null||c.call(w,x):(f=(h=this.callbacks).onError)==null||f.call(h,new Error(String(x))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=bn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(g){let w={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(w),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,g):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(g)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,t)=>{var d,g;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(g=t.sequence)!=null?g:0;return i!==a?i-a:r.id.localeCompare(t.id)})}};var p=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};var Ia=xa(require("lucide"),1),ie=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ia[o];return s?Pa(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Pa(e,n,r,t){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([g,w])=>{g!=="stroke"&&d.setAttribute(g,String(w))}),o.appendChild(d)}}}),o}function Ii(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pi(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Hi(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Bi(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Bs(e){return{type:"text",text:e}}function Ri(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Fi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function $i(e,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Oi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ha=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],cn=[...Oi,...Ha];function Ba(e){return Oi.includes(e)||e.startsWith("image/")}function Rs(e){return Ba(e.type)}async function Ni(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;Rs(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function Di(e,n=cn,r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ra(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function ji(e,n){let r=Ra(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var Fs={allowedTypes:cn,maxFileSize:10*1024*1024,maxFiles:4};function Fa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $a(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Cn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,t,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Fs.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Fs.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Fs.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Fs.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,o,s,i,a,d,g;if(!n||n.length===0)return;let r=Array.from(n);for(let w of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,w,"count");continue}let c=Di(w,this.config.allowedTypes,this.config.maxFileSize);if(!c.valid){let h=(s=c.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,w,h);continue}try{let h=await Ni(w),f=Rs(w)?URL.createObjectURL(w):null,x={id:Fa(),file:w,previewUrl:f,contentPart:h};this.attachments.push(x),this.renderPreview(x)}catch(h){console.error("[AttachmentManager] Failed to process file:",h)}}this.updatePreviewsVisibility(),(g=(d=this.config).onAttachmentsChange)==null||g.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(d=>d.id===n);if(r===-1)return;let t=this.attachments[r];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=Rs(n.file),t=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",r&&n.previewUrl){let i=p("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=p("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=$a(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let g=p("span");g.textContent=ji(n.file.type,n.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--cw-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",i.appendChild(g),t.appendChild(i)}let o=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(o),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:r})}};var rr=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Oa=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",r=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||rr()==="dark"?t:r},_i=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(rr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(rr());r.addEventListener?(r.addEventListener("change",t),n.push(()=>r.removeEventListener("change",t))):r.addListener&&(r.addListener(t),n.push(()=>r.removeListener(t)))}return()=>{n.forEach(r=>r())}},$s=(e,n)=>{let r=Oa(n);Object.entries(r).forEach(([t,o])=>{if(o==null||o==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(o))})};var qi=require("idiomorph"),zi=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;qi.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&t&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ut={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var is=(e,n)=>{let r=p("button");r.type="button",r.innerHTML=`
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=(Tn=le(m,!1))!=null?Tn:le(m,!0))!=null?rt:`tool-${g()}`,v=X(P),T=(Jt=v.toolCall)!=null?Jt:{id:P,status:"running"};T.status="complete",m.result!==void 0&&(T.result=m.result),typeof m.duration=="number"&&(T.duration=m.duration),T.completedAt=U((qn=m.completedAt)!=null?qn:m.timestamp);let se=(an=m.duration)!=null?an:m.executionTime;if(typeof se=="number")T.durationMs=se;else{let Lt=(Kt=T.startedAt)!=null?Kt:Date.now();T.durationMs=Math.max(0,((F=T.completedAt)!=null?F:Date.now())-Lt)}v.toolCall=T,v.streaming=!1;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(un=v.agentMetadata)!=null?un:{executionId:(ln=Ee==null?void 0:Ee.executionId)!=null?ln:m.executionId,iteration:(Gt=Ee==null?void 0:Ee.iteration)!=null?Gt:m.iteration}),c(v);let Ye=y(m);Ye&&S.byCall.delete(Ye)}else if(_e==="step_chunk"||_e==="step_delta"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=O(),se=(Mn=(Zt=(Qt=(zn=m.text)!=null?zn:m.delta)!=null?Qt:m.content)!=null?Zt:m.chunk)!=null?Mn:"";if(se){let Ye=((Ln=re.get(T.id))!=null?Ln:"")+se;T.rawContent=Ye,N.has(T.id)||N.set(T.id,this.createStreamParser());let Lt=N.get(T.id),nt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(nt&&re.set(T.id,Ye),Lt.__isPlainTextParser===!0){T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T);continue}let gt=Lt.processChunk(Ye);if(gt instanceof Promise)gt.then(De=>{var lt;let qe=typeof De=="string"?De:(lt=De==null?void 0:De.text)!=null?lt:null;if(qe!==null&&qe.trim()!==""){let ze=h;ze&&ze.id===T.id&&(ze.content=qe,c(ze))}else if(!nt&&!Ye.trim().startsWith("<")){let ze=h;ze&&ze.id===T.id&&(ze.content+=se,re.delete(ze.id),N.delete(ze.id),ze.rawContent=void 0,c(ze))}}).catch(()=>{T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T)});else{let De=typeof gt=="string"?gt:(ps=gt==null?void 0:gt.text)!=null?ps:null;De!==null&&De.trim()!==""?(T.content=De,c(T)):!nt&&!Ye.trim().startsWith("<")&&(T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T))}}if(m.isComplete){let Ee=(ms=(gs=m.result)==null?void 0:gs.response)!=null?ms:T.content;if(Ee){let Ye=re.get(T.id),Lt=Ye!=null?Ye:Se(Ee);T.rawContent=Lt;let nt=N.get(T.id),Ct=null,gt=!1;if(nt&&(Ct=nt.getExtractedText(),Ct===null&&(Ct=ks(Lt)),Ct===null)){let De=nt.processChunk(Lt);De instanceof Promise?(gt=!0,De.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===T.id&&(xt.content=lt,xt.streaming=!1,N.delete(xt.id),re.delete(xt.id),c(xt))}})):Ct=typeof De=="string"?De:(Un=De==null?void 0:De.text)!=null?Un:null}if(!gt){Ct!==null&&Ct.trim()!==""?T.content=Ct:re.has(T.id)||(T.content=Se(Ee));let De=N.get(T.id);if(De){let qe=(kn=De.close)==null?void 0:kn.call(De);qe instanceof Promise&&qe.catch(()=>{}),N.delete(T.id)}re.delete(T.id),T.streaming=!1,c(T)}}}}else if(_e==="step_complete"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=(Ke=m.result)==null?void 0:Ke.response,se=O();if(T!=null){let Ee=N.get(se.id),Ye=!1,Lt=!1;if(Ee){let nt=Ee.getExtractedText(),Ct=re.get(se.id),gt=Ct!=null?Ct:Se(T);if(se.rawContent=gt,nt!==null&&nt.trim()!=="")se.content=nt,Ye=!0;else{let De=ks(gt);if(De!==null)se.content=De,Ye=!0;else{let qe=Ee.processChunk(gt);if(qe instanceof Promise)Lt=!0,qe.then(lt=>{var xt;let ze=typeof lt=="string"?lt:(xt=lt==null?void 0:lt.text)!=null?xt:null;if(ze!==null&&ze.trim()!==""){let Rt=h;Rt&&Rt.id===se.id&&(Rt.content=ze,Rt.streaming=!1,N.delete(Rt.id),re.delete(Rt.id),c(Rt))}else{let Rt=Ee.getExtractedText(),_t=h;_t&&_t.id===se.id&&(Rt!==null&&Rt.trim()!==""?_t.content=Rt:re.has(_t.id)||(_t.content=Se(T)),_t.streaming=!1,N.delete(_t.id),re.delete(_t.id),c(_t))}});else{let lt=typeof qe=="string"?qe:(Jn=qe==null?void 0:qe.text)!=null?Jn:null;if(lt!==null&&lt.trim()!=="")se.content=lt,Ye=!0;else{let ze=Ee.getExtractedText();ze!==null&&ze.trim()!==""&&(se.content=ze,Ye=!0)}}}}}if(!Lt){if(!se.rawContent){let nt=re.get(se.id);se.rawContent=nt!=null?nt:Se(T)}if(!Ye&&!re.has(se.id)&&(se.content=Se(T)),Ee){let nt=(Kn=Ee.close)==null?void 0:Kn.call(Ee);nt instanceof Promise&&nt.catch(()=>{})}N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}}else N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}else if(_e==="flow_complete"){let P=(en=m.result)==null?void 0:en.response;if(P!=null){let v=O(),T=re.get(v.id),se=T!=null?T:Se(P);v.rawContent=se;let Ee=Se(P),Ye=N.get(v.id);if(Ye){let Ct=ks(se);if(Ct!==null)Ee=Ct;else{let gt=Ye.processChunk(se);gt instanceof Promise&&gt.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===v.id&&(xt.content=lt,xt.streaming=!1,c(xt))}});let De=Ye.getExtractedText();De!==null&&(Ee=De)}}N.delete(v.id),re.delete(v.id);let Lt=Ee!==v.content,nt=v.streaming!==!1;Lt&&(v.content=Ee),v.streaming=!1,(Lt||nt)&&c(v)}else if(h!==null){let v=h;N.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,c(v))}r({type:"status",status:"idle"})}else if(_e==="agent_start")D={executionId:m.executionId,agentId:(hs=m.agentId)!=null?hs:"virtual",agentName:(fs=m.agentName)!=null?fs:"",status:"running",currentIteration:0,maxIterations:(Yn=m.maxIterations)!=null?Yn:1,startedAt:U(m.startedAt)};else if(_e==="agent_iteration_start"){if(D&&(D.currentIteration=m.iteration),ve==="separate"&&m.iteration>1){let P=h;P&&(P.streaming=!1,c(P),Z.set(m.iteration-1,P),h=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(m.contentType==="text"){let P=O();P.content+=(pn=m.delta)!=null?pn:"",P.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:D==null?void 0:D.agentName},c(P)}else if(m.contentType==="thinking"){let P=(tn=m.turnId)!=null?tn:`agent-think-${m.iteration}`,v=oe(P);v.reasoning=(ws=v.reasoning)!=null?ws:{id:P,status:"streaming",chunks:[]},v.reasoning.chunks.push((vs=m.delta)!=null?vs:""),v.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},c(v)}else if(m.contentType==="tool_input"){let P=(ys=m.toolCallId)!=null?ys:S.lastId;if(P){let v=C.get(P);v!=null&&v.toolCall&&(v.toolCall.chunks=(Zs=v.toolCall.chunks)!=null?Zs:[],v.toolCall.chunks.push((gn=m.delta)!=null?gn:""),c(v))}}}else if(_e==="agent_turn_complete"){let P=m.turnId;if(P){let v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U(m.completedAt);let T=(mn=v.reasoning.startedAt)!=null?mn:Date.now();v.reasoning.durationMs=Math.max(0,((tt=v.reasoning.completedAt)!=null?tt:Date.now())-T),v.streaming=!1,c(v)}}}else if(_e==="agent_tool_start"){let P=(Wn=m.toolCallId)!=null?Wn:`agent-tool-${g()}`;_(y(m),P);let v=X(P),T=(Vn=v.toolCall)!=null?Vn:{id:P,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};T.name=(Xn=m.toolName)!=null?Xn:T.name,T.status="running",m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=U((Gn=m.startedAt)!=null?Gn:m.timestamp),v.toolCall=T,v.streaming=!0,v.agentMetadata={executionId:m.executionId,iteration:m.iteration},c(v)}else if(_e==="agent_tool_delta"){let P=(Ht=m.toolCallId)!=null?Ht:S.lastId;if(P){let v=(Nt=C.get(P))!=null?Nt:X(P);v.toolCall&&(v.toolCall.chunks=(nn=v.toolCall.chunks)!=null?nn:[],v.toolCall.chunks.push((Yt=m.delta)!=null?Yt:""),v.toolCall.status="running",v.streaming=!0,c(v))}}else if(_e==="agent_tool_complete"){let P=(Qn=m.toolCallId)!=null?Qn:S.lastId;if(P){let v=(hn=C.get(P))!=null?hn:X(P);if(v.toolCall){v.toolCall.status="complete",m.result!==void 0&&(v.toolCall.result=m.result),typeof m.executionTime=="number"&&(v.toolCall.durationMs=m.executionTime),v.toolCall.completedAt=U((qt=m.completedAt)!=null?qt:m.timestamp),v.streaming=!1,c(v);let T=y(m);T&&S.byCall.delete(T)}}}else if(_e!=="agent_iteration_complete")if(_e==="agent_reflection"||_e==="agent_reflect"){let P=`agent-reflection-${m.executionId}-${m.iteration}`,v={id:P,role:"assistant",content:(bs=m.reflection)!=null?bs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:g(),reasoning:{id:P,status:"complete",chunks:[(In=m.reflection)!=null?In:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};c(v)}else if(_e==="agent_complete"){D&&(D.status=m.success?"complete":"error",D.completedAt=U(m.completedAt),D.stopReason=m.stopReason);let P=h;P&&(P.streaming=!1,c(P)),r({type:"status",status:"idle"})}else if(_e==="agent_error"){let P=typeof m.error=="string"?m.error:(xs=(Cs=m.error)==null?void 0:Cs.message)!=null?xs:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",P):r({type:"error",error:new Error(P)})}else _e==="agent_ping"||_e==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}};function Wi(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Pn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function bn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Hn=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,t,o,s,i,a,d;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(t=n.message.agentMetadata.agentName)!=null?t:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new yn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(r=(n=this.callbacks).onError)==null||r.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new yn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:t,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:g=!1}=n,c={id:i!=null?i:r==="user"?Pn():r==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:g,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(c),c}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let t of n){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:g,sequence:w,streaming:c=!1}=t,f={id:d!=null?d:o==="user"?Pn():o==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:g!=null?g:new Date().toISOString(),sequence:w!=null?w:this.nextSequence(),streaming:c,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(f)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var g,w,c,h,f;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(g=this.abortController)==null||g.abort();let o=Pn(),s=bn(),i={id:o,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(c=(w=this.callbacks).onError)==null||c.call(w,x):(f=(h=this.callbacks).onError)==null||f.call(h,new Error(String(x))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=bn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(g){let w={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(w),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,g):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(g)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,t)=>{var d,g;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(g=t.sequence)!=null?g:0;return i!==a?i-a:r.id.localeCompare(t.id)})}};var p=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};var Ia=xa(require("lucide"),1),ie=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ia[o];return s?Pa(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Pa(e,n,r,t){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([g,w])=>{g!=="stroke"&&d.setAttribute(g,String(w))}),o.appendChild(d)}}}),o}function Ii(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pi(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Hi(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Bi(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Bs(e){return{type:"text",text:e}}function Ri(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Fi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function $i(e,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Oi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ha=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],cn=[...Oi,...Ha];function Ba(e){return Oi.includes(e)||e.startsWith("image/")}function Rs(e){return Ba(e.type)}async function Ni(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;Rs(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function Di(e,n=cn,r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ra(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function ji(e,n){let r=Ra(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var Fs={allowedTypes:cn,maxFileSize:10*1024*1024,maxFiles:4};function Fa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $a(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Cn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,t,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Fs.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Fs.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Fs.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Fs.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,o,s,i,a,d,g;if(!n||n.length===0)return;let r=Array.from(n);for(let w of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,w,"count");continue}let c=Di(w,this.config.allowedTypes,this.config.maxFileSize);if(!c.valid){let h=(s=c.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,w,h);continue}try{let h=await Ni(w),f=Rs(w)?URL.createObjectURL(w):null,x={id:Fa(),file:w,previewUrl:f,contentPart:h};this.attachments.push(x),this.renderPreview(x)}catch(h){console.error("[AttachmentManager] Failed to process file:",h)}}this.updatePreviewsVisibility(),(g=(d=this.config).onAttachmentsChange)==null||g.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(d=>d.id===n);if(r===-1)return;let t=this.attachments[r];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=Rs(n.file),t=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",r&&n.previewUrl){let i=p("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=p("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=$a(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let g=p("span");g.textContent=ji(n.file.type,n.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--cw-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",i.appendChild(g),t.appendChild(i)}let o=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(o),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:r})}};var rr=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Oa=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",r=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||rr()==="dark"?t:r},_i=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(rr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(rr());r.addEventListener?(r.addEventListener("change",t),n.push(()=>r.removeEventListener("change",t))):r.addListener&&(r.addListener(t),n.push(()=>r.removeListener(t)))}return()=>{n.forEach(r=>r())}},$s=(e,n)=>{let r=Oa(n);Object.entries(r).forEach(([t,o])=>{if(o==null||o==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(o))})};var qi=require("idiomorph"),zi=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;qi.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&t&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ut={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var is=(e,n)=>{let r=p("button");r.type="button",r.innerHTML=`
8
8
  <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
10
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -57,7 +57,7 @@
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!I){let fn="max-height: -moz-available !important; max-height: stretch !important;",wn=l?"":"padding-top: 1.25em !important;";Fe.style.cssText+=fn+wn}};Tn(),$s(e,t);let rt=[];X&&rt.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),Z==null||Z.destroy(),Z=null,D==null||D.destroy(),D=null,N=null});let Jt=null,qn=()=>{Jt&&(Jt(),Jt=null),t.colorScheme==="auto"&&(Jt=_i(()=>{$s(e,t)}))};qn(),rt.push(()=>{Jt&&(Jt(),Jt=null)});let an=Gi(At),Kt=null,F,ln=!1,Gt=!0,un=0,zn=0,Qt=null,Zt=!1,Mn=0,Ln=!1,ps=125,gs=2e3,ms=5,Un=50,kn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Jn=(Hr=(Pr=t.voiceRecognition)==null?void 0:Pr.autoResume)!=null?Hr:!1,Kn=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},en=()=>{c(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},hs=()=>{var L,A;if(((L=t.voiceRecognition)==null?void 0:L.enabled)===!1)return;let l=br(a.voiceState),u=!!l.active,b=Number((A=l.timestamp)!=null?A:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-b<il&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,hn("restore"))},1e3)},fs=()=>F?ra(F.getMessages()).filter(l=>!l.__skipPersist):[];function Yn(l){if(!(i!=null&&i.save))return;let b={messages:l?ra(l):F?fs():[],metadata:a};try{let L=i.save(b);L instanceof Promise&&L.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(L){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)}}let pn=(l=!1)=>{if(!Gt)return;let u=Date.now();Zt&&u<Mn&&!l||(Zt&&u>=Mn&&(Zt=!1),!(!l&&!ln)&&(u-zn<ps||(zn=u,Qt&&cancelAnimationFrame(Qt),Qt=requestAnimationFrame(()=>{Zt||!Gt||(Ln=!0,$e.scrollTop=$e.scrollHeight,un=$e.scrollTop,requestAnimationFrame(()=>{Ln=!1}),Qt=null)}))))},tn=null,ws=()=>Fe.querySelector("#persona-scroll-container")||$e,vs=(l,u=500)=>{let b=l.scrollTop,L=l.clientHeight,A=l.scrollHeight,$=A-b;if(b+L>=A-2||Math.abs($)<5)return;tn!==null&&(cancelAnimationFrame(tn),tn=null);let ce=performance.now(),be=Ce=>1-Math.pow(1-Ce,3),Te=Ce=>{let Pe=l.scrollHeight;Pe!==A&&(A=Pe,$=A-b);let G=Ce-ce,I=Math.min(G/u,1),we=be(I),xe=b+$*we;l.scrollTop=xe,I<1?tn=requestAnimationFrame(Te):(l.scrollTop=l.scrollHeight,tn=null)};tn=requestAnimationFrame(Te)},ys=l=>{let u=new Map;l.forEach(b=>{let L=kn.get(b.id);u.set(b.id,{streaming:b.streaming,role:b.role}),!L&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(L!=null&&L.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b)}),kn.clear(),u.forEach((b,L)=>{kn.set(L,b)})},gn=(l,u,b)=>{var Te,Ce,Pe,G;let L=document.createElement("div"),$=(()=>{var we;let I=o.find(xe=>xe.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((we=t.loadingIndicator)!=null&&we.render)return t.loadingIndicator.render})();u.forEach(I=>{var mt,It;let we=null,xe=o.find(K=>!!(I.variant==="reasoning"&&K.renderReasoning||I.variant==="tool"&&K.renderToolCall||!I.variant&&K.renderMessage)),Ve=(mt=t.layout)==null?void 0:mt.messages;if(xe)if(I.variant==="reasoning"&&I.reasoning&&xe.renderReasoning){if(!_)return;we=xe.renderReasoning({message:I,defaultRenderer:()=>ur(I),config:t})}else if(I.variant==="tool"&&I.toolCall&&xe.renderToolCall){if(!le)return;we=xe.renderToolCall({message:I,defaultRenderer:()=>pr(I,t),config:t})}else xe.renderMessage&&(we=xe.renderMessage({message:I,defaultRenderer:()=>{let K=Fn(I,b,Ve,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t});return I.role!=="user"&&mr(K,I,t,F),K},config:t}));if(!we&&I.role==="assistant"&&!I.variant&&t.enableComponentStreaming!==!1&&qs(I)){let je=zs(I);if(je){let Vt=_s(je,{config:t,message:I,transform:b});if(Vt){let zt=document.createElement("div");if(zt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),zt.id=`bubble-${I.id}`,zt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let dn=document.createElement("div");dn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",dn.innerHTML=b({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),zt.appendChild(dn)}zt.appendChild(Vt),we=zt}}}if(!we)if(I.variant==="reasoning"&&I.reasoning){if(!_)return;we=ur(I)}else if(I.variant==="tool"&&I.toolCall){if(!le)return;we=pr(I,t)}else{let K=(It=t.layout)==null?void 0:It.messages;K!=null&&K.renderUserMessage&&I.role==="user"?we=K.renderUserMessage({message:I,config:t,streaming:!!I.streaming}):K!=null&&K.renderAssistantMessage&&I.role==="assistant"?we=K.renderAssistantMessage({message:I,config:t,streaming:!!I.streaming}):we=Fn(I,b,K,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t}),I.role!=="user"&&we&&mr(we,I,t,F)}let He=document.createElement("div");He.className="tvw-flex",He.id=`wrapper-${I.id}`,He.setAttribute("data-wrapper-id",I.id),I.role==="user"&&He.classList.add("tvw-justify-end"),He.appendChild(we),L.appendChild(He)});let ye=u.some(I=>I.role==="assistant"&&I.streaming),ce=u[u.length-1],be=(ce==null?void 0:ce.role)==="assistant"&&!ce.streaming;if(ln&&u.some(I=>I.role==="user")&&!ye&&!be){let I={config:t,streaming:!0,location:"standalone",defaultRenderer:Sn},we=o.find(Ve=>Ve.renderLoadingIndicator),xe=null;if(we!=null&&we.renderLoadingIndicator&&(xe=we.renderLoadingIndicator(I)),xe===null&&((Te=t.loadingIndicator)!=null&&Te.render)&&(xe=t.loadingIndicator.render(I)),xe===null&&(xe=Sn()),xe){let Ve=document.createElement("div"),He=((Ce=t.loadingIndicator)==null?void 0:Ce.showBubble)!==!1;Ve.className=He?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(xe);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Ve),L.appendChild(mt)}}if(!ln&&u.length>0){let I=u[u.length-1],we={config:t,lastMessage:I,messageCount:u.length},xe=o.find(He=>He.renderIdleIndicator),Ve=null;if(xe!=null&&xe.renderIdleIndicator&&(Ve=xe.renderIdleIndicator(we)),Ve===null&&((Pe=t.loadingIndicator)!=null&&Pe.renderIdle)&&(Ve=t.loadingIndicator.renderIdle(we)),Ve){let He=document.createElement("div"),mt=((G=t.loadingIndicator)==null?void 0:G.showBubble)!==!1;He.className=mt?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(Ve);let It=document.createElement("div");It.className="tvw-flex",It.id="wrapper-idle-indicator",It.setAttribute("data-wrapper-id","idle-indicator"),It.appendChild(He),L.appendChild(It)}}zi(l,L),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=ws();vs(I)})})},mn=()=>{C&&(y?(Fe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-95","tvw-opacity-0"),Ae.classList.add("tvw-scale-100","tvw-opacity-100"),ne?ne.element.style.display="none":ae&&(ae.style.display="none")):(Fe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-100","tvw-opacity-100"),Ae.classList.add("tvw-scale-95","tvw-opacity-0"),ne?ne.element.style.display="":ae&&(ae.style.display="")))},tt=(l,u="user")=>{if(!C||y===l)return;let b=y;y=l,mn(),y&&(Xe(),pn(!0));let L={open:y,source:u,timestamp:Date.now()};y&&!b?s.emit("widget:opened",L):!y&&b&&s.emit("widget:closed",L),s.emit("widget:state",{open:y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()})},Wn=l=>{J.disabled=l,j&&(j.disabled=l),an.buttons.forEach(u=>{u.disabled=l})},Vn=()=>{var A,$,ye,ce,be,Te,Ce,Pe,G,I,we,xe,Ve,He;Ot.textContent=($=(A=t.copy)==null?void 0:A.welcomeTitle)!=null?$:"Hello \u{1F44B}",wt.textContent=(ce=(ye=t.copy)==null?void 0:ye.welcomeSubtitle)!=null?ce:"Ask anything about your account or products.",me.placeholder=(Te=(be=t.copy)==null?void 0:be.inputPlaceholder)!=null?Te:"How can I help...",((Pe=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?Pe:!1)||(J.textContent=(I=(G=t.copy)==null?void 0:G.sendButtonLabel)!=null?I:"Send");let u=(xe=(we=t.theme)==null?void 0:we.inputFontFamily)!=null?xe:"sans-serif",b=(He=(Ve=t.theme)==null?void 0:Ve.inputFontWeight)!=null?He:"400",L=mt=>{switch(mt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};me.style.fontFamily=L(u),me.style.fontWeight=b};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{c(u=>({...u,sessionId:l}))}}),F=new Hn(t,{onMessagesChanged(l){gn(Qe,l,oe),F&&(l.some(A=>A.role==="user")?an.render([],F,me,l):an.render(t.suggestionChips,F,me,l,t.suggestionChipsConfig)),pn(!ln),ys(l);let u=[...l].reverse().find(L=>L.role==="user"),b=Ke.lastUserMessageId;u&&u.id!==b&&(Ke.lastUserMessageId=u.id,s.emit("user:message",u)),Ke.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Yn(l)},onStatusChanged(l){var L;let u=(L=t.statusIndicator)!=null?L:{},b=A=>{var $,ye,ce,be;return A==="idle"?($=u.idleText)!=null?$:Pt.idle:A==="connecting"?(ye=u.connectingText)!=null?ye:Pt.connecting:A==="connected"?(ce=u.connectedText)!=null?ce:Pt.connected:A==="error"?(be=u.errorText)!=null?be:Pt.error:Pt[A]};ft.textContent=b(l)},onStreamingChanged(l){ln=l,Wn(l),F&&gn(Qe,F.getMessages(),oe),l||pn(!0)}}),t.clientToken&&F.initClientSession().catch(l=>{t.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&F.setSSEEventCallback((l,u)=>{D==null||D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(a=br(l.metadata),x.syncFromMetadata()),(u=l.messages)!=null&&u.length&&F.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Xn=l=>{var A;l.preventDefault();let u=me.value.trim(),b=(A=ue==null?void 0:ue.hasAttachments())!=null?A:!1;if(!u&&!b)return;let L;b&&(L=[],L.push(...ue.getContentParts()),u&&L.push(Bs(u))),me.value="",me.style.height="auto",F.sendMessage(u,{contentParts:L}),b&&ue.clearAttachments()},Gn=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},Ht=null,Nt=!1,nn=null,Yt=null,Qn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,hn=(l="user")=>{var $,ye,ce,be;if(Nt||F.isStreaming())return;let u=Qn();if(!u)return;Ht=new u;let L=(ye=(($=t.voiceRecognition)!=null?$:{}).pauseDuration)!=null?ye:2e3;Ht.continuous=!0,Ht.interimResults=!0,Ht.lang="en-US";let A=me.value;Ht.onresult=Te=>{let Ce="",Pe="";for(let I=0;I<Te.results.length;I++){let we=Te.results[I],xe=we[0].transcript;we.isFinal?Ce+=xe+" ":Pe=xe}let G=A+Ce+Pe;me.value=G,nn&&clearTimeout(nn),(Ce||Pe)&&(nn=window.setTimeout(()=>{let I=me.value.trim();I&&Ht&&Nt&&(qt(),me.value="",me.style.height="auto",F.sendMessage(I,{viaVoice:!0}))},L))},Ht.onerror=Te=>{Te.error!=="no-speech"&&qt()},Ht.onend=()=>{if(Nt){let Te=me.value.trim();Te&&Te!==A.trim()&&(me.value="",me.style.height="auto",F.sendMessage(Te,{viaVoice:!0})),qt()}};try{if(Ht.start(),Nt=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),Kn(l),en(),j){Yt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let Te=(ce=t.voiceRecognition)!=null?ce:{},Ce=(be=Te.recordingBackgroundColor)!=null?be:"#ef4444",Pe=Te.recordingIconColor,G=Te.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=Ce,Pe){j.style.color=Pe;let I=j.querySelector("svg");I&&I.setAttribute("stroke",Pe)}G&&(j.style.borderColor=G),j.setAttribute("aria-label","Stop voice recognition")}}catch{qt("system")}},qt=(l="user")=>{if(Nt){if(Nt=!1,nn&&(clearTimeout(nn),nn=null),Ht){try{Ht.stop()}catch{}Ht=null}if(Ke.active=!1,Kn(l),en(),j){if(j.classList.remove("tvw-voice-recording"),Yt){j.style.backgroundColor=Yt.backgroundColor,j.style.color=Yt.color,j.style.borderColor=Yt.borderColor;let u=j.querySelector("svg");u&&u.setAttribute("stroke",Yt.color||"currentColor"),Yt=null}j.setAttribute("aria-label","Start voice recognition")}}},bs=(l,u)=>{var xe,Ve,He,mt,It,K,je;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let L=p("div","tvw-send-button-wrapper"),A=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let $=(xe=l==null?void 0:l.iconName)!=null?xe:"mic",ye=(Ve=u==null?void 0:u.size)!=null?Ve:"40px",ce=(He=l==null?void 0:l.iconSize)!=null?He:ye,be=parseFloat(ce)||24,Te=(mt=l==null?void 0:l.backgroundColor)!=null?mt:u==null?void 0:u.backgroundColor,Ce=(It=l==null?void 0:l.iconColor)!=null?It:u==null?void 0:u.textColor;A.style.width=ce,A.style.height=ce,A.style.minWidth=ce,A.style.minHeight=ce,A.style.fontSize="18px",A.style.lineHeight="1";let Pe=Ce||"currentColor",G=ie($,be,Pe,1.5);G?(A.appendChild(G),A.style.color=Pe):(A.textContent="\u{1F3A4}",A.style.color=Pe),Te?A.style.backgroundColor=Te:A.classList.add("tvw-bg-cw-primary"),Ce?A.style.color=Ce:!Ce&&!(u!=null&&u.textColor)&&A.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(A.style.borderWidth=l.borderWidth,A.style.borderStyle="solid"),l!=null&&l.borderColor&&(A.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(A.style.paddingLeft=l.paddingX,A.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(A.style.paddingTop=l.paddingY,A.style.paddingBottom=l.paddingY),L.appendChild(A);let I=(K=l==null?void 0:l.tooltipText)!=null?K:"Start voice recognition";if(((je=l==null?void 0:l.showTooltip)!=null?je:!1)&&I){let Vt=p("div","tvw-send-button-tooltip");Vt.textContent=I,L.appendChild(Vt)}return{micButton:A,micButtonWrapper:L}},In=()=>{if(Nt){let l=me.value.trim();Ke.manuallyDeactivated=!0,en(),qt("user"),l&&(me.value="",me.style.height="auto",F.sendMessage(l))}else Ke.manuallyDeactivated=!1,en(),hn("user")};j&&(j.addEventListener("click",In),rt.push(()=>{qt("system"),j&&j.removeEventListener("click",In)}));let Cs=s.on("assistant:complete",()=>{Jn&&(Ke.active||Ke.manuallyDeactivated||Jn==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&hn("auto")},600))});rt.push(Cs);let xs=s.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});rt.push(xs);let B=()=>{tt(!y,"user")},ne=null,ae=null;if(C){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:t,defaultRenderer:()=>is(t,B).element,onToggle:B});u&&(ae=u)}ae||(ne=is(t,B))}ne?e.appendChild(ne.element):ae&&e.appendChild(ae),mn(),an.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),Vn(),Wn(F.isStreaming()),pn(!0),hs();let Xe=()=>{var b,L,A,$,ye,ce,be,Te;let l=(L=(b=t.launcher)==null?void 0:b.sidebarMode)!=null?L:!1,u=l||(($=(A=t.launcher)==null?void 0:A.fullHeight)!=null?$:!1);if(!C){Ae.style.height="",Ae.style.width="";return}if(!l){let Ce=(ce=(ye=t==null?void 0:t.launcher)==null?void 0:ye.width)!=null?ce:t==null?void 0:t.launcherWidth,Pe=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";Ae.style.width=Pe,Ae.style.maxWidth=Pe}if(!u){let Ce=window.innerHeight,Pe=64,G=(Te=(be=t.launcher)==null?void 0:be.heightOffset)!=null?Te:0,I=Math.max(200,Ce-Pe),we=Math.min(640,I),xe=Math.max(200,we-G);Ae.style.height=`${xe}px`}};Xe(),window.addEventListener("resize",Xe),rt.push(()=>window.removeEventListener("resize",Xe)),un=$e.scrollTop;let pt=()=>{let l=$e.scrollTop,u=$e.scrollHeight,b=$e.clientHeight,L=u-l-b,A=Math.abs(l-un);if(un=l,!Ln&&!(A<=ms)){if(!Gt&&L<Un){Zt=!1,Gt=!0;return}Gt&&L>Un&&(Zt=!0,Mn=Date.now()+gs,Gt=!1)}};$e.addEventListener("scroll",pt,{passive:!0}),rt.push(()=>$e.removeEventListener("scroll",pt)),rt.push(()=>{Qt&&cancelAnimationFrame(Qt)});let Et=()=>{Y&&(Kt&&(Y.removeEventListener("click",Kt),Kt=null),C?(Y.style.display="",Kt=()=>{y=!1,mn()},Y.addEventListener("click",Kt)):Y.style.display="none")};Et(),(()=>{let{clearChatButton:l}=ee;l&&l.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(_n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_n}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==_n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",L)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()})})(),ut.addEventListener("submit",Xn),me.addEventListener("keydown",Gn),rt.push(()=>{ut.removeEventListener("submit",Xn),me.removeEventListener("keydown",Gn)}),rt.push(()=>{F.cancel()}),ne?rt.push(()=>{ne==null||ne.destroy()}):ae&&rt.push(()=>{ae==null||ae.remove()});let m={update(l){var Dr,jr,_r,qr,zr,Ur,Jr,Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,Lo,ko,Wo,Io,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,jo,_o,qo,zo,Uo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,hi,fi,wi,vi;let u=t.toolCall,b=t.colorScheme;t={...t,...l},Tn(),$s(e,t),t.colorScheme!==b&&qn();let L=ds.getForInstance(t.plugins);o.length=0,o.push(...L),C=(jr=(Dr=t.launcher)==null?void 0:Dr.enabled)!=null?jr:!0,E=(qr=(_r=t.launcher)==null?void 0:_r.autoExpand)!=null?qr:!1,_=(Ur=(zr=t.features)==null?void 0:zr.showReasoning)!=null?Ur:!0,le=(Kr=(Jr=t.features)==null?void 0:Jr.showToolCalls)!=null?Kr:!0;let A=X;if(X=(Vr=(Yr=t.features)==null?void 0:Yr.showEventStreamToggle)!=null?Vr:!1,X&&!A){if(D||(N=new ls(Se),D=new as(re,N),N.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),F.setSSEEventCallback((M,Me)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:M,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!q&&Q){let M=(Gr=(Xr=t.features)==null?void 0:Xr.eventStream)==null?void 0:Gr.classNames,Me="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(M!=null&&M.toggleButton?" "+M.toggleButton:"");q=p("button",Me),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let Ge=ie("activity","18px","currentColor",1.5);Ge&&q.appendChild(Ge);let fe=ee.clearChatButtonWrapper,Re=ee.closeButtonWrapper,ht=fe||Re;ht&&ht.parentNode===Q?Q.insertBefore(q,ht):Q.appendChild(q),q.addEventListener("click",()=>{ve?Ne():Le()})}}else!X&&A&&(Ne(),q&&(q.remove(),q=null),D==null||D.clear(),N==null||N.destroy(),D=null,N=null);if(((Qr=t.launcher)==null?void 0:Qr.enabled)===!1&&ne&&(ne.destroy(),ne=null),((Zr=t.launcher)==null?void 0:Zr.enabled)===!1&&ae&&(ae.remove(),ae=null),((eo=t.launcher)==null?void 0:eo.enabled)!==!1&&!ne&&!ae){let M=o.find(Me=>Me.renderLauncher);if(M!=null&&M.renderLauncher){let Me=M.renderLauncher({config:t,defaultRenderer:()=>is(t,B).element,onToggle:B});Me&&(ae=Me,e.appendChild(ae))}ae||(ne=is(t,B),e.appendChild(ne.element))}ne&&ne.update(t),vt&&((to=t.launcher)==null?void 0:to.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((no=t.launcher)==null?void 0:no.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let $=(so=t.layout)==null?void 0:so.header;if(($==null?void 0:$.layout)!==V&&Q){let M=$?Bn(t,$,{showClose:C,onClose:()=>tt(!1,"user")}):rn({config:t,showClose:C,onClose:()=>tt(!1,"user")});Q.replaceWith(M.header),Q=M.header,Ie=M.iconHolder,vt=M.headerTitle,yt=M.headerSubtitle,Y=M.closeButton,V=$==null?void 0:$.layout}else if($&&(Ie&&(Ie.style.display=$.showIcon===!1?"none":""),vt&&(vt.style.display=$.showTitle===!1?"none":""),yt&&(yt.style.display=$.showSubtitle===!1?"none":""),Y&&(Y.style.display=$.showCloseButton===!1?"none":""),ee.clearChatButtonWrapper)){let M=$.showClearChat;if(M!==void 0){ee.clearChatButtonWrapper.style.display=M?"":"none";let{closeButtonWrapper:Me}=ee;Me&&!Me.classList.contains("tvw-absolute")&&(M?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let ce=((ro=t.layout)==null?void 0:ro.showHeader)!==!1;Q&&(Q.style.display=ce?"":"none");let be=((oo=t.layout)==null?void 0:oo.showFooter)!==!1;Oe&&(Oe.style.display=be?"":"none"),C!==k?C?tt(E,"auto"):(y=!0,mn()):E!==S&&tt(E,"auto"),S=E,k=C,Xe(),Et(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&F&&gn(Qe,F.getMessages(),oe);let G=(io=t.launcher)!=null?io:{},I=(ao=G.headerIconHidden)!=null?ao:!1,we=(co=(lo=t.layout)==null?void 0:lo.header)==null?void 0:co.showIcon,xe=I||we===!1,Ve=G.headerIconName,He=(uo=G.headerIconSize)!=null?uo:"48px";if(Ie){let M=ge.querySelector(".tvw-border-b-cw-divider"),Me=M==null?void 0:M.querySelector(".tvw-flex-col");if(xe)Ie.style.display="none",M&&Me&&!M.contains(Me)&&M.insertBefore(Me,M.firstChild);else{if(Ie.style.display="",Ie.style.height=He,Ie.style.width=He,M&&Me&&(M.contains(Ie)?Ie.nextSibling!==Me&&(Ie.remove(),M.insertBefore(Ie,Me)):M.insertBefore(Ie,Me)),Ve){let fe=parseFloat(He)||24,Re=ie(Ve,fe*.6,"#ffffff",2);Re?Ie.replaceChildren(Re):Ie.textContent=(po=G.agentIconText)!=null?po:"\u{1F4AC}"}else if(G.iconUrl){let fe=Ie.querySelector("img");if(fe)fe.src=G.iconUrl,fe.style.height=He,fe.style.width=He;else{let Re=document.createElement("img");Re.src=G.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=He,Re.style.width=He,Ie.replaceChildren(Re)}}else{let fe=Ie.querySelector("svg"),Re=Ie.querySelector("img");(fe||Re)&&Ie.replaceChildren(),Ie.textContent=(go=G.agentIconText)!=null?go:"\u{1F4AC}"}let Ge=Ie.querySelector("img");Ge&&(Ge.style.height=He,Ge.style.width=He)}}let mt=(ho=(mo=t.layout)==null?void 0:mo.header)==null?void 0:ho.showTitle,It=(wo=(fo=t.layout)==null?void 0:fo.header)==null?void 0:wo.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=It===!1?"none":""),Y){((yo=(vo=t.layout)==null?void 0:vo.header)==null?void 0:yo.showCloseButton)===!1?Y.style.display="none":Y.style.display="";let Me=(bo=G.closeButtonSize)!=null?bo:"32px",Ge=(Co=G.closeButtonPlacement)!=null?Co:"inline";Y.style.height=Me,Y.style.width=Me;let{closeButtonWrapper:fe}=ee,Re=Ge==="top-right",ht=fe==null?void 0:fe.classList.contains("tvw-absolute");if(fe&&Re!==ht)if(fe.remove(),Re)fe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",ge.style.position="relative",ge.appendChild(fe);else{let ke=(So=(xo=G.clearChat)==null?void 0:xo.placement)!=null?So:"inline",St=(Eo=(Ao=G.clearChat)==null?void 0:Ao.enabled)!=null?Eo:!0;fe.className=St&&ke==="inline"?"":"tvw-ml-auto";let Ft=ge.querySelector(".tvw-border-b-cw-divider");Ft&&Ft.appendChild(fe)}if(G.closeButtonColor?(Y.style.color=G.closeButtonColor,Y.classList.remove("tvw-text-cw-muted")):(Y.style.color="",Y.classList.add("tvw-text-cw-muted")),G.closeButtonBackgroundColor?(Y.style.backgroundColor=G.closeButtonBackgroundColor,Y.classList.remove("hover:tvw-bg-gray-100")):(Y.style.backgroundColor="",Y.classList.add("hover:tvw-bg-gray-100")),G.closeButtonBorderWidth||G.closeButtonBorderColor){let ke=G.closeButtonBorderWidth||"0px",St=G.closeButtonBorderColor||"transparent";Y.style.border=`${ke} solid ${St}`,Y.classList.remove("tvw-border-none")}else Y.style.border="",Y.classList.add("tvw-border-none");G.closeButtonBorderRadius?(Y.style.borderRadius=G.closeButtonBorderRadius,Y.classList.remove("tvw-rounded-full")):(Y.style.borderRadius="",Y.classList.add("tvw-rounded-full")),G.closeButtonPaddingX?(Y.style.paddingLeft=G.closeButtonPaddingX,Y.style.paddingRight=G.closeButtonPaddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),G.closeButtonPaddingY?(Y.style.paddingTop=G.closeButtonPaddingY,Y.style.paddingBottom=G.closeButtonPaddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let kt=(To=G.closeButtonIconName)!=null?To:"x",Dt=(Mo=G.closeButtonIconText)!=null?Mo:"\xD7";Y.innerHTML="";let Bt=ie(kt,"20px",G.closeButtonColor||"",2);Bt?Y.appendChild(Bt):Y.textContent=Dt;let ot=(Lo=G.closeButtonTooltipText)!=null?Lo:"Close chat",jt=(ko=G.closeButtonShowTooltip)!=null?ko:!0;if(Y.setAttribute("aria-label",ot),fe&&(fe._cleanupTooltip&&(fe._cleanupTooltip(),delete fe._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!Y)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let ss=p("div");ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(ss);let vn=Y.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${vn.left+vn.width/2}px`,ke.style.top=`${vn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};fe.addEventListener("mouseenter",St),fe.addEventListener("mouseleave",Ft),Y.addEventListener("focus",St),Y.addEventListener("blur",Ft),fe._cleanupTooltip=()=>{Ft(),fe&&(fe.removeEventListener("mouseenter",St),fe.removeEventListener("mouseleave",Ft)),Y&&(Y.removeEventListener("focus",St),Y.removeEventListener("blur",Ft))}}}let{clearChatButton:K,clearChatButtonWrapper:je}=ee;if(K){let M=(Wo=G.clearChat)!=null?Wo:{},Me=(Io=M.enabled)!=null?Io:!0,Ge=(Ho=(Po=t.layout)==null?void 0:Po.header)==null?void 0:Ho.showClearChat,fe=Ge!==void 0?Ge:Me,Re=(Bo=M.placement)!=null?Bo:"inline";if(je){je.style.display=fe?"":"none";let{closeButtonWrapper:ht}=ee;ht&&!ht.classList.contains("tvw-absolute")&&(fe?ht.classList.remove("tvw-ml-auto"):ht.classList.add("tvw-ml-auto"));let kt=Re==="top-right",Dt=je.classList.contains("tvw-absolute");if(kt!==Dt&&fe){if(je.remove(),kt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",ge.style.position="relative",ge.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ot=ge.querySelector(".tvw-border-b-cw-divider"),jt=ee.closeButtonWrapper;ot&&jt&&jt.parentElement===ot?ot.insertBefore(je,jt):ot&&ot.appendChild(je)}let Bt=ee.closeButtonWrapper;Bt&&!Bt.classList.contains("tvw-absolute")&&(kt?Bt.classList.add("tvw-ml-auto"):Bt.classList.remove("tvw-ml-auto"))}}if(fe){let ht=(Ro=M.size)!=null?Ro:"32px";K.style.height=ht,K.style.width=ht;let kt=(Fo=M.iconName)!=null?Fo:"refresh-cw",Dt=($o=M.iconColor)!=null?$o:"";K.innerHTML="";let Bt=ie(kt,"20px",Dt||"",2);if(Bt&&K.appendChild(Bt),Dt?(K.style.color=Dt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),M.backgroundColor?(K.style.backgroundColor=M.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let ke=M.borderWidth||"0px",St=M.borderColor||"transparent";K.style.border=`${ke} solid ${St}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");M.borderRadius?(K.style.borderRadius=M.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),M.paddingX?(K.style.paddingLeft=M.paddingX,K.style.paddingRight=M.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),M.paddingY?(K.style.paddingTop=M.paddingY,K.style.paddingBottom=M.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let ot=(Oo=M.tooltipText)!=null?Oo:"Clear chat",jt=(No=M.showTooltip)!=null?No:!0;if(K.setAttribute("aria-label",ot),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!K)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let ss=p("div");ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(ss);let vn=K.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${vn.left+vn.width/2}px`,ke.style.top=`${vn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};je.addEventListener("mouseenter",St),je.addEventListener("mouseleave",Ft),K.addEventListener("focus",St),K.addEventListener("blur",Ft),je._cleanupTooltip=()=>{Ft(),je&&(je.removeEventListener("mouseenter",St),je.removeEventListener("mouseleave",Ft)),K&&(K.removeEventListener("focus",St),K.removeEventListener("blur",Ft))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[cs],zt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[An.message,An.messageAndClick];x=us({parsers:Vt,handlers:zt,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),oe=oa(t,x,H),F.updateConfig(t),gn(Qe,F.getMessages(),oe),an.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),Vn(),Wn(F.isStreaming());let dn=((Do=t.voiceRecognition)==null?void 0:Do.enabled)===!0,Ss=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(dn&&Ss)if(!j||!Ze){let M=bs(t.voiceRecognition,t.sendButton);M&&(j=M.micButton,Ze=M.micButtonWrapper,Mt.insertBefore(Ze,ct),j.addEventListener("click",In),j.disabled=F.isStreaming())}else{let M=(jo=t.voiceRecognition)!=null?jo:{},Me=(_o=t.sendButton)!=null?_o:{},Ge=(qo=M.iconName)!=null?qo:"mic",fe=(zo=Me.size)!=null?zo:"40px",Re=(Uo=M.iconSize)!=null?Uo:fe,ht=parseFloat(Re)||24;j.style.width=Re,j.style.height=Re,j.style.minWidth=Re,j.style.minHeight=Re;let kt=(Ko=(Jo=M.iconColor)!=null?Jo:Me.textColor)!=null?Ko:"currentColor";j.innerHTML="";let Dt=ie(Ge,ht,kt,2);Dt?j.appendChild(Dt):j.textContent="\u{1F3A4}";let Bt=(Yo=M.backgroundColor)!=null?Yo:Me.backgroundColor;Bt?(j.style.backgroundColor=Bt,j.classList.remove("tvw-bg-cw-primary")):(j.style.backgroundColor="",j.classList.add("tvw-bg-cw-primary")),kt?(j.style.color=kt,j.classList.remove("tvw-text-white")):!kt&&!Me.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),M.borderWidth?(j.style.borderWidth=M.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),M.borderColor?j.style.borderColor=M.borderColor:j.style.borderColor="",M.paddingX?(j.style.paddingLeft=M.paddingX,j.style.paddingRight=M.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),M.paddingY?(j.style.paddingTop=M.paddingY,j.style.paddingBottom=M.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let ot=Ze==null?void 0:Ze.querySelector(".tvw-send-button-tooltip"),jt=(Vo=M.tooltipText)!=null?Vo:"Start voice recognition";if(((Xo=M.showTooltip)!=null?Xo:!1)&&jt)if(ot)ot.textContent=jt,ot.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=jt,Ze==null||Ze.insertBefore(St,j)}else ot&&(ot.style.display="none");Ze.style.display="",j.disabled=F.isStreaming()}else j&&Ze&&(Ze.style.display="none",Nt&&qt());if(((Go=t.attachments)==null?void 0:Go.enabled)===!0)if(!z||!We){let M=(Qo=t.attachments)!=null?Qo:{},Ge=(ei=((Zo=t.sendButton)!=null?Zo:{}).size)!=null?ei:"40px";he||(he=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),he.style.display="none",ut.insertBefore(he,me)),R||(R=document.createElement("input"),R.type="file",R.accept=((ti=M.allowedTypes)!=null?ti:cn).join(","),R.multiple=((ni=M.maxFiles)!=null?ni:4)>1,R.style.display="none",R.setAttribute("aria-label","Attach files"),ut.insertBefore(R,me)),z=p("div","tvw-send-button-wrapper"),We=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),We.type="button",We.setAttribute("aria-label",(si=M.buttonTooltipText)!=null?si:"Attach file");let fe=(ri=M.buttonIconName)!=null?ri:"paperclip",Re=Ge,ht=parseFloat(Re)||40,kt=Math.round(ht*.6);We.style.width=Re,We.style.height=Re,We.style.minWidth=Re,We.style.minHeight=Re,We.style.fontSize="18px",We.style.lineHeight="1",We.style.backgroundColor="transparent",We.style.color="var(--cw-primary, #111827)",We.style.border="none",We.style.borderRadius="6px",We.style.transition="background-color 0.15s ease",We.addEventListener("mouseenter",()=>{We.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),We.addEventListener("mouseleave",()=>{We.style.backgroundColor="transparent"});let Dt=ie(fe,kt,"currentColor",1.5);Dt?We.appendChild(Dt):We.textContent="\u{1F4CE}",We.addEventListener("click",jt=>{jt.preventDefault(),R==null||R.click()}),z.appendChild(We);let Bt=(oi=M.buttonTooltipText)!=null?oi:"Attach file",ot=p("div","tvw-send-button-tooltip");ot.textContent=Bt,z.appendChild(ot),Wt.append(z),!ue&&R&&he&&(ue=Cn.fromConfig(M),ue.setPreviewsContainer(he),R.addEventListener("change",async()=>{ue&&(R!=null&&R.files)&&(await ue.handleFileSelect(R.files),R.value="")}))}else{z.style.display="";let M=(ii=t.attachments)!=null?ii:{};R&&(R.accept=((ai=M.allowedTypes)!=null?ai:cn).join(","),R.multiple=((li=M.maxFiles)!=null?li:4)>1),ue&&ue.updateConfig({allowedTypes:M.allowedTypes,maxFileSize:M.maxFileSize,maxFiles:M.maxFiles})}else z&&(z.style.display="none"),ue&&ue.clearAttachments();let dt=(di=t.sendButton)!=null?di:{},As=(ci=dt.useIcon)!=null?ci:!1,Zn=(ui=dt.iconText)!=null?ui:"\u2191",fn=dt.iconName,wn=(pi=dt.tooltipText)!=null?pi:"Send message",ma=(gi=dt.showTooltip)!=null?gi:!1,es=(mi=dt.size)!=null?mi:"40px",Es=dt.backgroundColor,Xt=dt.textColor;if(As){if(J.style.width=es,J.style.height=es,J.style.minWidth=es,J.style.minHeight=es,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",fn){let M=parseFloat(es)||24,Me=Xt&&typeof Xt=="string"&&Xt.trim()?Xt.trim():"currentColor",Ge=ie(fn,M,Me,2);Ge?(J.appendChild(Ge),J.style.color=Me):(J.textContent=Zn,Xt?J.style.color=Xt:J.classList.add("tvw-text-white"))}else J.textContent=Zn,Xt?J.style.color=Xt:J.classList.add("tvw-text-white");J.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Es?(J.style.backgroundColor=Es,J.classList.remove("tvw-bg-cw-primary")):J.classList.add("tvw-bg-cw-primary")}else J.textContent=(fi=(hi=t.copy)==null?void 0:hi.sendButtonLabel)!=null?fi:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Es?(J.style.backgroundColor=Es,J.classList.remove("tvw-bg-cw-accent")):J.classList.add("tvw-bg-cw-accent"),Xt?J.style.color=Xt:J.classList.add("tvw-text-white");dt.borderWidth?(J.style.borderWidth=dt.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),dt.borderColor?J.style.borderColor=dt.borderColor:J.style.borderColor="",dt.paddingX?(J.style.paddingLeft=dt.paddingX,J.style.paddingRight=dt.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),dt.paddingY?(J.style.paddingTop=dt.paddingY,J.style.paddingBottom=dt.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let ts=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(ma&&wn)if(ts)ts.textContent=wn,ts.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=wn,ct==null||ct.insertBefore(M,J)}else ts&&(ts.style.display="none");let ns=(wi=t.statusIndicator)!=null?wi:{},ha=(vi=ns.visible)!=null?vi:!0;if(ft.style.display=ha?"":"none",F){let M=F.getStatus(),Me=Ge=>{var fe,Re,ht,kt;return Ge==="idle"?(fe=ns.idleText)!=null?fe:Pt.idle:Ge==="connecting"?(Re=ns.connectingText)!=null?Re:Pt.connecting:Ge==="connected"?(ht=ns.connectedText)!=null?ht:Pt.connected:Ge==="error"?(kt=ns.errorText)!=null?kt:Pt.error:Pt[Ge]};ft.textContent=Me(M)}},open(){C&&tt(!0,"api")},close(){C&&tt(!1,"api")},toggle(){C&&tt(!y,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(_n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_n}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==_n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()},setMessage(l){return!me||F.isStreaming()?!1:(!y&&C&&tt(!0,"system"),me.value=l,me.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let u=(l==null?void 0:l.trim())||me.value.trim();return u?(!y&&C&&tt(!0,"system"),me.value="",me.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){return Nt||F.isStreaming()||!Qn()?!1:(!y&&C&&tt(!0,"system"),Ke.manuallyDeactivated=!1,en(),hn("user"),!0)},stopVoiceRecognition(){return Nt?(Ke.manuallyDeactivated=!0,en(),qt("user"),!0):!1},injectMessage(l){return!y&&C&&tt(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!y&&C&&tt(!0,"system");let u=F.injectAssistantMessage(l);return O&&(O=!1,W&&(clearTimeout(W),W=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),u},injectUserMessage(l){return!y&&C&&tt(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!y&&C&&tt(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!y&&C&&tt(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!y&&C&&tt(!0,"system"),F.injectTestEvent(l)},__pushEventStreamEvent(l){D&&D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!X||!D||Le()},hideEventStream(){ve&&Ne()},isEventStreamVisible(){return ve},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){c(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return C&&y},isVoiceActive(){return Ke.active},getState(){return{open:C&&y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()}},showCSATFeedback(l){!y&&C&&tt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Us({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitCSATFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!y&&C&&tt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Js({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitNPSFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return F.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return F.submitNPSFeedback(l,u)},destroy(){rt.forEach(l=>l()),Fe.remove(),ne==null||ne.destroy(),ae==null||ae.remove(),Kt&&Y.removeEventListener("click",Kt)}};if((((Br=r==null?void 0:r.debugTools)!=null?Br:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:m,getMessages:m.getMessages,getStatus:m.getStatus,getMetadata:m.getPersistentMetadata,updateMetadata:m.updatePersistentMetadata,clearHistory:()=>m.clearChat(),setVoiceActive:b=>b?m.startVoiceRecognition():m.stopVoiceRecognition()};window.AgentWidgetBrowser=u,rt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(X&&typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.showEventStream()},b=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.hideEventStream()};window.addEventListener("persona:showEventStream",u),window.addEventListener("persona:hideEventStream",b),rt.push(()=>{window.removeEventListener("persona:showEventStream",u),window.removeEventListener("persona:hideEventStream",b)})}let P=al(t.persistState);if(P&&C){let l=ll(P.storage),u=`${P.keyPrefix}widget-open`,b=`${P.keyPrefix}widget-voice`,L=`${P.keyPrefix}widget-voice-mode`;if(l){let A=((Rr=P.persist)==null?void 0:Rr.openState)&&l.getItem(u)==="true",$=((Fr=P.persist)==null?void 0:Fr.voiceState)&&l.getItem(b)==="true",ye=(($r=P.persist)==null?void 0:$r.voiceState)&&l.getItem(L)==="true";if(A&&setTimeout(()=>{m.open(),setTimeout(()=>{var ce;if($||ye)m.startVoiceRecognition();else if((ce=P.persist)!=null&&ce.focusInput){let be=e.querySelector("textarea");be&&be.focus()}},100)},0),(Or=P.persist)!=null&&Or.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Nr=P.persist)!=null&&Nr.voiceState&&(s.on("voice:state",ce=>{l.setItem(b,ce.active?"true":"false")}),s.on("user:message",ce=>{l.setItem(L,ce.viaVoice?"true":"false")})),P.clearOnChatClear){let ce=()=>{l.removeItem(u),l.removeItem(b),l.removeItem(L)},be=()=>ce();window.addEventListener("persona:clear-chat",be),rt.push(()=>{window.removeEventListener("persona:clear-chat",be)})}}}return m};var Cr={},dl=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},cl=()=>{try{if(typeof Cr!="undefined"&&Cr.url)return new URL("../widget.css",Cr.url).href}catch{}return null},ia=e=>{let n=cl(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},xr=e=>{var g,w,c,h;let n=dl(e.target),r=document.createElement("div");r.className="persona-host";let t=(c=(w=(g=e.config)==null?void 0:g.launcher)==null?void 0:w.enabled)!=null?c:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let f=r.attachShadow({mode:"open"});i=f,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),f.appendChild(s),ia(f)}else i=r,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),ia(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=Ks(s,e.config,{debugTools:e.debugTools});(h=e.onReady)==null||h.call(e);let d={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var aa={name:"@runtypelabs/persona",version:"1.44.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var En=aa.version;function on(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function pl(e){if(e)return{getHeaders:on(e.getHeaders),onFeedback:on(e.onFeedback),onCopy:on(e.onCopy),requestMiddleware:on(e.requestMiddleware),actionHandlers:on(e.actionHandlers),actionParsers:on(e.actionParsers),postprocessMessage:on(e.postprocessMessage),contextProviders:on(e.contextProviders),streamParser:on(e.streamParser)}}var la=`({ text, message }: any) => {
60
+ `}if(!I){let fn="max-height: -moz-available !important; max-height: stretch !important;",wn=l?"":"padding-top: 1.25em !important;";Fe.style.cssText+=fn+wn}};Tn(),$s(e,t);let rt=[];X&&rt.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),Z==null||Z.destroy(),Z=null,D==null||D.destroy(),D=null,N=null});let Jt=null,qn=()=>{Jt&&(Jt(),Jt=null),t.colorScheme==="auto"&&(Jt=_i(()=>{$s(e,t)}))};qn(),rt.push(()=>{Jt&&(Jt(),Jt=null)});let an=Gi(At),Kt=null,F,ln=!1,Gt=!0,un=0,zn=0,Qt=null,Zt=!1,Mn=0,Ln=!1,ps=125,gs=2e3,ms=5,Un=50,kn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Jn=(Hr=(Pr=t.voiceRecognition)==null?void 0:Pr.autoResume)!=null?Hr:!1,Kn=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},en=()=>{c(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},hs=()=>{var L,A;if(((L=t.voiceRecognition)==null?void 0:L.enabled)===!1)return;let l=br(a.voiceState),u=!!l.active,b=Number((A=l.timestamp)!=null?A:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-b<il&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,hn("restore"))},1e3)},fs=()=>F?ra(F.getMessages()).filter(l=>!l.__skipPersist):[];function Yn(l){if(!(i!=null&&i.save))return;let b={messages:l?ra(l):F?fs():[],metadata:a};try{let L=i.save(b);L instanceof Promise&&L.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(L){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)}}let pn=(l=!1)=>{if(!Gt)return;let u=Date.now();Zt&&u<Mn&&!l||(Zt&&u>=Mn&&(Zt=!1),!(!l&&!ln)&&(u-zn<ps||(zn=u,Qt&&cancelAnimationFrame(Qt),Qt=requestAnimationFrame(()=>{Zt||!Gt||(Ln=!0,$e.scrollTop=$e.scrollHeight,un=$e.scrollTop,requestAnimationFrame(()=>{Ln=!1}),Qt=null)}))))},tn=null,ws=()=>Fe.querySelector("#persona-scroll-container")||$e,vs=(l,u=500)=>{let b=l.scrollTop,L=l.clientHeight,A=l.scrollHeight,$=A-b;if(b+L>=A-2||Math.abs($)<5)return;tn!==null&&(cancelAnimationFrame(tn),tn=null);let ce=performance.now(),be=Ce=>1-Math.pow(1-Ce,3),Te=Ce=>{let Pe=l.scrollHeight;Pe!==A&&(A=Pe,$=A-b);let G=Ce-ce,I=Math.min(G/u,1),we=be(I),xe=b+$*we;l.scrollTop=xe,I<1?tn=requestAnimationFrame(Te):(l.scrollTop=l.scrollHeight,tn=null)};tn=requestAnimationFrame(Te)},ys=l=>{let u=new Map;l.forEach(b=>{let L=kn.get(b.id);u.set(b.id,{streaming:b.streaming,role:b.role}),!L&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(L!=null&&L.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b)}),kn.clear(),u.forEach((b,L)=>{kn.set(L,b)})},gn=(l,u,b)=>{var Te,Ce,Pe,G;let L=document.createElement("div"),$=(()=>{var we;let I=o.find(xe=>xe.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((we=t.loadingIndicator)!=null&&we.render)return t.loadingIndicator.render})();u.forEach(I=>{var mt,It;let we=null,xe=o.find(K=>!!(I.variant==="reasoning"&&K.renderReasoning||I.variant==="tool"&&K.renderToolCall||!I.variant&&K.renderMessage)),Ve=(mt=t.layout)==null?void 0:mt.messages;if(xe)if(I.variant==="reasoning"&&I.reasoning&&xe.renderReasoning){if(!_)return;we=xe.renderReasoning({message:I,defaultRenderer:()=>ur(I),config:t})}else if(I.variant==="tool"&&I.toolCall&&xe.renderToolCall){if(!le)return;we=xe.renderToolCall({message:I,defaultRenderer:()=>pr(I,t),config:t})}else xe.renderMessage&&(we=xe.renderMessage({message:I,defaultRenderer:()=>{let K=Fn(I,b,Ve,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t});return I.role!=="user"&&mr(K,I,t,F),K},config:t}));if(!we&&I.role==="assistant"&&!I.variant&&t.enableComponentStreaming!==!1&&qs(I)){let je=zs(I);if(je){let Vt=_s(je,{config:t,message:I,transform:b});if(Vt){let zt=document.createElement("div");if(zt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),zt.id=`bubble-${I.id}`,zt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let dn=document.createElement("div");dn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",dn.innerHTML=b({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),zt.appendChild(dn)}zt.appendChild(Vt),we=zt}}}if(!we)if(I.variant==="reasoning"&&I.reasoning){if(!_)return;we=ur(I)}else if(I.variant==="tool"&&I.toolCall){if(!le)return;we=pr(I,t)}else{let K=(It=t.layout)==null?void 0:It.messages;K!=null&&K.renderUserMessage&&I.role==="user"?we=K.renderUserMessage({message:I,config:t,streaming:!!I.streaming}):K!=null&&K.renderAssistantMessage&&I.role==="assistant"?we=K.renderAssistantMessage({message:I,config:t,streaming:!!I.streaming}):we=Fn(I,b,K,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t}),I.role!=="user"&&we&&mr(we,I,t,F)}let He=document.createElement("div");He.className="tvw-flex",He.id=`wrapper-${I.id}`,He.setAttribute("data-wrapper-id",I.id),I.role==="user"&&He.classList.add("tvw-justify-end"),He.appendChild(we),L.appendChild(He)});let ye=u.some(I=>I.role==="assistant"&&I.streaming),ce=u[u.length-1],be=(ce==null?void 0:ce.role)==="assistant"&&!ce.streaming;if(ln&&u.some(I=>I.role==="user")&&!ye&&!be){let I={config:t,streaming:!0,location:"standalone",defaultRenderer:Sn},we=o.find(Ve=>Ve.renderLoadingIndicator),xe=null;if(we!=null&&we.renderLoadingIndicator&&(xe=we.renderLoadingIndicator(I)),xe===null&&((Te=t.loadingIndicator)!=null&&Te.render)&&(xe=t.loadingIndicator.render(I)),xe===null&&(xe=Sn()),xe){let Ve=document.createElement("div"),He=((Ce=t.loadingIndicator)==null?void 0:Ce.showBubble)!==!1;Ve.className=He?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(xe);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Ve),L.appendChild(mt)}}if(!ln&&u.length>0){let I=u[u.length-1],we={config:t,lastMessage:I,messageCount:u.length},xe=o.find(He=>He.renderIdleIndicator),Ve=null;if(xe!=null&&xe.renderIdleIndicator&&(Ve=xe.renderIdleIndicator(we)),Ve===null&&((Pe=t.loadingIndicator)!=null&&Pe.renderIdle)&&(Ve=t.loadingIndicator.renderIdle(we)),Ve){let He=document.createElement("div"),mt=((G=t.loadingIndicator)==null?void 0:G.showBubble)!==!1;He.className=mt?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(Ve);let It=document.createElement("div");It.className="tvw-flex",It.id="wrapper-idle-indicator",It.setAttribute("data-wrapper-id","idle-indicator"),It.appendChild(He),L.appendChild(It)}}zi(l,L),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=ws();vs(I)})})},mn=()=>{C&&(y?(Fe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-95","tvw-opacity-0"),Ae.classList.add("tvw-scale-100","tvw-opacity-100"),ne?ne.element.style.display="none":ae&&(ae.style.display="none")):(Fe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-100","tvw-opacity-100"),Ae.classList.add("tvw-scale-95","tvw-opacity-0"),ne?ne.element.style.display="":ae&&(ae.style.display="")))},tt=(l,u="user")=>{if(!C||y===l)return;let b=y;y=l,mn(),y&&(Xe(),pn(!0));let L={open:y,source:u,timestamp:Date.now()};y&&!b?s.emit("widget:opened",L):!y&&b&&s.emit("widget:closed",L),s.emit("widget:state",{open:y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()})},Wn=l=>{J.disabled=l,j&&(j.disabled=l),an.buttons.forEach(u=>{u.disabled=l})},Vn=()=>{var A,$,ye,ce,be,Te,Ce,Pe,G,I,we,xe,Ve,He;Ot.textContent=($=(A=t.copy)==null?void 0:A.welcomeTitle)!=null?$:"Hello \u{1F44B}",wt.textContent=(ce=(ye=t.copy)==null?void 0:ye.welcomeSubtitle)!=null?ce:"Ask anything about your account or products.",me.placeholder=(Te=(be=t.copy)==null?void 0:be.inputPlaceholder)!=null?Te:"How can I help...",((Pe=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?Pe:!1)||(J.textContent=(I=(G=t.copy)==null?void 0:G.sendButtonLabel)!=null?I:"Send");let u=(xe=(we=t.theme)==null?void 0:we.inputFontFamily)!=null?xe:"sans-serif",b=(He=(Ve=t.theme)==null?void 0:Ve.inputFontWeight)!=null?He:"400",L=mt=>{switch(mt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};me.style.fontFamily=L(u),me.style.fontWeight=b};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{c(u=>({...u,sessionId:l}))}}),F=new Hn(t,{onMessagesChanged(l){gn(Qe,l,oe),F&&(l.some(A=>A.role==="user")?an.render([],F,me,l):an.render(t.suggestionChips,F,me,l,t.suggestionChipsConfig)),pn(!ln),ys(l);let u=[...l].reverse().find(L=>L.role==="user"),b=Ke.lastUserMessageId;u&&u.id!==b&&(Ke.lastUserMessageId=u.id,s.emit("user:message",u)),Ke.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Yn(l)},onStatusChanged(l){var L;let u=(L=t.statusIndicator)!=null?L:{},b=A=>{var $,ye,ce,be;return A==="idle"?($=u.idleText)!=null?$:Pt.idle:A==="connecting"?(ye=u.connectingText)!=null?ye:Pt.connecting:A==="connected"?(ce=u.connectedText)!=null?ce:Pt.connected:A==="error"?(be=u.errorText)!=null?be:Pt.error:Pt[A]};ft.textContent=b(l)},onStreamingChanged(l){ln=l,Wn(l),F&&gn(Qe,F.getMessages(),oe),l||pn(!0)}}),t.clientToken&&F.initClientSession().catch(l=>{t.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&F.setSSEEventCallback((l,u)=>{D==null||D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(a=br(l.metadata),x.syncFromMetadata()),(u=l.messages)!=null&&u.length&&F.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Xn=l=>{var A;l.preventDefault();let u=me.value.trim(),b=(A=ue==null?void 0:ue.hasAttachments())!=null?A:!1;if(!u&&!b)return;let L;b&&(L=[],L.push(...ue.getContentParts()),u&&L.push(Bs(u))),me.value="",me.style.height="auto",F.sendMessage(u,{contentParts:L}),b&&ue.clearAttachments()},Gn=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},Ht=null,Nt=!1,nn=null,Yt=null,Qn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,hn=(l="user")=>{var $,ye,ce,be;if(Nt||F.isStreaming())return;let u=Qn();if(!u)return;Ht=new u;let L=(ye=(($=t.voiceRecognition)!=null?$:{}).pauseDuration)!=null?ye:2e3;Ht.continuous=!0,Ht.interimResults=!0,Ht.lang="en-US";let A=me.value;Ht.onresult=Te=>{let Ce="",Pe="";for(let I=0;I<Te.results.length;I++){let we=Te.results[I],xe=we[0].transcript;we.isFinal?Ce+=xe+" ":Pe=xe}let G=A+Ce+Pe;me.value=G,nn&&clearTimeout(nn),(Ce||Pe)&&(nn=window.setTimeout(()=>{let I=me.value.trim();I&&Ht&&Nt&&(qt(),me.value="",me.style.height="auto",F.sendMessage(I,{viaVoice:!0}))},L))},Ht.onerror=Te=>{Te.error!=="no-speech"&&qt()},Ht.onend=()=>{if(Nt){let Te=me.value.trim();Te&&Te!==A.trim()&&(me.value="",me.style.height="auto",F.sendMessage(Te,{viaVoice:!0})),qt()}};try{if(Ht.start(),Nt=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),Kn(l),en(),j){Yt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let Te=(ce=t.voiceRecognition)!=null?ce:{},Ce=(be=Te.recordingBackgroundColor)!=null?be:"#ef4444",Pe=Te.recordingIconColor,G=Te.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=Ce,Pe){j.style.color=Pe;let I=j.querySelector("svg");I&&I.setAttribute("stroke",Pe)}G&&(j.style.borderColor=G),j.setAttribute("aria-label","Stop voice recognition")}}catch{qt("system")}},qt=(l="user")=>{if(Nt){if(Nt=!1,nn&&(clearTimeout(nn),nn=null),Ht){try{Ht.stop()}catch{}Ht=null}if(Ke.active=!1,Kn(l),en(),j){if(j.classList.remove("tvw-voice-recording"),Yt){j.style.backgroundColor=Yt.backgroundColor,j.style.color=Yt.color,j.style.borderColor=Yt.borderColor;let u=j.querySelector("svg");u&&u.setAttribute("stroke",Yt.color||"currentColor"),Yt=null}j.setAttribute("aria-label","Start voice recognition")}}},bs=(l,u)=>{var xe,Ve,He,mt,It,K,je;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let L=p("div","tvw-send-button-wrapper"),A=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let $=(xe=l==null?void 0:l.iconName)!=null?xe:"mic",ye=(Ve=u==null?void 0:u.size)!=null?Ve:"40px",ce=(He=l==null?void 0:l.iconSize)!=null?He:ye,be=parseFloat(ce)||24,Te=(mt=l==null?void 0:l.backgroundColor)!=null?mt:u==null?void 0:u.backgroundColor,Ce=(It=l==null?void 0:l.iconColor)!=null?It:u==null?void 0:u.textColor;A.style.width=ce,A.style.height=ce,A.style.minWidth=ce,A.style.minHeight=ce,A.style.fontSize="18px",A.style.lineHeight="1";let Pe=Ce||"currentColor",G=ie($,be,Pe,1.5);G?(A.appendChild(G),A.style.color=Pe):(A.textContent="\u{1F3A4}",A.style.color=Pe),Te?A.style.backgroundColor=Te:A.classList.add("tvw-bg-cw-primary"),Ce?A.style.color=Ce:!Ce&&!(u!=null&&u.textColor)&&A.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(A.style.borderWidth=l.borderWidth,A.style.borderStyle="solid"),l!=null&&l.borderColor&&(A.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(A.style.paddingLeft=l.paddingX,A.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(A.style.paddingTop=l.paddingY,A.style.paddingBottom=l.paddingY),L.appendChild(A);let I=(K=l==null?void 0:l.tooltipText)!=null?K:"Start voice recognition";if(((je=l==null?void 0:l.showTooltip)!=null?je:!1)&&I){let Vt=p("div","tvw-send-button-tooltip");Vt.textContent=I,L.appendChild(Vt)}return{micButton:A,micButtonWrapper:L}},In=()=>{if(Nt){let l=me.value.trim();Ke.manuallyDeactivated=!0,en(),qt("user"),l&&(me.value="",me.style.height="auto",F.sendMessage(l))}else Ke.manuallyDeactivated=!1,en(),hn("user")};j&&(j.addEventListener("click",In),rt.push(()=>{qt("system"),j&&j.removeEventListener("click",In)}));let Cs=s.on("assistant:complete",()=>{Jn&&(Ke.active||Ke.manuallyDeactivated||Jn==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&hn("auto")},600))});rt.push(Cs);let xs=s.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});rt.push(xs);let B=()=>{tt(!y,"user")},ne=null,ae=null;if(C){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:t,defaultRenderer:()=>is(t,B).element,onToggle:B});u&&(ae=u)}ae||(ne=is(t,B))}ne?e.appendChild(ne.element):ae&&e.appendChild(ae),mn(),an.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),Vn(),Wn(F.isStreaming()),pn(!0),hs();let Xe=()=>{var b,L,A,$,ye,ce,be,Te;let l=(L=(b=t.launcher)==null?void 0:b.sidebarMode)!=null?L:!1,u=l||(($=(A=t.launcher)==null?void 0:A.fullHeight)!=null?$:!1);if(!C){Ae.style.height="",Ae.style.width="";return}if(!l){let Ce=(ce=(ye=t==null?void 0:t.launcher)==null?void 0:ye.width)!=null?ce:t==null?void 0:t.launcherWidth,Pe=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";Ae.style.width=Pe,Ae.style.maxWidth=Pe}if(!u){let Ce=window.innerHeight,Pe=64,G=(Te=(be=t.launcher)==null?void 0:be.heightOffset)!=null?Te:0,I=Math.max(200,Ce-Pe),we=Math.min(640,I),xe=Math.max(200,we-G);Ae.style.height=`${xe}px`}};Xe(),window.addEventListener("resize",Xe),rt.push(()=>window.removeEventListener("resize",Xe)),un=$e.scrollTop;let pt=()=>{let l=$e.scrollTop,u=$e.scrollHeight,b=$e.clientHeight,L=u-l-b,A=Math.abs(l-un);if(un=l,!Ln&&!(A<=ms)){if(!Gt&&L<Un){Zt=!1,Gt=!0;return}Gt&&L>Un&&(Zt=!0,Mn=Date.now()+gs,Gt=!1)}};$e.addEventListener("scroll",pt,{passive:!0}),rt.push(()=>$e.removeEventListener("scroll",pt)),rt.push(()=>{Qt&&cancelAnimationFrame(Qt)});let Et=()=>{Y&&(Kt&&(Y.removeEventListener("click",Kt),Kt=null),C?(Y.style.display="",Kt=()=>{y=!1,mn()},Y.addEventListener("click",Kt)):Y.style.display="none")};Et(),(()=>{let{clearChatButton:l}=ee;l&&l.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(_n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_n}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==_n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",L)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()})})(),ut.addEventListener("submit",Xn),me.addEventListener("keydown",Gn),rt.push(()=>{ut.removeEventListener("submit",Xn),me.removeEventListener("keydown",Gn)}),rt.push(()=>{F.cancel()}),ne?rt.push(()=>{ne==null||ne.destroy()}):ae&&rt.push(()=>{ae==null||ae.remove()});let m={update(l){var Dr,jr,_r,qr,zr,Ur,Jr,Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,Lo,ko,Wo,Io,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,jo,_o,qo,zo,Uo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,hi,fi,wi,vi;let u=t.toolCall,b=t.colorScheme;t={...t,...l},Tn(),$s(e,t),t.colorScheme!==b&&qn();let L=ds.getForInstance(t.plugins);o.length=0,o.push(...L),C=(jr=(Dr=t.launcher)==null?void 0:Dr.enabled)!=null?jr:!0,E=(qr=(_r=t.launcher)==null?void 0:_r.autoExpand)!=null?qr:!1,_=(Ur=(zr=t.features)==null?void 0:zr.showReasoning)!=null?Ur:!0,le=(Kr=(Jr=t.features)==null?void 0:Jr.showToolCalls)!=null?Kr:!0;let A=X;if(X=(Vr=(Yr=t.features)==null?void 0:Yr.showEventStreamToggle)!=null?Vr:!1,X&&!A){if(D||(N=new ls(Se),D=new as(re,N),N.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),F.setSSEEventCallback((M,Me)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:M,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!q&&Q){let M=(Gr=(Xr=t.features)==null?void 0:Xr.eventStream)==null?void 0:Gr.classNames,Me="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(M!=null&&M.toggleButton?" "+M.toggleButton:"");q=p("button",Me),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let Ge=ie("activity","18px","currentColor",1.5);Ge&&q.appendChild(Ge);let fe=ee.clearChatButtonWrapper,Re=ee.closeButtonWrapper,ht=fe||Re;ht&&ht.parentNode===Q?Q.insertBefore(q,ht):Q.appendChild(q),q.addEventListener("click",()=>{ve?Ne():Le()})}}else!X&&A&&(Ne(),q&&(q.remove(),q=null),D==null||D.clear(),N==null||N.destroy(),D=null,N=null);if(((Qr=t.launcher)==null?void 0:Qr.enabled)===!1&&ne&&(ne.destroy(),ne=null),((Zr=t.launcher)==null?void 0:Zr.enabled)===!1&&ae&&(ae.remove(),ae=null),((eo=t.launcher)==null?void 0:eo.enabled)!==!1&&!ne&&!ae){let M=o.find(Me=>Me.renderLauncher);if(M!=null&&M.renderLauncher){let Me=M.renderLauncher({config:t,defaultRenderer:()=>is(t,B).element,onToggle:B});Me&&(ae=Me,e.appendChild(ae))}ae||(ne=is(t,B),e.appendChild(ne.element))}ne&&ne.update(t),vt&&((to=t.launcher)==null?void 0:to.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((no=t.launcher)==null?void 0:no.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let $=(so=t.layout)==null?void 0:so.header;if(($==null?void 0:$.layout)!==V&&Q){let M=$?Bn(t,$,{showClose:C,onClose:()=>tt(!1,"user")}):rn({config:t,showClose:C,onClose:()=>tt(!1,"user")});Q.replaceWith(M.header),Q=M.header,Ie=M.iconHolder,vt=M.headerTitle,yt=M.headerSubtitle,Y=M.closeButton,V=$==null?void 0:$.layout}else if($&&(Ie&&(Ie.style.display=$.showIcon===!1?"none":""),vt&&(vt.style.display=$.showTitle===!1?"none":""),yt&&(yt.style.display=$.showSubtitle===!1?"none":""),Y&&(Y.style.display=$.showCloseButton===!1?"none":""),ee.clearChatButtonWrapper)){let M=$.showClearChat;if(M!==void 0){ee.clearChatButtonWrapper.style.display=M?"":"none";let{closeButtonWrapper:Me}=ee;Me&&!Me.classList.contains("tvw-absolute")&&(M?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let ce=((ro=t.layout)==null?void 0:ro.showHeader)!==!1;Q&&(Q.style.display=ce?"":"none");let be=((oo=t.layout)==null?void 0:oo.showFooter)!==!1;Oe&&(Oe.style.display=be?"":"none"),C!==k?C?tt(E,"auto"):(y=!0,mn()):E!==S&&tt(E,"auto"),S=E,k=C,Xe(),Et(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&F&&gn(Qe,F.getMessages(),oe);let G=(io=t.launcher)!=null?io:{},I=(ao=G.headerIconHidden)!=null?ao:!1,we=(co=(lo=t.layout)==null?void 0:lo.header)==null?void 0:co.showIcon,xe=I||we===!1,Ve=G.headerIconName,He=(uo=G.headerIconSize)!=null?uo:"48px";if(Ie){let M=ge.querySelector(".tvw-border-b-cw-divider"),Me=M==null?void 0:M.querySelector(".tvw-flex-col");if(xe)Ie.style.display="none",M&&Me&&!M.contains(Me)&&M.insertBefore(Me,M.firstChild);else{if(Ie.style.display="",Ie.style.height=He,Ie.style.width=He,M&&Me&&(M.contains(Ie)?Ie.nextSibling!==Me&&(Ie.remove(),M.insertBefore(Ie,Me)):M.insertBefore(Ie,Me)),Ve){let fe=parseFloat(He)||24,Re=ie(Ve,fe*.6,"#ffffff",2);Re?Ie.replaceChildren(Re):Ie.textContent=(po=G.agentIconText)!=null?po:"\u{1F4AC}"}else if(G.iconUrl){let fe=Ie.querySelector("img");if(fe)fe.src=G.iconUrl,fe.style.height=He,fe.style.width=He;else{let Re=document.createElement("img");Re.src=G.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=He,Re.style.width=He,Ie.replaceChildren(Re)}}else{let fe=Ie.querySelector("svg"),Re=Ie.querySelector("img");(fe||Re)&&Ie.replaceChildren(),Ie.textContent=(go=G.agentIconText)!=null?go:"\u{1F4AC}"}let Ge=Ie.querySelector("img");Ge&&(Ge.style.height=He,Ge.style.width=He)}}let mt=(ho=(mo=t.layout)==null?void 0:mo.header)==null?void 0:ho.showTitle,It=(wo=(fo=t.layout)==null?void 0:fo.header)==null?void 0:wo.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=It===!1?"none":""),Y){((yo=(vo=t.layout)==null?void 0:vo.header)==null?void 0:yo.showCloseButton)===!1?Y.style.display="none":Y.style.display="";let Me=(bo=G.closeButtonSize)!=null?bo:"32px",Ge=(Co=G.closeButtonPlacement)!=null?Co:"inline";Y.style.height=Me,Y.style.width=Me;let{closeButtonWrapper:fe}=ee,Re=Ge==="top-right",ht=fe==null?void 0:fe.classList.contains("tvw-absolute");if(fe&&Re!==ht)if(fe.remove(),Re)fe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",ge.style.position="relative",ge.appendChild(fe);else{let ke=(So=(xo=G.clearChat)==null?void 0:xo.placement)!=null?So:"inline",St=(Eo=(Ao=G.clearChat)==null?void 0:Ao.enabled)!=null?Eo:!0;fe.className=St&&ke==="inline"?"":"tvw-ml-auto";let Ft=ge.querySelector(".tvw-border-b-cw-divider");Ft&&Ft.appendChild(fe)}if(G.closeButtonColor?(Y.style.color=G.closeButtonColor,Y.classList.remove("tvw-text-cw-muted")):(Y.style.color="",Y.classList.add("tvw-text-cw-muted")),G.closeButtonBackgroundColor?(Y.style.backgroundColor=G.closeButtonBackgroundColor,Y.classList.remove("hover:tvw-bg-gray-100")):(Y.style.backgroundColor="",Y.classList.add("hover:tvw-bg-gray-100")),G.closeButtonBorderWidth||G.closeButtonBorderColor){let ke=G.closeButtonBorderWidth||"0px",St=G.closeButtonBorderColor||"transparent";Y.style.border=`${ke} solid ${St}`,Y.classList.remove("tvw-border-none")}else Y.style.border="",Y.classList.add("tvw-border-none");G.closeButtonBorderRadius?(Y.style.borderRadius=G.closeButtonBorderRadius,Y.classList.remove("tvw-rounded-full")):(Y.style.borderRadius="",Y.classList.add("tvw-rounded-full")),G.closeButtonPaddingX?(Y.style.paddingLeft=G.closeButtonPaddingX,Y.style.paddingRight=G.closeButtonPaddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),G.closeButtonPaddingY?(Y.style.paddingTop=G.closeButtonPaddingY,Y.style.paddingBottom=G.closeButtonPaddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let kt=(To=G.closeButtonIconName)!=null?To:"x",Dt=(Mo=G.closeButtonIconText)!=null?Mo:"\xD7";Y.innerHTML="";let Bt=ie(kt,"20px",G.closeButtonColor||"",2);Bt?Y.appendChild(Bt):Y.textContent=Dt;let ot=(Lo=G.closeButtonTooltipText)!=null?Lo:"Close chat",jt=(ko=G.closeButtonShowTooltip)!=null?ko:!0;if(Y.setAttribute("aria-label",ot),fe&&(fe._cleanupTooltip&&(fe._cleanupTooltip(),delete fe._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!Y)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let ss=p("div");ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(ss);let vn=Y.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${vn.left+vn.width/2}px`,ke.style.top=`${vn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};fe.addEventListener("mouseenter",St),fe.addEventListener("mouseleave",Ft),Y.addEventListener("focus",St),Y.addEventListener("blur",Ft),fe._cleanupTooltip=()=>{Ft(),fe&&(fe.removeEventListener("mouseenter",St),fe.removeEventListener("mouseleave",Ft)),Y&&(Y.removeEventListener("focus",St),Y.removeEventListener("blur",Ft))}}}let{clearChatButton:K,clearChatButtonWrapper:je}=ee;if(K){let M=(Wo=G.clearChat)!=null?Wo:{},Me=(Io=M.enabled)!=null?Io:!0,Ge=(Ho=(Po=t.layout)==null?void 0:Po.header)==null?void 0:Ho.showClearChat,fe=Ge!==void 0?Ge:Me,Re=(Bo=M.placement)!=null?Bo:"inline";if(je){je.style.display=fe?"":"none";let{closeButtonWrapper:ht}=ee;ht&&!ht.classList.contains("tvw-absolute")&&(fe?ht.classList.remove("tvw-ml-auto"):ht.classList.add("tvw-ml-auto"));let kt=Re==="top-right",Dt=je.classList.contains("tvw-absolute");if(kt!==Dt&&fe){if(je.remove(),kt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",ge.style.position="relative",ge.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ot=ge.querySelector(".tvw-border-b-cw-divider"),jt=ee.closeButtonWrapper;ot&&jt&&jt.parentElement===ot?ot.insertBefore(je,jt):ot&&ot.appendChild(je)}let Bt=ee.closeButtonWrapper;Bt&&!Bt.classList.contains("tvw-absolute")&&(kt?Bt.classList.add("tvw-ml-auto"):Bt.classList.remove("tvw-ml-auto"))}}if(fe){let ht=(Ro=M.size)!=null?Ro:"32px";K.style.height=ht,K.style.width=ht;let kt=(Fo=M.iconName)!=null?Fo:"refresh-cw",Dt=($o=M.iconColor)!=null?$o:"";K.innerHTML="";let Bt=ie(kt,"20px",Dt||"",2);if(Bt&&K.appendChild(Bt),Dt?(K.style.color=Dt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),M.backgroundColor?(K.style.backgroundColor=M.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let ke=M.borderWidth||"0px",St=M.borderColor||"transparent";K.style.border=`${ke} solid ${St}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");M.borderRadius?(K.style.borderRadius=M.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),M.paddingX?(K.style.paddingLeft=M.paddingX,K.style.paddingRight=M.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),M.paddingY?(K.style.paddingTop=M.paddingY,K.style.paddingBottom=M.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let ot=(Oo=M.tooltipText)!=null?Oo:"Clear chat",jt=(No=M.showTooltip)!=null?No:!0;if(K.setAttribute("aria-label",ot),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!K)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let ss=p("div");ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(ss);let vn=K.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${vn.left+vn.width/2}px`,ke.style.top=`${vn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};je.addEventListener("mouseenter",St),je.addEventListener("mouseleave",Ft),K.addEventListener("focus",St),K.addEventListener("blur",Ft),je._cleanupTooltip=()=>{Ft(),je&&(je.removeEventListener("mouseenter",St),je.removeEventListener("mouseleave",Ft)),K&&(K.removeEventListener("focus",St),K.removeEventListener("blur",Ft))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[cs],zt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[An.message,An.messageAndClick];x=us({parsers:Vt,handlers:zt,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),oe=oa(t,x,H),F.updateConfig(t),gn(Qe,F.getMessages(),oe),an.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),Vn(),Wn(F.isStreaming());let dn=((Do=t.voiceRecognition)==null?void 0:Do.enabled)===!0,Ss=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(dn&&Ss)if(!j||!Ze){let M=bs(t.voiceRecognition,t.sendButton);M&&(j=M.micButton,Ze=M.micButtonWrapper,Mt.insertBefore(Ze,ct),j.addEventListener("click",In),j.disabled=F.isStreaming())}else{let M=(jo=t.voiceRecognition)!=null?jo:{},Me=(_o=t.sendButton)!=null?_o:{},Ge=(qo=M.iconName)!=null?qo:"mic",fe=(zo=Me.size)!=null?zo:"40px",Re=(Uo=M.iconSize)!=null?Uo:fe,ht=parseFloat(Re)||24;j.style.width=Re,j.style.height=Re,j.style.minWidth=Re,j.style.minHeight=Re;let kt=(Ko=(Jo=M.iconColor)!=null?Jo:Me.textColor)!=null?Ko:"currentColor";j.innerHTML="";let Dt=ie(Ge,ht,kt,2);Dt?j.appendChild(Dt):j.textContent="\u{1F3A4}";let Bt=(Yo=M.backgroundColor)!=null?Yo:Me.backgroundColor;Bt?(j.style.backgroundColor=Bt,j.classList.remove("tvw-bg-cw-primary")):(j.style.backgroundColor="",j.classList.add("tvw-bg-cw-primary")),kt?(j.style.color=kt,j.classList.remove("tvw-text-white")):!kt&&!Me.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),M.borderWidth?(j.style.borderWidth=M.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),M.borderColor?j.style.borderColor=M.borderColor:j.style.borderColor="",M.paddingX?(j.style.paddingLeft=M.paddingX,j.style.paddingRight=M.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),M.paddingY?(j.style.paddingTop=M.paddingY,j.style.paddingBottom=M.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let ot=Ze==null?void 0:Ze.querySelector(".tvw-send-button-tooltip"),jt=(Vo=M.tooltipText)!=null?Vo:"Start voice recognition";if(((Xo=M.showTooltip)!=null?Xo:!1)&&jt)if(ot)ot.textContent=jt,ot.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=jt,Ze==null||Ze.insertBefore(St,j)}else ot&&(ot.style.display="none");Ze.style.display="",j.disabled=F.isStreaming()}else j&&Ze&&(Ze.style.display="none",Nt&&qt());if(((Go=t.attachments)==null?void 0:Go.enabled)===!0)if(!z||!We){let M=(Qo=t.attachments)!=null?Qo:{},Ge=(ei=((Zo=t.sendButton)!=null?Zo:{}).size)!=null?ei:"40px";he||(he=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),he.style.display="none",ut.insertBefore(he,me)),R||(R=document.createElement("input"),R.type="file",R.accept=((ti=M.allowedTypes)!=null?ti:cn).join(","),R.multiple=((ni=M.maxFiles)!=null?ni:4)>1,R.style.display="none",R.setAttribute("aria-label","Attach files"),ut.insertBefore(R,me)),z=p("div","tvw-send-button-wrapper"),We=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),We.type="button",We.setAttribute("aria-label",(si=M.buttonTooltipText)!=null?si:"Attach file");let fe=(ri=M.buttonIconName)!=null?ri:"paperclip",Re=Ge,ht=parseFloat(Re)||40,kt=Math.round(ht*.6);We.style.width=Re,We.style.height=Re,We.style.minWidth=Re,We.style.minHeight=Re,We.style.fontSize="18px",We.style.lineHeight="1",We.style.backgroundColor="transparent",We.style.color="var(--cw-primary, #111827)",We.style.border="none",We.style.borderRadius="6px",We.style.transition="background-color 0.15s ease",We.addEventListener("mouseenter",()=>{We.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),We.addEventListener("mouseleave",()=>{We.style.backgroundColor="transparent"});let Dt=ie(fe,kt,"currentColor",1.5);Dt?We.appendChild(Dt):We.textContent="\u{1F4CE}",We.addEventListener("click",jt=>{jt.preventDefault(),R==null||R.click()}),z.appendChild(We);let Bt=(oi=M.buttonTooltipText)!=null?oi:"Attach file",ot=p("div","tvw-send-button-tooltip");ot.textContent=Bt,z.appendChild(ot),Wt.append(z),!ue&&R&&he&&(ue=Cn.fromConfig(M),ue.setPreviewsContainer(he),R.addEventListener("change",async()=>{ue&&(R!=null&&R.files)&&(await ue.handleFileSelect(R.files),R.value="")}))}else{z.style.display="";let M=(ii=t.attachments)!=null?ii:{};R&&(R.accept=((ai=M.allowedTypes)!=null?ai:cn).join(","),R.multiple=((li=M.maxFiles)!=null?li:4)>1),ue&&ue.updateConfig({allowedTypes:M.allowedTypes,maxFileSize:M.maxFileSize,maxFiles:M.maxFiles})}else z&&(z.style.display="none"),ue&&ue.clearAttachments();let dt=(di=t.sendButton)!=null?di:{},As=(ci=dt.useIcon)!=null?ci:!1,Zn=(ui=dt.iconText)!=null?ui:"\u2191",fn=dt.iconName,wn=(pi=dt.tooltipText)!=null?pi:"Send message",ma=(gi=dt.showTooltip)!=null?gi:!1,es=(mi=dt.size)!=null?mi:"40px",Es=dt.backgroundColor,Xt=dt.textColor;if(As){if(J.style.width=es,J.style.height=es,J.style.minWidth=es,J.style.minHeight=es,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",fn){let M=parseFloat(es)||24,Me=Xt&&typeof Xt=="string"&&Xt.trim()?Xt.trim():"currentColor",Ge=ie(fn,M,Me,2);Ge?(J.appendChild(Ge),J.style.color=Me):(J.textContent=Zn,Xt?J.style.color=Xt:J.classList.add("tvw-text-white"))}else J.textContent=Zn,Xt?J.style.color=Xt:J.classList.add("tvw-text-white");J.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Es?(J.style.backgroundColor=Es,J.classList.remove("tvw-bg-cw-primary")):J.classList.add("tvw-bg-cw-primary")}else J.textContent=(fi=(hi=t.copy)==null?void 0:hi.sendButtonLabel)!=null?fi:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Es?(J.style.backgroundColor=Es,J.classList.remove("tvw-bg-cw-accent")):J.classList.add("tvw-bg-cw-accent"),Xt?J.style.color=Xt:J.classList.add("tvw-text-white");dt.borderWidth?(J.style.borderWidth=dt.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),dt.borderColor?J.style.borderColor=dt.borderColor:J.style.borderColor="",dt.paddingX?(J.style.paddingLeft=dt.paddingX,J.style.paddingRight=dt.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),dt.paddingY?(J.style.paddingTop=dt.paddingY,J.style.paddingBottom=dt.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let ts=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(ma&&wn)if(ts)ts.textContent=wn,ts.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=wn,ct==null||ct.insertBefore(M,J)}else ts&&(ts.style.display="none");let ns=(wi=t.statusIndicator)!=null?wi:{},ha=(vi=ns.visible)!=null?vi:!0;if(ft.style.display=ha?"":"none",F){let M=F.getStatus(),Me=Ge=>{var fe,Re,ht,kt;return Ge==="idle"?(fe=ns.idleText)!=null?fe:Pt.idle:Ge==="connecting"?(Re=ns.connectingText)!=null?Re:Pt.connecting:Ge==="connected"?(ht=ns.connectedText)!=null?ht:Pt.connected:Ge==="error"?(kt=ns.errorText)!=null?kt:Pt.error:Pt[Ge]};ft.textContent=Me(M)}},open(){C&&tt(!0,"api")},close(){C&&tt(!1,"api")},toggle(){C&&tt(!y,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(_n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_n}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==_n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()},setMessage(l){return!me||F.isStreaming()?!1:(!y&&C&&tt(!0,"system"),me.value=l,me.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let u=(l==null?void 0:l.trim())||me.value.trim();return u?(!y&&C&&tt(!0,"system"),me.value="",me.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){return Nt||F.isStreaming()||!Qn()?!1:(!y&&C&&tt(!0,"system"),Ke.manuallyDeactivated=!1,en(),hn("user"),!0)},stopVoiceRecognition(){return Nt?(Ke.manuallyDeactivated=!0,en(),qt("user"),!0):!1},injectMessage(l){return!y&&C&&tt(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!y&&C&&tt(!0,"system");let u=F.injectAssistantMessage(l);return O&&(O=!1,W&&(clearTimeout(W),W=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),u},injectUserMessage(l){return!y&&C&&tt(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!y&&C&&tt(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!y&&C&&tt(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!y&&C&&tt(!0,"system"),F.injectTestEvent(l)},__pushEventStreamEvent(l){D&&D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!X||!D||Le()},hideEventStream(){ve&&Ne()},isEventStreamVisible(){return ve},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){c(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return C&&y},isVoiceActive(){return Ke.active},getState(){return{open:C&&y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()}},showCSATFeedback(l){!y&&C&&tt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Us({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitCSATFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!y&&C&&tt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Js({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitNPSFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return F.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return F.submitNPSFeedback(l,u)},destroy(){rt.forEach(l=>l()),Fe.remove(),ne==null||ne.destroy(),ae==null||ae.remove(),Kt&&Y.removeEventListener("click",Kt)}};if((((Br=r==null?void 0:r.debugTools)!=null?Br:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:m,getMessages:m.getMessages,getStatus:m.getStatus,getMetadata:m.getPersistentMetadata,updateMetadata:m.updatePersistentMetadata,clearHistory:()=>m.clearChat(),setVoiceActive:b=>b?m.startVoiceRecognition():m.stopVoiceRecognition()};window.AgentWidgetBrowser=u,rt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(X&&typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.showEventStream()},b=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.hideEventStream()};window.addEventListener("persona:showEventStream",u),window.addEventListener("persona:hideEventStream",b),rt.push(()=>{window.removeEventListener("persona:showEventStream",u),window.removeEventListener("persona:hideEventStream",b)})}let P=al(t.persistState);if(P&&C){let l=ll(P.storage),u=`${P.keyPrefix}widget-open`,b=`${P.keyPrefix}widget-voice`,L=`${P.keyPrefix}widget-voice-mode`;if(l){let A=((Rr=P.persist)==null?void 0:Rr.openState)&&l.getItem(u)==="true",$=((Fr=P.persist)==null?void 0:Fr.voiceState)&&l.getItem(b)==="true",ye=(($r=P.persist)==null?void 0:$r.voiceState)&&l.getItem(L)==="true";if(A&&setTimeout(()=>{m.open(),setTimeout(()=>{var ce;if($||ye)m.startVoiceRecognition();else if((ce=P.persist)!=null&&ce.focusInput){let be=e.querySelector("textarea");be&&be.focus()}},100)},0),(Or=P.persist)!=null&&Or.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Nr=P.persist)!=null&&Nr.voiceState&&(s.on("voice:state",ce=>{l.setItem(b,ce.active?"true":"false")}),s.on("user:message",ce=>{l.setItem(L,ce.viaVoice?"true":"false")})),P.clearOnChatClear){let ce=()=>{l.removeItem(u),l.removeItem(b),l.removeItem(L)},be=()=>ce();window.addEventListener("persona:clear-chat",be),rt.push(()=>{window.removeEventListener("persona:clear-chat",be)})}}}return m};var Cr={},dl=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},cl=()=>{try{if(typeof Cr!="undefined"&&Cr.url)return new URL("../widget.css",Cr.url).href}catch{}return null},ia=e=>{let n=cl(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},xr=e=>{var g,w,c,h;let n=dl(e.target),r=document.createElement("div");r.className="persona-host";let t=(c=(w=(g=e.config)==null?void 0:g.launcher)==null?void 0:w.enabled)!=null?c:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let f=r.attachShadow({mode:"open"});i=f,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),f.appendChild(s),ia(f)}else i=r,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),ia(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=Ks(s,e.config,{debugTools:e.debugTools});(h=e.onReady)==null||h.call(e);let d={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var aa={name:"@runtypelabs/persona",version:"1.44.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 En=aa.version;function on(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function pl(e){if(e)return{getHeaders:on(e.getHeaders),onFeedback:on(e.onFeedback),onCopy:on(e.onCopy),requestMiddleware:on(e.requestMiddleware),actionHandlers:on(e.actionHandlers),actionParsers:on(e.actionParsers),postprocessMessage:on(e.postprocessMessage),contextProviders:on(e.contextProviders),streamParser:on(e.streamParser)}}var la=`({ text, message }: any) => {
61
61
  const jsonSource = (message as any).rawContent || text || message.content;
62
62
  if (!jsonSource || typeof jsonSource !== 'string') return null;
63
63
  let cleanJson = jsonSource