@runtypelabs/persona 1.46.0 → 1.46.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:()=>t,processChunk:async e=>{if(e.length<=n)return t!==null?{text:t,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(t=s),n=e.length,t!==null?{text:t,raw:e}:null},close:async()=>{}}},Ys=t=>{try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Vs=()=>{let t={processChunk:n=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Xs=()=>{var n;let t=Ba();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(n=t.close)==null?void 0:n.bind(t)}},Gs=()=>{let t=null,n=0;return{getExtractedText:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t!==null||t===""?{text:t||"",raw:r}:null;try{let o=(0,dn.parse)(r,dn.STR|dn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?Ks(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=Ks(o.text)))}catch{}return n=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Ri=t=>{let n=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Ks(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ks(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,dn.parse)(s,dn.STR|dn.OBJ),u=o(a);u!==null&&(n=u)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Qs=()=>{let t=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let e=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(t=e[1],{text:t,raw:n}):null},getExtractedText:()=>t}};var Ra="https://api.runtype.com/v1/dispatch",Ar="https://api.runtype.com",Er=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Fa(t){switch(t){case"json":return Gs;case"regex-json":return Xs;case"xml":return Qs;case"plain":default:return Vs}}var Mn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=n.apiUrl)!=null?r:Ra,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(e=n.streamParser)!=null?e:Fa(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 e;let r=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ar;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 e=await this.sessionInitPromise;return this.clientSession=e,(r=(n=this.config).onSessionInit)==null||r.call(n,e),e}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}},e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let a=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):e.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await e.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ar}/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 e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"nps",rating: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 e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let h=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:h}),h}let c=await this.buildPayload(n.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,d={sessionId:u.sessionId,messages:n.messages.filter(Er).map(h=>{var C,b,E;return{id:h.id,role:h.role,content:(E=(b=(C=h.contentParts)!=null?C:h.llmContent)!=null?b:h.rawContent)!=null?E:h.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:e.signal});if(!f.ok){let h=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}if(f.status===429){let b=new Error(h.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let C=new Error(h.error||"Failed to send message");throw r({type:"error",error:C}),C}if(!f.body){let h=new Error("No response body received");throw r({type:"error",error:h}),h}r({type:"status",status:"connected"});try{await this.streamResponse(f.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&r({type:"error",error:c}),c}}async dispatchProxy(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.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:e.signal},o)}catch(a){let u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.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:e.signal},o)}catch(a){let u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(n,r,e){r({type:"status",status:"connected"});try{await this.streamResponse(n,r,e)}finally{r({type:"status",status:"idle"})}}async resolveApproval(n,r){var i;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ar}/v1/agents/${n.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:r,streamResponse:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(Er).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),e={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages: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&&(e.context=o)}return e}async buildPayload(n){let e={messages:n.slice().filter(Er).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&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async handleCustomSSEEvent(n,r,e,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(e.current)return e.current;let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return e.current=u,o(u),u};if(i.text!==void 0){let u=a();u.content+=i.text,o(u)}return i.done&&(e.current&&(e.current.streaming=!1,o(e.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,e){var fe,He,St,ht,Et,Ht,Oe,te,ye,Be,Fe,ze,Ot,de,G,ot,wt,Tt,vt,zt,ee,ke,yt,ce,xe,Je,Bt,Mt,_t,z,et,F,Q,se,$e,U,Ee,je,Ce,D,Te,Xe,lt,vn,pn,ut,Xt,Gn,gn,Gt,O,mn,tn,yn,Qn,nn,sn,Bn,Rn,Ws,Ps,Hs,Zn,Fn,Ke,es,ts,rn,Bs,Rs,ns,bn,on,Fs,$s,Os,yr,xn,Cn,nt,$n,On,ss,rs,os,is,Rt,jt,an,Qt,as,Sn,Kt,Ns,Nn,Ds,_s,ln,Ge,Qe,fn,ls,ds,br,Lt,xr,Ft,cs,us,ps,gs,ms,fs,hs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),u=0,c=()=>a+u++,v=j=>{let Ie=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,De=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,it=j.tools?j.tools.map(pt=>({...pt,chunks:pt.chunks?[...pt.chunks]:void 0})):void 0;return{...j,reasoning:Ie,toolCall:De,tools:it}},d=j=>{r({type:"message",message:v(j)})},f=null,h={current:null},C=new Map,b=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},P=j=>{if(j==null)return null;try{return String(j)}catch{return null}},Y=j=>{var Ie,De,it,pt,At;return P((At=(pt=(it=(De=(Ie=j.stepId)!=null?Ie:j.step_id)!=null?De:j.step)!=null?it:j.parentId)!=null?pt:j.flowStepId)!=null?At:j.flow_step_id)},T=j=>{var Ie,De,it,pt,At,st,m;return P((m=(st=(At=(pt=(it=(De=(Ie=j.callId)!=null?Ie:j.call_id)!=null?De:j.requestId)!=null?it:j.request_id)!=null?pt:j.toolCallId)!=null?At:j.tool_call_id)!=null?st:j.stepId)!=null?m:j.step_id)},I=()=>f||(f={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f),M=(j,Ie)=>{E.lastId=Ie,j&&E.byStep.set(j,Ie)},R=(j,Ie)=>{var At;let De=(At=j.reasoningId)!=null?At:j.id,it=Y(j);if(De){let st=String(De);return M(it,st),st}if(it){let st=E.byStep.get(it);if(st)return E.lastId=st,st}if(E.lastId&&!Ie)return E.lastId;if(!Ie)return null;let pt=`reason-${c()}`;return M(it,pt),pt},ie=j=>{let Ie=C.get(j);if(Ie)return Ie;let De={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:j,status:"streaming",chunks:[]}};return C.set(j,De),d(De),De},K=(j,Ie)=>{x.lastId=Ie,j&&x.byCall.set(j,Ie)},q=(j,Ie)=>{var At;let De=(At=j.toolId)!=null?At:j.id,it=T(j);if(De){let st=String(De);return K(it,st),st}if(it){let st=x.byCall.get(it);if(st)return x.lastId=st,st}if(x.lastId&&!Ie)return x.lastId;if(!Ie)return null;let pt=`tool-${c()}`;return K(it,pt),pt},V=j=>{let Ie=b.get(j);if(Ie)return Ie;let De={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:j,status:"pending"}};return b.set(j,De),d(De),De},N=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let Ie=Number(j);if(!Number.isNaN(Ie)&&Number.isFinite(Ie))return Ie;let De=Date.parse(j);if(!Number.isNaN(De))return De}return Date.now()},me=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},_=new Map,J=new Map,X=null,$=new Map,ae=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(;;){let{done:j,value:Ie}=await o.read();if(j)break;i+=s.decode(Ie,{stream:!0});let De=i.split(`
5
5
 
6
6
  `);i=(He=De.pop())!=null?He:"";for(let it of De){let pt=it.split(`
7
- `),At="message",st="";for(let B of pt)B.startsWith("event:")?At=B.replace("event:","").trim():B.startsWith("data:")&&(st+=B.replace("data:","").trim());if(!st)continue;let m;try{m=JSON.parse(st)}catch(B){r({type:"error",error:B instanceof Error?B:new Error("Failed to parse chat stream payload")});continue}let We=At!=="message"?At:(St=m.type)!=null?St:"message";if((ht=this.onSSEEvent)==null||ht.call(this,We,m),this.parseSSEEvent){h.current=f;let B=await this.handleCustomSSEEvent(m,r,h,d,c);if(h.current&&!f&&(f=h.current),B)continue}if(We==="reason_start"){let B=(Et=R(m,!0))!=null?Et:`reason-${c()}`,y=ie(B);y.reasoning=(Ht=y.reasoning)!=null?Ht:{id:B,status:"streaming",chunks:[]},y.reasoning.startedAt=(te=y.reasoning.startedAt)!=null?te:N((Oe=m.startedAt)!=null?Oe:m.timestamp),y.reasoning.completedAt=void 0,y.reasoning.durationMs=void 0,y.streaming=!0,y.reasoning.status="streaming",d(y)}else if(We==="reason_delta"||We==="reason_chunk"){let B=(Be=(ye=R(m,!1))!=null?ye:R(m,!0))!=null?Be:`reason-${c()}`,y=ie(B);y.reasoning=(Fe=y.reasoning)!=null?Fe:{id:B,status:"streaming",chunks:[]},y.reasoning.startedAt=(Ot=y.reasoning.startedAt)!=null?Ot:N((ze=m.startedAt)!=null?ze:m.timestamp);let L=(ot=(G=(de=m.reasoningText)!=null?de:m.text)!=null?G:m.delta)!=null?ot:"";if(L&&m.hidden!==!0&&y.reasoning.chunks.push(String(L)),y.reasoning.status=m.done?"complete":"streaming",m.done){y.reasoning.completedAt=N((wt=m.completedAt)!=null?wt:m.timestamp);let oe=(Tt=y.reasoning.startedAt)!=null?Tt:Date.now();y.reasoning.durationMs=Math.max(0,((vt=y.reasoning.completedAt)!=null?vt:Date.now())-oe)}y.streaming=y.reasoning.status!=="complete",d(y)}else if(We==="reason_complete"){let B=(ee=(zt=R(m,!1))!=null?zt:R(m,!0))!=null?ee:`reason-${c()}`,y=C.get(B);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=N((ke=m.completedAt)!=null?ke:m.timestamp);let oe=(yt=y.reasoning.startedAt)!=null?yt:Date.now();y.reasoning.durationMs=Math.max(0,((ce=y.reasoning.completedAt)!=null?ce:Date.now())-oe),y.streaming=!1,d(y)}let L=Y(m);L&&E.byStep.delete(L)}else if(We==="tool_start"){let B=(xe=q(m,!0))!=null?xe:`tool-${c()}`,y=V(B),L=(Je=y.toolCall)!=null?Je:{id:B,status:"pending"};L.name=(Bt=m.toolName)!=null?Bt:L.name,L.status="running",m.args!==void 0?L.args=m.args:m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=(_t=L.startedAt)!=null?_t:N((Mt=m.startedAt)!=null?Mt:m.timestamp),L.completedAt=void 0,L.durationMs=void 0,y.toolCall=L,y.streaming=!0;let oe=m.agentContext;(oe||m.executionId)&&(y.agentMetadata={executionId:(z=oe==null?void 0:oe.executionId)!=null?z:m.executionId,iteration:(et=oe==null?void 0:oe.iteration)!=null?et:m.iteration}),d(y)}else if(We==="tool_chunk"||We==="tool_delta"){let B=(Q=(F=q(m,!1))!=null?F:q(m,!0))!=null?Q:`tool-${c()}`,y=V(B),L=(se=y.toolCall)!=null?se:{id:B,status:"running"};L.startedAt=(U=L.startedAt)!=null?U:N(($e=m.startedAt)!=null?$e:m.timestamp);let oe=(Ce=(je=(Ee=m.text)!=null?Ee:m.delta)!=null?je:m.message)!=null?Ce:"";oe&&(L.chunks=(D=L.chunks)!=null?D:[],L.chunks.push(String(oe))),L.status="running",y.toolCall=L,y.streaming=!0;let Se=m.agentContext;(Se||m.executionId)&&(y.agentMetadata=(lt=y.agentMetadata)!=null?lt:{executionId:(Te=Se==null?void 0:Se.executionId)!=null?Te:m.executionId,iteration:(Xe=Se==null?void 0:Se.iteration)!=null?Xe:m.iteration}),d(y)}else if(We==="tool_complete"){let B=(pn=(vn=q(m,!1))!=null?vn:q(m,!0))!=null?pn:`tool-${c()}`,y=V(B),L=(ut=y.toolCall)!=null?ut:{id:B,status:"running"};L.status="complete",m.result!==void 0&&(L.result=m.result),typeof m.duration=="number"&&(L.duration=m.duration),L.completedAt=N((Xt=m.completedAt)!=null?Xt:m.timestamp);let oe=(Gn=m.duration)!=null?Gn:m.executionTime;if(typeof oe=="number")L.durationMs=oe;else{let It=(gn=L.startedAt)!=null?gn:Date.now();L.durationMs=Math.max(0,((Gt=L.completedAt)!=null?Gt:Date.now())-It)}y.toolCall=L,y.streaming=!1;let Se=m.agentContext;(Se||m.executionId)&&(y.agentMetadata=(tn=y.agentMetadata)!=null?tn:{executionId:(O=Se==null?void 0:Se.executionId)!=null?O:m.executionId,iteration:(mn=Se==null?void 0:Se.iteration)!=null?mn:m.iteration}),d(y);let Ye=T(m);Ye&&x.byCall.delete(Ye)}else if(We==="step_chunk"||We==="step_delta"){let B=m.stepType,y=m.executionType;if(B==="tool"||y==="context")continue;let L=I(),oe=(sn=(nn=(Qn=(yn=m.text)!=null?yn:m.delta)!=null?Qn:m.content)!=null?nn:m.chunk)!=null?sn:"";if(oe){let Ye=((Bn=J.get(L.id))!=null?Bn:"")+oe;L.rawContent=Ye,_.has(L.id)||_.set(L.id,this.createStreamParser());let It=_.get(L.id),rt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(rt&&J.set(L.id,Ye),It.__isPlainTextParser===!0){L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L);continue}let gt=It.processChunk(Ye);if(gt instanceof Promise)gt.then(Ne=>{var dt;let qe=typeof Ne=="string"?Ne:(dt=Ne==null?void 0:Ne.text)!=null?dt:null;if(qe!==null&&qe.trim()!==""){let Ue=f;Ue&&Ue.id===L.id&&(Ue.content=qe,d(Ue))}else if(!rt&&!Ye.trim().startsWith("<")){let Ue=f;Ue&&Ue.id===L.id&&(Ue.content+=oe,J.delete(Ue.id),_.delete(Ue.id),Ue.rawContent=void 0,d(Ue))}}).catch(()=>{L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L)});else{let Ne=typeof gt=="string"?gt:(Rn=gt==null?void 0:gt.text)!=null?Rn:null;Ne!==null&&Ne.trim()!==""?(L.content=Ne,d(L)):!rt&&!Ye.trim().startsWith("<")&&(L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L))}}if(m.isComplete){let Se=(Ps=(Ws=m.result)==null?void 0:Ws.response)!=null?Ps:L.content;if(Se){let Ye=J.get(L.id),It=Ye!=null?Ye:me(Se);L.rawContent=It;let rt=_.get(L.id),bt=null,gt=!1;if(rt&&(bt=rt.getExtractedText(),bt===null&&(bt=Ys(It)),bt===null)){let Ne=rt.processChunk(It);Ne instanceof Promise?(gt=!0,Ne.then(qe=>{var Ue;let dt=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(dt!==null){let xt=f;xt&&xt.id===L.id&&(xt.content=dt,xt.streaming=!1,_.delete(xt.id),J.delete(xt.id),d(xt))}})):bt=typeof Ne=="string"?Ne:(Hs=Ne==null?void 0:Ne.text)!=null?Hs:null}if(!gt){bt!==null&&bt.trim()!==""?L.content=bt:J.has(L.id)||(L.content=me(Se));let Ne=_.get(L.id);if(Ne){let qe=(Zn=Ne.close)==null?void 0:Zn.call(Ne);qe instanceof Promise&&qe.catch(()=>{}),_.delete(L.id)}J.delete(L.id),L.streaming=!1,d(L)}}}}else if(We==="step_complete"){let B=m.stepType,y=m.executionType;if(B==="tool"||y==="context")continue;let L=(Fn=m.result)==null?void 0:Fn.response,oe=I();if(L!=null){let Se=_.get(oe.id),Ye=!1,It=!1;if(Se){let rt=Se.getExtractedText(),bt=J.get(oe.id),gt=bt!=null?bt:me(L);if(oe.rawContent=gt,rt!==null&&rt.trim()!=="")oe.content=rt,Ye=!0;else{let Ne=Ys(gt);if(Ne!==null)oe.content=Ne,Ye=!0;else{let qe=Se.processChunk(gt);if(qe instanceof Promise)It=!0,qe.then(dt=>{var xt;let Ue=typeof dt=="string"?dt:(xt=dt==null?void 0:dt.text)!=null?xt:null;if(Ue!==null&&Ue.trim()!==""){let Nt=f;Nt&&Nt.id===oe.id&&(Nt.content=Ue,Nt.streaming=!1,_.delete(Nt.id),J.delete(Nt.id),d(Nt))}else{let Nt=Se.getExtractedText(),Jt=f;Jt&&Jt.id===oe.id&&(Nt!==null&&Nt.trim()!==""?Jt.content=Nt:J.has(Jt.id)||(Jt.content=me(L)),Jt.streaming=!1,_.delete(Jt.id),J.delete(Jt.id),d(Jt))}});else{let dt=typeof qe=="string"?qe:(Ke=qe==null?void 0:qe.text)!=null?Ke:null;if(dt!==null&&dt.trim()!=="")oe.content=dt,Ye=!0;else{let Ue=Se.getExtractedText();Ue!==null&&Ue.trim()!==""&&(oe.content=Ue,Ye=!0)}}}}}if(!It){if(!oe.rawContent){let rt=J.get(oe.id);oe.rawContent=rt!=null?rt:me(L)}if(!Ye&&!J.has(oe.id)&&(oe.content=me(L)),Se){let rt=(es=Se.close)==null?void 0:es.call(Se);rt instanceof Promise&&rt.catch(()=>{})}_.delete(oe.id),J.delete(oe.id),oe.streaming=!1,d(oe)}}else _.delete(oe.id),J.delete(oe.id),oe.streaming=!1,d(oe)}else if(We==="flow_complete"){let B=(ts=m.result)==null?void 0:ts.response;if(B!=null){let y=I(),L=J.get(y.id),oe=L!=null?L:me(B);y.rawContent=oe;let Se=me(B),Ye=_.get(y.id);if(Ye){let bt=Ys(oe);if(bt!==null)Se=bt;else{let gt=Ye.processChunk(oe);gt instanceof Promise&&gt.then(qe=>{var Ue;let dt=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(dt!==null){let xt=f;xt&&xt.id===y.id&&(xt.content=dt,xt.streaming=!1,d(xt))}});let Ne=Ye.getExtractedText();Ne!==null&&(Se=Ne)}}_.delete(y.id),J.delete(y.id);let It=Se!==y.content,rt=y.streaming!==!1;It&&(y.content=Se),y.streaming=!1,(It||rt)&&d(y)}else if(f!==null){let y=f;_.delete(y.id),J.delete(y.id),y.streaming!==!1&&(y.streaming=!1,d(y))}r({type:"status",status:"idle"})}else if(We==="agent_start")X={executionId:m.executionId,agentId:(rn=m.agentId)!=null?rn:"virtual",agentName:(Bs=m.agentName)!=null?Bs:"",status:"running",currentIteration:0,maxIterations:(Rs=m.maxIterations)!=null?Rs:1,startedAt:N(m.startedAt)};else if(We==="agent_iteration_start"){if(X&&(X.currentIteration=m.iteration),ae==="separate"&&m.iteration>1){let B=f;B&&(B.streaming=!1,d(B),$.set(m.iteration-1,B),f=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(m.contentType==="text"){let B=I();B.content+=(ns=m.delta)!=null?ns:"",B.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:X==null?void 0:X.agentName},d(B)}else if(m.contentType==="thinking"){let B=(bn=m.turnId)!=null?bn:`agent-think-${m.iteration}`,y=ie(B);y.reasoning=(on=y.reasoning)!=null?on:{id:B,status:"streaming",chunks:[]},y.reasoning.chunks.push((Fs=m.delta)!=null?Fs:""),y.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},d(y)}else if(m.contentType==="tool_input"){let B=($s=m.toolCallId)!=null?$s:x.lastId;if(B){let y=b.get(B);y!=null&&y.toolCall&&(y.toolCall.chunks=(Os=y.toolCall.chunks)!=null?Os:[],y.toolCall.chunks.push((yr=m.delta)!=null?yr:""),d(y))}}}else if(We==="agent_turn_complete"){let B=m.turnId;if(B){let y=C.get(B);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=N(m.completedAt);let L=(xn=y.reasoning.startedAt)!=null?xn:Date.now();y.reasoning.durationMs=Math.max(0,((Cn=y.reasoning.completedAt)!=null?Cn:Date.now())-L),y.streaming=!1,d(y)}}}else if(We==="agent_tool_start"){let B=(nt=m.toolCallId)!=null?nt:`agent-tool-${c()}`;K(T(m),B);let y=V(B),L=($n=y.toolCall)!=null?$n:{id:B,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};L.name=(On=m.toolName)!=null?On:L.name,L.status="running",m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=N((ss=m.startedAt)!=null?ss:m.timestamp),y.toolCall=L,y.streaming=!0,y.agentMetadata={executionId:m.executionId,iteration:m.iteration},d(y)}else if(We==="agent_tool_delta"){let B=(rs=m.toolCallId)!=null?rs:x.lastId;if(B){let y=(os=b.get(B))!=null?os:V(B);y.toolCall&&(y.toolCall.chunks=(is=y.toolCall.chunks)!=null?is:[],y.toolCall.chunks.push((Rt=m.delta)!=null?Rt:""),y.toolCall.status="running",y.streaming=!0,d(y))}}else if(We==="agent_tool_complete"){let B=(jt=m.toolCallId)!=null?jt:x.lastId;if(B){let y=(an=b.get(B))!=null?an:V(B);if(y.toolCall){y.toolCall.status="complete",m.result!==void 0&&(y.toolCall.result=m.result),typeof m.executionTime=="number"&&(y.toolCall.durationMs=m.executionTime),y.toolCall.completedAt=N((Qt=m.completedAt)!=null?Qt:m.timestamp),y.streaming=!1,d(y);let L=T(m);L&&x.byCall.delete(L)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let B=`agent-reflection-${m.executionId}-${m.iteration}`,y={id:B,role:"assistant",content:(as=m.reflection)!=null?as:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"complete",chunks:[(Sn=m.reflection)!=null?Sn:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};d(y)}else if(We==="agent_complete"){X&&(X.status=m.success?"complete":"error",X.completedAt=N(m.completedAt),X.stopReason=m.stopReason);let B=f;B&&(B.streaming=!1,d(B)),r({type:"status",status:"idle"})}else if(We==="agent_error"){let B=typeof m.error=="string"?m.error:(Ns=(Kt=m.error)==null?void 0:Kt.message)!=null?Ns:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",B):r({type:"error",error:new Error(B)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let B=(Nn=m.approvalId)!=null?Nn:`approval-${c()}`,y={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(Ds=X==null?void 0:X.agentId)!=null?Ds:"virtual",executionId:(ln=(_s=m.executionId)!=null?_s:X==null?void 0:X.executionId)!=null?ln:"",toolName:(Ge=m.toolName)!=null?Ge:"",toolType:m.toolType,description:(fn=m.description)!=null?fn:`Execute ${(Qe=m.toolName)!=null?Qe:"tool"}`,parameters:m.parameters}};d(y)}else if(We==="step_await"&&m.awaitReason==="approval_required"){let B=(ls=m.approvalId)!=null?ls:`approval-${c()}`,y={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(ds=X==null?void 0:X.agentId)!=null?ds:"virtual",executionId:(Lt=(br=m.executionId)!=null?br:X==null?void 0:X.executionId)!=null?Lt:"",toolName:(xr=m.toolName)!=null?xr:"",toolType:m.toolType,description:(cs=m.description)!=null?cs:`Execute ${(Ft=m.toolName)!=null?Ft:"tool"}`,parameters:m.parameters}};d(y)}else if(We==="agent_approval_complete"){let B=m.approvalId;if(B){let L={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:(us=m.decision)!=null?us:"approved",agentId:(ps=X==null?void 0:X.agentId)!=null?ps:"virtual",executionId:(ms=(gs=m.executionId)!=null?gs:X==null?void 0:X.executionId)!=null?ms:"",toolName:(fs=m.toolName)!=null?fs:"",description:(hs=m.description)!=null?hs:"",resolvedAt:Date.now()}};d(L)}}else We==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}}};function Fi(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${t}_${n}`}function Dn(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${t}_${n}`}function Ln(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${t}_${n}`}var Zs="[Image]";function $i(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Oi(t){return typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.text).join("")}function Ni(t){return typeof t=="string"?!1:t.some(n=>n.type==="image")}function Di(t){return typeof t=="string"?[]:t.filter(n=>n.type==="image")}function er(t){return{type:"text",text:t}}function _i(t,n){return{type:"image",image:t,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function ji(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;n({type:"image",image:o,mimeType:t.type,alt:t.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(t)})}function qi(t,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(t.type)?t.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 Ui=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],$a=["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"],wn=[...Ui,...$a];function Oa(t){return Ui.includes(t)||t.startsWith("image/")}function tr(t){return Oa(t.type)}async function zi(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;tr(t)?n({type:"image",image:o,mimeType:t.type,alt:t.name}):n({type:"file",data:o,mimeType:t.type,filename:t.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(t)})}function Ji(t,n=wn,r=10*1024*1024){return n.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${n.join(", ")}`}}function Na(t){let n=t.split(".");return n.length>1?n.pop().toLowerCase():""}function Ki(t,n){let r=Na(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"}[t]||r||"FILE"}var _n=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,e,o,s,i,a,u;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:(e=n.message.agentMetadata.agentName)!=null?e:"",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"),(u=(a=this.callbacks).onError)==null||u.call(a,n.error))};var e;this.messages=[...(e=n.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Mn(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 e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(n=this.callbacks).onError)==null||r.call(n,e instanceof Error?e:new Error(String(e))),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 Mn(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:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:u,streaming:c=!1}=n,d={id:i!=null?i:r==="user"?Dn():r==="assistant"?Ln():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(d),d}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 e of n){let{role:o,content:s,llmContent:i,contentParts:a,id:u,createdAt:c,sequence:v,streaming:d=!1}=e,h={id:u!=null?u:o==="user"?Dn():o==="assistant"?Ln():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:d,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(h)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var c,v,d,f,h;let e=n.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(c=this.abortController)==null||c.abort();let o=Dn(),s=Ln(),i={id:o,role:"user",content:e||Zs,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(C){let b=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!b){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,b||(C instanceof Error?(d=(v=this.callbacks).onError)==null||d.call(v,C):(h=(f=this.callbacks).onError)==null||h.call(f,new Error(String(C))))}}async continueConversation(){var o,s,i,a,u;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=Ln();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let e=[...this.messages];try{await this.client.dispatch({messages:e,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(c){let v={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(v),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,c):(u=(a=this.callbacks).onError)==null||u.call(a,new Error(String(c)))}}async connectStream(n,r){var e,o,s;if(!this.streaming){(e=this.abortController)==null||e.abort(),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(s=(o=this.callbacks).onError)==null||s.call(o,i instanceof Error?i:new Error(String(i)))}}}async resolveApproval(n,r){var u,c,v;let e=`approval-${n.id}`,o={...n,status:r,resolvedAt:Date.now()},s={id:e,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let i=this.config.approval,a=i&&typeof i=="object"?i.onDecision:void 0;try{let d;if(a?d=await a({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},r):d=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},r),d){let f=null;if(d instanceof Response){if(!d.ok){let h=await d.json().catch(()=>null);throw new Error((u=h==null?void 0:h.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):r==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(v=(c=this.callbacks).onError)==null||v.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var 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(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(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),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,e)=>{var u,c;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(u=r.sequence)!=null?u:0,a=(c=e.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(e.id)})}};var p=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Da=La(require("lucide"),1),re=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Da[o];return s?_a(s,n,r,e):(console.warn(`Lucide icon "${t}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${t}":`,o),null}};function _a(t,n,r,e){if(!t||!Array.isArray(t))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(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,v])=>{c!=="stroke"&&u.setAttribute(c,String(v))}),o.appendChild(u)}}}),o}var nr={allowedTypes:wn,maxFileSize:10*1024*1024,maxFiles:4};function ja(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function qa(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-json":"file"}var In=class t{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:nr.allowedTypes,maxFileSize:(e=n.maxFileSize)!=null?e:nr.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:nr.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:nr.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var r,e,o,s,i,a,u;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=Ji(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let d=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,d);continue}try{let d=await zi(c),f=tr(c)?URL.createObjectURL(c):null,h={id:ja(),file:c,previewUrl:f,contentPart:d};this.attachments.push(h),this.renderPreview(h)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(a=this.config).onAttachmentsChange)==null||u.call(a,this.getAttachments())}}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(u=>u.id===n);if(r===-1)return;let e=this.attachments[r];e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.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=tr(n.file),e=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",n.id),e.style.width="48px",e.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",e.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=qa(n.file.type),u=re(a,20,"var(--cw-muted, #6b7280)",1.5);u&&i.appendChild(u);let c=p("span");c.textContent=Ki(n.file.type,n.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--cw-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),e.appendChild(i)}let o=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=re("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new t({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 Tr=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ua=t=>{var s,i,a;let n=(s=t==null?void 0:t.colorScheme)!=null?s:"light",r=(i=t==null?void 0:t.theme)!=null?i:{},e=(a=t==null?void 0:t.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||Tr()==="dark"?e:r},Yi=t=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Tr())});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)"),e=()=>t(Tr());r.addEventListener?(r.addEventListener("change",e),n.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),n.push(()=>r.removeListener(e)))}return()=>{n.forEach(r=>r())}},sr=(t,n)=>{let r=Ua(n);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);t.style.setProperty(`--cw-${s}`,String(o))})};var Vi=require("idiomorph"),Xi=(t,n,r={})=>{let{preserveTypingAnimation:e=!0}=r;Vi.Idiomorph.morph(t,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&e&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Vt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Es=(t,n)=>{let r=p("button");r.type="button",r.innerHTML=`
7
+ `),At="message",st="";for(let B of pt)B.startsWith("event:")?At=B.replace("event:","").trim():B.startsWith("data:")&&(st+=B.replace("data:","").trim());if(!st)continue;let m;try{m=JSON.parse(st)}catch(B){r({type:"error",error:B instanceof Error?B:new Error("Failed to parse chat stream payload")});continue}let We=At!=="message"?At:(St=m.type)!=null?St:"message";if((ht=this.onSSEEvent)==null||ht.call(this,We,m),this.parseSSEEvent){h.current=f;let B=await this.handleCustomSSEEvent(m,r,h,d,c);if(h.current&&!f&&(f=h.current),B)continue}if(We==="reason_start"){let B=(Et=R(m,!0))!=null?Et:`reason-${c()}`,y=ie(B);y.reasoning=(Ht=y.reasoning)!=null?Ht:{id:B,status:"streaming",chunks:[]},y.reasoning.startedAt=(te=y.reasoning.startedAt)!=null?te:N((Oe=m.startedAt)!=null?Oe:m.timestamp),y.reasoning.completedAt=void 0,y.reasoning.durationMs=void 0,y.streaming=!0,y.reasoning.status="streaming",d(y)}else if(We==="reason_delta"||We==="reason_chunk"){let B=(Be=(ye=R(m,!1))!=null?ye:R(m,!0))!=null?Be:`reason-${c()}`,y=ie(B);y.reasoning=(Fe=y.reasoning)!=null?Fe:{id:B,status:"streaming",chunks:[]},y.reasoning.startedAt=(Ot=y.reasoning.startedAt)!=null?Ot:N((ze=m.startedAt)!=null?ze:m.timestamp);let L=(ot=(G=(de=m.reasoningText)!=null?de:m.text)!=null?G:m.delta)!=null?ot:"";if(L&&m.hidden!==!0&&y.reasoning.chunks.push(String(L)),y.reasoning.status=m.done?"complete":"streaming",m.done){y.reasoning.completedAt=N((wt=m.completedAt)!=null?wt:m.timestamp);let oe=(Tt=y.reasoning.startedAt)!=null?Tt:Date.now();y.reasoning.durationMs=Math.max(0,((vt=y.reasoning.completedAt)!=null?vt:Date.now())-oe)}y.streaming=y.reasoning.status!=="complete",d(y)}else if(We==="reason_complete"){let B=(ee=(zt=R(m,!1))!=null?zt:R(m,!0))!=null?ee:`reason-${c()}`,y=C.get(B);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=N((ke=m.completedAt)!=null?ke:m.timestamp);let oe=(yt=y.reasoning.startedAt)!=null?yt:Date.now();y.reasoning.durationMs=Math.max(0,((ce=y.reasoning.completedAt)!=null?ce:Date.now())-oe),y.streaming=!1,d(y)}let L=Y(m);L&&E.byStep.delete(L)}else if(We==="tool_start"){let B=(xe=q(m,!0))!=null?xe:`tool-${c()}`,y=V(B),L=(Je=y.toolCall)!=null?Je:{id:B,status:"pending"};L.name=(Bt=m.toolName)!=null?Bt:L.name,L.status="running",m.args!==void 0?L.args=m.args:m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=(_t=L.startedAt)!=null?_t:N((Mt=m.startedAt)!=null?Mt:m.timestamp),L.completedAt=void 0,L.durationMs=void 0,y.toolCall=L,y.streaming=!0;let oe=m.agentContext;(oe||m.executionId)&&(y.agentMetadata={executionId:(z=oe==null?void 0:oe.executionId)!=null?z:m.executionId,iteration:(et=oe==null?void 0:oe.iteration)!=null?et:m.iteration}),d(y)}else if(We==="tool_chunk"||We==="tool_delta"){let B=(Q=(F=q(m,!1))!=null?F:q(m,!0))!=null?Q:`tool-${c()}`,y=V(B),L=(se=y.toolCall)!=null?se:{id:B,status:"running"};L.startedAt=(U=L.startedAt)!=null?U:N(($e=m.startedAt)!=null?$e:m.timestamp);let oe=(Ce=(je=(Ee=m.text)!=null?Ee:m.delta)!=null?je:m.message)!=null?Ce:"";oe&&(L.chunks=(D=L.chunks)!=null?D:[],L.chunks.push(String(oe))),L.status="running",y.toolCall=L,y.streaming=!0;let Se=m.agentContext;(Se||m.executionId)&&(y.agentMetadata=(lt=y.agentMetadata)!=null?lt:{executionId:(Te=Se==null?void 0:Se.executionId)!=null?Te:m.executionId,iteration:(Xe=Se==null?void 0:Se.iteration)!=null?Xe:m.iteration}),d(y)}else if(We==="tool_complete"){let B=(pn=(vn=q(m,!1))!=null?vn:q(m,!0))!=null?pn:`tool-${c()}`,y=V(B),L=(ut=y.toolCall)!=null?ut:{id:B,status:"running"};L.status="complete",m.result!==void 0&&(L.result=m.result),typeof m.duration=="number"&&(L.duration=m.duration),L.completedAt=N((Xt=m.completedAt)!=null?Xt:m.timestamp);let oe=(Gn=m.duration)!=null?Gn:m.executionTime;if(typeof oe=="number")L.durationMs=oe;else{let It=(gn=L.startedAt)!=null?gn:Date.now();L.durationMs=Math.max(0,((Gt=L.completedAt)!=null?Gt:Date.now())-It)}y.toolCall=L,y.streaming=!1;let Se=m.agentContext;(Se||m.executionId)&&(y.agentMetadata=(tn=y.agentMetadata)!=null?tn:{executionId:(O=Se==null?void 0:Se.executionId)!=null?O:m.executionId,iteration:(mn=Se==null?void 0:Se.iteration)!=null?mn:m.iteration}),d(y);let Ye=T(m);Ye&&x.byCall.delete(Ye)}else if(We==="step_chunk"||We==="step_delta"){let B=m.stepType,y=m.executionType;if(B==="tool"||y==="context")continue;let L=I(),oe=(sn=(nn=(Qn=(yn=m.text)!=null?yn:m.delta)!=null?Qn:m.content)!=null?nn:m.chunk)!=null?sn:"";if(oe){let Ye=((Bn=J.get(L.id))!=null?Bn:"")+oe;L.rawContent=Ye,_.has(L.id)||_.set(L.id,this.createStreamParser());let It=_.get(L.id),rt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(rt&&J.set(L.id,Ye),It.__isPlainTextParser===!0){L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L);continue}let gt=It.processChunk(Ye);if(gt instanceof Promise)gt.then(Ne=>{var dt;let qe=typeof Ne=="string"?Ne:(dt=Ne==null?void 0:Ne.text)!=null?dt:null;if(qe!==null&&qe.trim()!==""){let Ue=f;Ue&&Ue.id===L.id&&(Ue.content=qe,d(Ue))}else if(!rt&&!Ye.trim().startsWith("<")){let Ue=f;Ue&&Ue.id===L.id&&(Ue.content+=oe,J.delete(Ue.id),_.delete(Ue.id),Ue.rawContent=void 0,d(Ue))}}).catch(()=>{L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L)});else{let Ne=typeof gt=="string"?gt:(Rn=gt==null?void 0:gt.text)!=null?Rn:null;Ne!==null&&Ne.trim()!==""?(L.content=Ne,d(L)):!rt&&!Ye.trim().startsWith("<")&&(L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L))}}if(m.isComplete){let Se=(Ps=(Ws=m.result)==null?void 0:Ws.response)!=null?Ps:L.content;if(Se){let Ye=J.get(L.id),It=Ye!=null?Ye:me(Se);L.rawContent=It;let rt=_.get(L.id),bt=null,gt=!1;if(rt&&(bt=rt.getExtractedText(),bt===null&&(bt=Ys(It)),bt===null)){let Ne=rt.processChunk(It);Ne instanceof Promise?(gt=!0,Ne.then(qe=>{var Ue;let dt=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(dt!==null){let xt=f;xt&&xt.id===L.id&&(xt.content=dt,xt.streaming=!1,_.delete(xt.id),J.delete(xt.id),d(xt))}})):bt=typeof Ne=="string"?Ne:(Hs=Ne==null?void 0:Ne.text)!=null?Hs:null}if(!gt){bt!==null&&bt.trim()!==""?L.content=bt:J.has(L.id)||(L.content=me(Se));let Ne=_.get(L.id);if(Ne){let qe=(Zn=Ne.close)==null?void 0:Zn.call(Ne);qe instanceof Promise&&qe.catch(()=>{}),_.delete(L.id)}J.delete(L.id),L.streaming=!1,d(L)}}}}else if(We==="step_complete"){let B=m.stepType,y=m.executionType;if(B==="tool"||y==="context")continue;let L=(Fn=m.result)==null?void 0:Fn.response,oe=I();if(L!=null){let Se=_.get(oe.id),Ye=!1,It=!1;if(Se){let rt=Se.getExtractedText(),bt=J.get(oe.id),gt=bt!=null?bt:me(L);if(oe.rawContent=gt,rt!==null&&rt.trim()!=="")oe.content=rt,Ye=!0;else{let Ne=Ys(gt);if(Ne!==null)oe.content=Ne,Ye=!0;else{let qe=Se.processChunk(gt);if(qe instanceof Promise)It=!0,qe.then(dt=>{var xt;let Ue=typeof dt=="string"?dt:(xt=dt==null?void 0:dt.text)!=null?xt:null;if(Ue!==null&&Ue.trim()!==""){let Nt=f;Nt&&Nt.id===oe.id&&(Nt.content=Ue,Nt.streaming=!1,_.delete(Nt.id),J.delete(Nt.id),d(Nt))}else{let Nt=Se.getExtractedText(),Jt=f;Jt&&Jt.id===oe.id&&(Nt!==null&&Nt.trim()!==""?Jt.content=Nt:J.has(Jt.id)||(Jt.content=me(L)),Jt.streaming=!1,_.delete(Jt.id),J.delete(Jt.id),d(Jt))}});else{let dt=typeof qe=="string"?qe:(Ke=qe==null?void 0:qe.text)!=null?Ke:null;if(dt!==null&&dt.trim()!=="")oe.content=dt,Ye=!0;else{let Ue=Se.getExtractedText();Ue!==null&&Ue.trim()!==""&&(oe.content=Ue,Ye=!0)}}}}}if(!It){if(!oe.rawContent){let rt=J.get(oe.id);oe.rawContent=rt!=null?rt:me(L)}if(!Ye&&!J.has(oe.id)&&(oe.content=me(L)),Se){let rt=(es=Se.close)==null?void 0:es.call(Se);rt instanceof Promise&&rt.catch(()=>{})}_.delete(oe.id),J.delete(oe.id),oe.streaming=!1,d(oe)}}else _.delete(oe.id),J.delete(oe.id),oe.streaming=!1,d(oe)}else if(We==="flow_complete"){let B=(ts=m.result)==null?void 0:ts.response;if(B!=null){let y=I(),L=J.get(y.id),oe=L!=null?L:me(B);y.rawContent=oe;let Se=me(B),Ye=_.get(y.id);if(Ye){let bt=Ys(oe);if(bt!==null)Se=bt;else{let gt=Ye.processChunk(oe);gt instanceof Promise&&gt.then(qe=>{var Ue;let dt=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(dt!==null){let xt=f;xt&&xt.id===y.id&&(xt.content=dt,xt.streaming=!1,d(xt))}});let Ne=Ye.getExtractedText();Ne!==null&&(Se=Ne)}}_.delete(y.id),J.delete(y.id);let It=Se!==y.content,rt=y.streaming!==!1;It&&(y.content=Se),y.streaming=!1,(It||rt)&&d(y)}else if(f!==null){let y=f;_.delete(y.id),J.delete(y.id),y.streaming!==!1&&(y.streaming=!1,d(y))}r({type:"status",status:"idle"})}else if(We==="agent_start")X={executionId:m.executionId,agentId:(rn=m.agentId)!=null?rn:"virtual",agentName:(Bs=m.agentName)!=null?Bs:"",status:"running",currentIteration:0,maxIterations:(Rs=m.maxIterations)!=null?Rs:1,startedAt:N(m.startedAt)};else if(We==="agent_iteration_start"){if(X&&(X.currentIteration=m.iteration),ae==="separate"&&m.iteration>1){let B=f;B&&(B.streaming=!1,d(B),$.set(m.iteration-1,B),f=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(m.contentType==="text"){let B=I();B.content+=(ns=m.delta)!=null?ns:"",B.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:X==null?void 0:X.agentName},d(B)}else if(m.contentType==="thinking"){let B=(bn=m.turnId)!=null?bn:`agent-think-${m.iteration}`,y=ie(B);y.reasoning=(on=y.reasoning)!=null?on:{id:B,status:"streaming",chunks:[]},y.reasoning.chunks.push((Fs=m.delta)!=null?Fs:""),y.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},d(y)}else if(m.contentType==="tool_input"){let B=($s=m.toolCallId)!=null?$s:x.lastId;if(B){let y=b.get(B);y!=null&&y.toolCall&&(y.toolCall.chunks=(Os=y.toolCall.chunks)!=null?Os:[],y.toolCall.chunks.push((yr=m.delta)!=null?yr:""),d(y))}}}else if(We==="agent_turn_complete"){let B=m.turnId;if(B){let y=C.get(B);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=N(m.completedAt);let L=(xn=y.reasoning.startedAt)!=null?xn:Date.now();y.reasoning.durationMs=Math.max(0,((Cn=y.reasoning.completedAt)!=null?Cn:Date.now())-L),y.streaming=!1,d(y)}}}else if(We==="agent_tool_start"){let B=(nt=m.toolCallId)!=null?nt:`agent-tool-${c()}`;K(T(m),B);let y=V(B),L=($n=y.toolCall)!=null?$n:{id:B,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};L.name=(On=m.toolName)!=null?On:L.name,L.status="running",m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=N((ss=m.startedAt)!=null?ss:m.timestamp),y.toolCall=L,y.streaming=!0,y.agentMetadata={executionId:m.executionId,iteration:m.iteration},d(y)}else if(We==="agent_tool_delta"){let B=(rs=m.toolCallId)!=null?rs:x.lastId;if(B){let y=(os=b.get(B))!=null?os:V(B);y.toolCall&&(y.toolCall.chunks=(is=y.toolCall.chunks)!=null?is:[],y.toolCall.chunks.push((Rt=m.delta)!=null?Rt:""),y.toolCall.status="running",y.streaming=!0,d(y))}}else if(We==="agent_tool_complete"){let B=(jt=m.toolCallId)!=null?jt:x.lastId;if(B){let y=(an=b.get(B))!=null?an:V(B);if(y.toolCall){y.toolCall.status="complete",m.result!==void 0&&(y.toolCall.result=m.result),typeof m.executionTime=="number"&&(y.toolCall.durationMs=m.executionTime),y.toolCall.completedAt=N((Qt=m.completedAt)!=null?Qt:m.timestamp),y.streaming=!1,d(y);let L=T(m);L&&x.byCall.delete(L)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let B=`agent-reflection-${m.executionId}-${m.iteration}`,y={id:B,role:"assistant",content:(as=m.reflection)!=null?as:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"complete",chunks:[(Sn=m.reflection)!=null?Sn:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};d(y)}else if(We==="agent_complete"){X&&(X.status=m.success?"complete":"error",X.completedAt=N(m.completedAt),X.stopReason=m.stopReason);let B=f;B&&(B.streaming=!1,d(B)),r({type:"status",status:"idle"})}else if(We==="agent_error"){let B=typeof m.error=="string"?m.error:(Ns=(Kt=m.error)==null?void 0:Kt.message)!=null?Ns:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",B):r({type:"error",error:new Error(B)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let B=(Nn=m.approvalId)!=null?Nn:`approval-${c()}`,y={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(Ds=X==null?void 0:X.agentId)!=null?Ds:"virtual",executionId:(ln=(_s=m.executionId)!=null?_s:X==null?void 0:X.executionId)!=null?ln:"",toolName:(Ge=m.toolName)!=null?Ge:"",toolType:m.toolType,description:(fn=m.description)!=null?fn:`Execute ${(Qe=m.toolName)!=null?Qe:"tool"}`,parameters:m.parameters}};d(y)}else if(We==="step_await"&&m.awaitReason==="approval_required"){let B=(ls=m.approvalId)!=null?ls:`approval-${c()}`,y={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(ds=X==null?void 0:X.agentId)!=null?ds:"virtual",executionId:(Lt=(br=m.executionId)!=null?br:X==null?void 0:X.executionId)!=null?Lt:"",toolName:(xr=m.toolName)!=null?xr:"",toolType:m.toolType,description:(cs=m.description)!=null?cs:`Execute ${(Ft=m.toolName)!=null?Ft:"tool"}`,parameters:m.parameters}};d(y)}else if(We==="agent_approval_complete"){let B=m.approvalId;if(B){let L={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:(us=m.decision)!=null?us:"approved",agentId:(ps=X==null?void 0:X.agentId)!=null?ps:"virtual",executionId:(ms=(gs=m.executionId)!=null?gs:X==null?void 0:X.executionId)!=null?ms:"",toolName:(fs=m.toolName)!=null?fs:"",description:(hs=m.description)!=null?hs:"",resolvedAt:Date.now()}};d(L)}}else We==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}}};function Fi(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${t}_${n}`}function Dn(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${t}_${n}`}function Ln(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${t}_${n}`}var Zs="[Image]";function $i(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Oi(t){return typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.text).join("")}function Ni(t){return typeof t=="string"?!1:t.some(n=>n.type==="image")}function Di(t){return typeof t=="string"?[]:t.filter(n=>n.type==="image")}function er(t){return{type:"text",text:t}}function _i(t,n){return{type:"image",image:t,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function ji(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;n({type:"image",image:o,mimeType:t.type,alt:t.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(t)})}function qi(t,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(t.type)?t.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 Ui=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],$a=["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"],wn=[...Ui,...$a];function Oa(t){return Ui.includes(t)||t.startsWith("image/")}function tr(t){return Oa(t.type)}async function zi(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;tr(t)?n({type:"image",image:o,mimeType:t.type,alt:t.name}):n({type:"file",data:o,mimeType:t.type,filename:t.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(t)})}function Ji(t,n=wn,r=10*1024*1024){return n.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${n.join(", ")}`}}function Na(t){let n=t.split(".");return n.length>1?n.pop().toLowerCase():""}function Ki(t,n){let r=Na(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"}[t]||r||"FILE"}var _n=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,e,o,s,i,a,u;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:(e=n.message.agentMetadata.agentName)!=null?e:"",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"),(u=(a=this.callbacks).onError)==null||u.call(a,n.error))};var e;this.messages=[...(e=n.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Mn(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 e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(n=this.callbacks).onError)==null||r.call(n,e instanceof Error?e:new Error(String(e))),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 Mn(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:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:u,streaming:c=!1}=n,d={id:i!=null?i:r==="user"?Dn():r==="assistant"?Ln():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(d),d}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 e of n){let{role:o,content:s,llmContent:i,contentParts:a,id:u,createdAt:c,sequence:v,streaming:d=!1}=e,h={id:u!=null?u:o==="user"?Dn():o==="assistant"?Ln():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:d,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(h)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var c,v,d,f,h;let e=n.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(c=this.abortController)==null||c.abort();let o=Dn(),s=Ln(),i={id:o,role:"user",content:e||Zs,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(C){let b=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!b){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,b||(C instanceof Error?(d=(v=this.callbacks).onError)==null||d.call(v,C):(h=(f=this.callbacks).onError)==null||h.call(f,new Error(String(C))))}}async continueConversation(){var o,s,i,a,u;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=Ln();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let e=[...this.messages];try{await this.client.dispatch({messages:e,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(c){let v={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(v),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,c):(u=(a=this.callbacks).onError)==null||u.call(a,new Error(String(c)))}}async connectStream(n,r){var o,s,i;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=!1;for(let a of this.messages)a.streaming&&(a.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(a){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(i=(s=this.callbacks).onError)==null||i.call(s,a instanceof Error?a:new Error(String(a)))}}async resolveApproval(n,r){var u,c,v;let e=`approval-${n.id}`,o={...n,status:r,resolvedAt:Date.now()},s={id:e,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let i=this.config.approval,a=i&&typeof i=="object"?i.onDecision:void 0;try{let d;if(a?d=await a({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},r):d=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},r),d){let f=null;if(d instanceof Response){if(!d.ok){let h=await d.json().catch(()=>null);throw new Error((u=h==null?void 0:h.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):r==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(v=(c=this.callbacks).onError)==null||v.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var 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(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(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),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,e)=>{var u,c;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(u=r.sequence)!=null?u:0,a=(c=e.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(e.id)})}};var p=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Da=La(require("lucide"),1),re=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Da[o];return s?_a(s,n,r,e):(console.warn(`Lucide icon "${t}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${t}":`,o),null}};function _a(t,n,r,e){if(!t||!Array.isArray(t))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(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,v])=>{c!=="stroke"&&u.setAttribute(c,String(v))}),o.appendChild(u)}}}),o}var nr={allowedTypes:wn,maxFileSize:10*1024*1024,maxFiles:4};function ja(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function qa(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-json":"file"}var In=class t{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:nr.allowedTypes,maxFileSize:(e=n.maxFileSize)!=null?e:nr.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:nr.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:nr.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var r,e,o,s,i,a,u;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=Ji(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let d=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,d);continue}try{let d=await zi(c),f=tr(c)?URL.createObjectURL(c):null,h={id:ja(),file:c,previewUrl:f,contentPart:d};this.attachments.push(h),this.renderPreview(h)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(a=this.config).onAttachmentsChange)==null||u.call(a,this.getAttachments())}}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(u=>u.id===n);if(r===-1)return;let e=this.attachments[r];e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.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=tr(n.file),e=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",n.id),e.style.width="48px",e.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",e.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=qa(n.file.type),u=re(a,20,"var(--cw-muted, #6b7280)",1.5);u&&i.appendChild(u);let c=p("span");c.textContent=Ki(n.file.type,n.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--cw-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),e.appendChild(i)}let o=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=re("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new t({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 Tr=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ua=t=>{var s,i,a;let n=(s=t==null?void 0:t.colorScheme)!=null?s:"light",r=(i=t==null?void 0:t.theme)!=null?i:{},e=(a=t==null?void 0:t.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||Tr()==="dark"?e:r},Yi=t=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Tr())});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)"),e=()=>t(Tr());r.addEventListener?(r.addEventListener("change",e),n.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),n.push(()=>r.removeListener(e)))}return()=>{n.forEach(r=>r())}},sr=(t,n)=>{let r=Ua(n);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);t.style.setProperty(`--cw-${s}`,String(o))})};var Vi=require("idiomorph"),Xi=(t,n,r={})=>{let{preserveTypingAnimation:e=!0}=r;Vi.Idiomorph.morph(t,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&e&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Vt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Es=(t,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(!k){let An="max-height: -moz-available !important; max-height: stretch !important;",En=l?"":"padding-top: 1.25em !important;";Oe.style.cssText+=An+En}};pn(),sr(t,e);let ut=[];N&&ut.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),ae==null||ae.destroy(),ae=null,$==null||$.destroy(),$=null,J=null});let Xt=null,Gn=()=>{Xt&&(Xt(),Xt=null),e.colorScheme==="auto"&&(Xt=Yi(()=>{sr(t,e)}))};Gn(),ut.push(()=>{Xt&&(Xt(),Xt=null)});let gn=sa(Ot),Gt=null,O,mn=!1,tn=!0,yn=0,Qn=0,nn=null,sn=!1,Bn=0,Rn=!1,Ws=125,Ps=2e3,Hs=5,Zn=50,Fn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},es=(Ne=(gt=e.voiceRecognition)==null?void 0:gt.autoResume)!=null?Ne:!1,ts=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},rn=()=>{d(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Bs=()=>{var A,S;if(((A=e.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=qr(a.voiceState),g=!!l.active,w=Number((S=l.timestamp)!=null?S:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-w<hl&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,Sn("restore"))},1e3)},Rs=()=>O?ca(O.getMessages()).filter(l=>!l.__skipPersist):[];function ns(l){if(!(i!=null&&i.save))return;let w={messages:l?ca(l):O?Rs():[],metadata:a};try{let A=i.save(w);A instanceof Promise&&A.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let bn=(l=!1)=>{if(!tn)return;let g=Date.now();sn&&g<Bn&&!l||(sn&&g>=Bn&&(sn=!1),!(!l&&!mn)&&(g-Qn<Ws||(Qn=g,nn&&cancelAnimationFrame(nn),nn=requestAnimationFrame(()=>{sn||!tn||(Rn=!0,Fe.scrollTop=Fe.scrollHeight,yn=Fe.scrollTop,requestAnimationFrame(()=>{Rn=!1}),nn=null)}))))},on=null,Fs=()=>Oe.querySelector("#persona-scroll-container")||Fe,$s=(l,g=500)=>{let w=l.scrollTop,A=l.clientHeight,S=l.scrollHeight,H=S-w;if(w+A>=S-2||Math.abs(H)<5)return;on!==null&&(cancelAnimationFrame(on),on=null);let le=performance.now(),ue=pe=>1-Math.pow(1-pe,3),be=pe=>{let Ae=l.scrollHeight;Ae!==S&&(S=Ae,H=S-w);let ne=pe-le,k=Math.min(ne/g,1),ge=ue(k),we=w+H*ge;l.scrollTop=we,k<1?on=requestAnimationFrame(be):(l.scrollTop=l.scrollHeight,on=null)};on=requestAnimationFrame(be)},Os=l=>{let g=new Map;l.forEach(w=>{let A=Fn.get(w.id);g.set(w.id,{streaming:w.streaming,role:w.role}),!A&&w.role==="assistant"&&s.emit("assistant:message",w),w.role==="assistant"&&(A!=null&&A.streaming)&&w.streaming===!1&&s.emit("assistant:complete",w),w.variant==="approval"&&w.approval&&(A?w.approval.status!=="pending"&&s.emit("approval:resolved",{approval:w.approval,decision:w.approval.status}):s.emit("approval:requested",{approval:w.approval,message:w}))}),Fn.clear(),g.forEach((w,A)=>{Fn.set(A,w)})},xn=(l,g,w)=>{var be,pe,Ae,ne;let A=document.createElement("div"),H=(()=>{var ge;let k=o.find(we=>we.renderLoadingIndicator);if(k!=null&&k.renderLoadingIndicator)return k.renderLoadingIndicator;if((ge=e.loadingIndicator)!=null&&ge.render)return e.loadingIndicator.render})();g.forEach(k=>{var mt,Wt;let ge=null,we=o.find(Z=>!!(k.variant==="reasoning"&&Z.renderReasoning||k.variant==="tool"&&Z.renderToolCall||k.variant==="approval"&&Z.renderApproval||!k.variant&&Z.renderMessage)),Ve=(mt=e.layout)==null?void 0:mt.messages;if(we)if(k.variant==="reasoning"&&k.reasoning&&we.renderReasoning){if(!q)return;ge=we.renderReasoning({message:k,defaultRenderer:()=>Hr(k),config:e})}else if(k.variant==="tool"&&k.toolCall&&we.renderToolCall){if(!V)return;ge=we.renderToolCall({message:k,defaultRenderer:()=>Br(k,e),config:e})}else if(k.variant==="approval"&&k.approval&&we.renderApproval){if(e.approval===!1)return;ge=we.renderApproval({message:k,defaultRenderer:()=>Rr(k,e),config:e})}else we.renderMessage&&(ge=we.renderMessage({message:k,defaultRenderer:()=>{let Z=Un(k,w,Ve,e.messageActions,ht,{loadingIndicatorRenderer:H,widgetConfig:e});return k.role!=="user"&&$r(Z,k,e,O),Z},config:e}));if(!ge&&k.role==="assistant"&&!k.variant&&e.enableComponentStreaming!==!1&&dr(k)){let _e=cr(k);if(_e){let Zt=lr(_e,{config:e,message:k,transform:w});if(Zt){let Yt=document.createElement("div");if(Yt.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(" "),Yt.id=`bubble-${k.id}`,Yt.setAttribute("data-message-id",k.id),k.content&&k.content.trim()){let hn=document.createElement("div");hn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",hn.innerHTML=w({text:k.content,message:k,streaming:!!k.streaming,raw:k.rawContent}),Yt.appendChild(hn)}Yt.appendChild(Zt),ge=Yt}}}if(!ge)if(k.variant==="reasoning"&&k.reasoning){if(!q)return;ge=Hr(k)}else if(k.variant==="tool"&&k.toolCall){if(!V)return;ge=Br(k,e)}else if(k.variant==="approval"&&k.approval){if(e.approval===!1)return;ge=Rr(k,e)}else{let Z=(Wt=e.layout)==null?void 0:Wt.messages;Z!=null&&Z.renderUserMessage&&k.role==="user"?ge=Z.renderUserMessage({message:k,config:e,streaming:!!k.streaming}):Z!=null&&Z.renderAssistantMessage&&k.role==="assistant"?ge=Z.renderAssistantMessage({message:k,config:e,streaming:!!k.streaming}):ge=Un(k,w,Z,e.messageActions,ht,{loadingIndicatorRenderer:H,widgetConfig:e}),k.role!=="user"&&ge&&$r(ge,k,e,O)}let Pe=document.createElement("div");Pe.className="tvw-flex",Pe.id=`wrapper-${k.id}`,Pe.setAttribute("data-wrapper-id",k.id),k.role==="user"&&Pe.classList.add("tvw-justify-end"),Pe.appendChild(ge),A.appendChild(Pe)});let he=g.some(k=>k.role==="assistant"&&k.streaming),le=g[g.length-1],ue=(le==null?void 0:le.role)==="assistant"&&!le.streaming&&le.variant!=="approval";if(mn&&g.some(k=>k.role==="user")&&!he&&!ue){let k={config:e,streaming:!0,location:"standalone",defaultRenderer:Wn},ge=o.find(Ve=>Ve.renderLoadingIndicator),we=null;if(ge!=null&&ge.renderLoadingIndicator&&(we=ge.renderLoadingIndicator(k)),we===null&&((be=e.loadingIndicator)!=null&&be.render)&&(we=e.loadingIndicator.render(k)),we===null&&(we=Wn()),we){let Ve=document.createElement("div"),Pe=((pe=e.loadingIndicator)==null?void 0:pe.showBubble)!==!1;Ve.className=Pe?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(we);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Ve),A.appendChild(mt)}}if(!mn&&g.length>0){let k=g[g.length-1],ge={config:e,lastMessage:k,messageCount:g.length},we=o.find(Pe=>Pe.renderIdleIndicator),Ve=null;if(we!=null&&we.renderIdleIndicator&&(Ve=we.renderIdleIndicator(ge)),Ve===null&&((Ae=e.loadingIndicator)!=null&&Ae.renderIdle)&&(Ve=e.loadingIndicator.renderIdle(ge)),Ve){let Pe=document.createElement("div"),mt=((ne=e.loadingIndicator)==null?void 0:ne.showBubble)!==!1;Pe.className=mt?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(Ve);let Wt=document.createElement("div");Wt.className="tvw-flex",Wt.id="wrapper-idle-indicator",Wt.setAttribute("data-wrapper-id","idle-indicator"),Wt.appendChild(Pe),A.appendChild(Wt)}}Xi(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let k=Fs();$s(k)})})},Cn=()=>{b&&(I?(Oe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),te.classList.remove("tvw-scale-95","tvw-opacity-0"),te.classList.add("tvw-scale-100","tvw-opacity-100"),Ge?Ge.element.style.display="none":Qe&&(Qe.style.display="none")):(Oe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),te.classList.remove("tvw-scale-100","tvw-opacity-100"),te.classList.add("tvw-scale-95","tvw-opacity-0"),Ge?Ge.element.style.display="":Qe&&(Qe.style.display="")))},nt=(l,g="user")=>{if(!b||I===l)return;let w=I;I=l,Cn(),I&&(fn(),bn(!0));let A={open:I,source:g,timestamp:Date.now()};I&&!w?s.emit("widget:opened",A):!I&&w&&s.emit("widget:closed",A),s.emit("widget:state",{open:I,launcherEnabled:b,voiceActive:Ke.active,streaming:O.isStreaming()})},$n=l=>{G.disabled=l,z&&(z.disabled=l),gn.buttons.forEach(g=>{g.disabled=l})},On=()=>{Ke.active||de&&de.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>On(),200)});let ss=()=>{var S,H,he,le,ue,be,pe,Ae,ne,k,ge,we,Ve,Pe;vt.textContent=(H=(S=e.copy)==null?void 0:S.welcomeTitle)!=null?H:"Hello \u{1F44B}",zt.textContent=(le=(he=e.copy)==null?void 0:he.welcomeSubtitle)!=null?le:"Ask anything about your account or products.",de.placeholder=(be=(ue=e.copy)==null?void 0:ue.inputPlaceholder)!=null?be:"How can I help...",((Ae=(pe=e.sendButton)==null?void 0:pe.useIcon)!=null?Ae:!1)||(G.textContent=(k=(ne=e.copy)==null?void 0:ne.sendButtonLabel)!=null?k:"Send");let g=(we=(ge=e.theme)==null?void 0:ge.inputFontFamily)!=null?we:"sans-serif",w=(Pe=(Ve=e.theme)==null?void 0:Ve.inputFontWeight)!=null?Pe:"400",A=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'}};de.style.fontFamily=A(g),de.style.fontWeight=w};e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{d(g=>({...g,sessionId:l}))}}),O=new _n(e,{onMessagesChanged(l){xn(ze,l,K),O&&(l.some(S=>S.role==="user")?gn.render([],O,de,l):gn.render(e.suggestionChips,O,de,l,e.suggestionChipsConfig)),bn(!mn),Os(l);let g=[...l].reverse().find(A=>A.role==="user"),w=Ke.lastUserMessageId;g&&g.id!==w&&(Ke.lastUserMessageId=g.id,s.emit("user:message",g)),Ke.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),ns(l)},onStatusChanged(l){var A;let g=(A=e.statusIndicator)!=null?A:{},w=S=>{var H,he,le,ue;return S==="idle"?(H=g.idleText)!=null?H:Pt.idle:S==="connecting"?(he=g.connectingText)!=null?he:Pt.connecting:S==="connected"?(le=g.connectedText)!=null?le:Pt.connected:S==="error"?(ue=g.errorText)!=null?ue:Pt.error:Pt[S]};Tt.textContent=w(l)},onStreamingChanged(l){mn=l,$n(l),O&&xn(ze,O.getMessages(),K),l||bn(!0)}}),e.clientToken&&O.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),$&&O.setSSEEventCallback((l,g)=>{$==null||$.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),u&&u.then(l=>{var g;l&&(l.metadata&&(a=qr(l.metadata),C.syncFromMetadata()),(g=l.messages)!=null&&g.length&&O.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let rs=l=>{var S;l.preventDefault();let g=de.value.trim(),w=(S=U==null?void 0:U.hasAttachments())!=null?S:!1;if(!g&&!w)return;let A;w&&(A=[],A.push(...U.getContentParts()),g&&A.push(er(g))),de.value="",de.style.height="auto",O.sendMessage(g,{contentParts:A}),w&&U.clearAttachments()},os=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),G.click())},is=async l=>{var w;if(((w=e.attachments)==null?void 0:w.enabled)!==!0||!U)return;let g=vl(l.clipboardData);g.length!==0&&(l.preventDefault(),await U.handleFiles(g))},Rt=null,jt=!1,an=null,Qt=null,as=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Sn=(l="user")=>{var H,he,le,ue;if(jt||O.isStreaming())return;let g=as();if(!g)return;Rt=new g;let A=(he=((H=e.voiceRecognition)!=null?H:{}).pauseDuration)!=null?he:2e3;Rt.continuous=!0,Rt.interimResults=!0,Rt.lang="en-US";let S=de.value;Rt.onresult=be=>{let pe="",Ae="";for(let k=0;k<be.results.length;k++){let ge=be.results[k],we=ge[0].transcript;ge.isFinal?pe+=we+" ":Ae=we}let ne=S+pe+Ae;de.value=ne,an&&clearTimeout(an),(pe||Ae)&&(an=window.setTimeout(()=>{let k=de.value.trim();k&&Rt&&jt&&(Kt(),de.value="",de.style.height="auto",O.sendMessage(k,{viaVoice:!0}))},A))},Rt.onerror=be=>{be.error!=="no-speech"&&Kt()},Rt.onend=()=>{if(jt){let be=de.value.trim();be&&be!==S.trim()&&(de.value="",de.style.height="auto",O.sendMessage(be,{viaVoice:!0})),Kt()}};try{if(Rt.start(),jt=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),ts(l),rn(),z){Qt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor};let be=(le=e.voiceRecognition)!=null?le:{},pe=(ue=be.recordingBackgroundColor)!=null?ue:"#ef4444",Ae=be.recordingIconColor,ne=be.recordingBorderColor;if(z.classList.add("tvw-voice-recording"),z.style.backgroundColor=pe,Ae){z.style.color=Ae;let k=z.querySelector("svg");k&&k.setAttribute("stroke",Ae)}ne&&(z.style.borderColor=ne),z.setAttribute("aria-label","Stop voice recognition")}}catch{Kt("system")}},Kt=(l="user")=>{if(jt){if(jt=!1,an&&(clearTimeout(an),an=null),Rt){try{Rt.stop()}catch{}Rt=null}if(Ke.active=!1,ts(l),rn(),z){if(z.classList.remove("tvw-voice-recording"),Qt){z.style.backgroundColor=Qt.backgroundColor,z.style.color=Qt.color,z.style.borderColor=Qt.borderColor;let g=z.querySelector("svg");g&&g.setAttribute("stroke",Qt.color||"currentColor"),Qt=null}z.setAttribute("aria-label","Start voice recognition")}}},Ns=(l,g)=>{var we,Ve,Pe,mt,Wt,Z,_e;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let A=p("div","tvw-send-button-wrapper"),S=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");S.type="button",S.setAttribute("aria-label","Start voice recognition");let H=(we=l==null?void 0:l.iconName)!=null?we:"mic",he=(Ve=g==null?void 0:g.size)!=null?Ve:"40px",le=(Pe=l==null?void 0:l.iconSize)!=null?Pe:he,ue=parseFloat(le)||24,be=(mt=l==null?void 0:l.backgroundColor)!=null?mt:g==null?void 0:g.backgroundColor,pe=(Wt=l==null?void 0:l.iconColor)!=null?Wt:g==null?void 0:g.textColor;S.style.width=le,S.style.height=le,S.style.minWidth=le,S.style.minHeight=le,S.style.fontSize="18px",S.style.lineHeight="1";let Ae=pe||"currentColor",ne=re(H,ue,Ae,1.5);ne?(S.appendChild(ne),S.style.color=Ae):(S.textContent="\u{1F3A4}",S.style.color=Ae),be?S.style.backgroundColor=be:S.classList.add("tvw-bg-cw-primary"),pe?S.style.color=pe:!pe&&!(g!=null&&g.textColor)&&S.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(S.style.borderWidth=l.borderWidth,S.style.borderStyle="solid"),l!=null&&l.borderColor&&(S.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(S.style.paddingLeft=l.paddingX,S.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(S.style.paddingTop=l.paddingY,S.style.paddingBottom=l.paddingY),A.appendChild(S);let k=(Z=l==null?void 0:l.tooltipText)!=null?Z:"Start voice recognition";if(((_e=l==null?void 0:l.showTooltip)!=null?_e:!1)&&k){let Zt=p("div","tvw-send-button-tooltip");Zt.textContent=k,A.appendChild(Zt)}return{micButton:S,micButtonWrapper:A}},Nn=()=>{if(jt){let l=de.value.trim();Ke.manuallyDeactivated=!0,rn(),Kt("user"),l&&(de.value="",de.style.height="auto",O.sendMessage(l))}else Ke.manuallyDeactivated=!1,rn(),Sn("user")};z&&(z.addEventListener("click",Nn),ut.push(()=>{Kt("system"),z&&z.removeEventListener("click",Nn)}));let Ds=s.on("assistant:complete",()=>{es&&(Ke.active||Ke.manuallyDeactivated||es==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&Sn("auto")},600))});ut.push(Ds);let _s=s.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});ut.push(_s);let ln=()=>{nt(!I,"user")},Ge=null,Qe=null;if(b){let l=o.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:e,defaultRenderer:()=>Es(e,ln).element,onToggle:ln});g&&(Qe=g)}Qe||(Ge=Es(e,ln))}Ge?t.appendChild(Ge.element):Qe&&t.appendChild(Qe),Cn(),gn.render(e.suggestionChips,O,de,void 0,e.suggestionChipsConfig),ss(),$n(O.isStreaming()),bn(!0),Bs(),x&&(b?I&&setTimeout(()=>On(),200):setTimeout(()=>On(),0));let fn=()=>{var w,A,S,H,he,le,ue,be;let l=(A=(w=e.launcher)==null?void 0:w.sidebarMode)!=null?A:!1,g=l||((H=(S=e.launcher)==null?void 0:S.fullHeight)!=null?H:!1);if(!b){te.style.height="",te.style.width="";return}if(!l){let pe=(le=(he=e==null?void 0:e.launcher)==null?void 0:he.width)!=null?le:e==null?void 0:e.launcherWidth,Ae=pe!=null?pe:"min(400px, calc(100vw - 24px))";te.style.width=Ae,te.style.maxWidth=Ae}if(!g){let pe=window.innerHeight,Ae=64,ne=(be=(ue=e.launcher)==null?void 0:ue.heightOffset)!=null?be:0,k=Math.max(200,pe-Ae),ge=Math.min(640,k),we=Math.max(200,ge-ne);te.style.height=`${we}px`}};fn(),window.addEventListener("resize",fn),ut.push(()=>window.removeEventListener("resize",fn)),yn=Fe.scrollTop;let ls=()=>{let l=Fe.scrollTop,g=Fe.scrollHeight,w=Fe.clientHeight,A=g-l-w,S=Math.abs(l-yn);if(yn=l,!Rn&&!(S<=Hs)){if(!tn&&A<Zn){sn=!1,tn=!0;return}tn&&A>Zn&&(sn=!0,Bn=Date.now()+Ps,tn=!1)}};Fe.addEventListener("scroll",ls,{passive:!0}),ut.push(()=>Fe.removeEventListener("scroll",ls)),ut.push(()=>{nn&&cancelAnimationFrame(nn)});let ds=()=>{ee&&(Gt&&(ee.removeEventListener("click",Gt),Gt=null),b?(ee.style.display="",Gt=()=>{I=!1,Cn()},ee.addEventListener("click",Gt)):ee.style.display="none")};ds(),(()=>{let{clearChatButton:l}=ye;l&&l.addEventListener("click",()=>{O.clearMessages();try{localStorage.removeItem(Xn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xn}`)}catch(w){console.error("[AgentWidget] Failed to clear default localStorage:",w)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Xn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(w){console.error("[AgentWidget] Failed to clear custom localStorage:",w)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let w=i.clear();w instanceof Promise&&w.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)}a={},C.syncFromMetadata(),$==null||$.clear(),ae==null||ae.update()})})(),wt.addEventListener("submit",rs),de.addEventListener("keydown",os),de.addEventListener("paste",is),ut.push(()=>{wt.removeEventListener("submit",rs),de.removeEventListener("keydown",os),de.removeEventListener("paste",is)}),ut.push(()=>{O.cancel()}),Ge?ut.push(()=>{Ge==null||Ge.destroy()}):Qe&&ut.push(()=>{Qe==null||Qe.remove()});let Lt={update(l){var Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,fo,ho,wo,vo,yo,bo,xo,Co,So,Ao,Eo,To,Mo,Lo,Io,ko,Wo,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,_o,jo,qo,Uo,zo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,fi,hi,wi,vi,yi,bi,xi,Ci,Si,Ai,Ei;let g=e.toolCall,w=e.colorScheme;e={...e,...l},pn(),sr(t,e),e.colorScheme!==w&&Gn();let A=Ls.getForInstance(e.plugins);o.length=0,o.push(...A),b=(Yr=(Kr=e.launcher)==null?void 0:Kr.enabled)!=null?Yr:!0,E=(Xr=(Vr=e.launcher)==null?void 0:Vr.autoExpand)!=null?Xr:!1,q=(Qr=(Gr=e.features)==null?void 0:Gr.showReasoning)!=null?Qr:!0,V=(eo=(Zr=e.features)==null?void 0:Zr.showToolCalls)!=null?eo:!0;let S=N;if(N=(no=(to=e.features)==null?void 0:to.showEventStreamToggle)!=null?no:!1,N&&!S){if($||(J=new Ms(_),$=new Ts(X,J),J.open().then(()=>$==null?void 0:$.restore()).catch(()=>{}),O.setSSEEventCallback((W,Me)=>{$.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:W,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!D&&xe){let W=(ro=(so=e.features)==null?void 0:so.eventStream)==null?void 0:ro.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"+(W!=null&&W.toggleButton?" "+W.toggleButton:"");D=p("button",Me),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let Ze=re("activity","18px","currentColor",1.5);Ze&&D.appendChild(Ze);let ve=ye.clearChatButtonWrapper,Re=ye.closeButtonWrapper,ft=ve||Re;ft&&ft.parentNode===xe?xe.insertBefore(D,ft):xe.appendChild(D),D.addEventListener("click",()=>{fe?Ce():je()})}}else!N&&S&&(Ce(),D&&(D.remove(),D=null),$==null||$.clear(),J==null||J.destroy(),$=null,J=null);if(((oo=e.launcher)==null?void 0:oo.enabled)===!1&&Ge&&(Ge.destroy(),Ge=null),((io=e.launcher)==null?void 0:io.enabled)===!1&&Qe&&(Qe.remove(),Qe=null),((ao=e.launcher)==null?void 0:ao.enabled)!==!1&&!Ge&&!Qe){let W=o.find(Me=>Me.renderLauncher);if(W!=null&&W.renderLauncher){let Me=W.renderLauncher({config:e,defaultRenderer:()=>Es(e,ln).element,onToggle:ln});Me&&(Qe=Me,t.appendChild(Qe))}Qe||(Ge=Es(e,ln),t.appendChild(Ge.element))}Ge&&Ge.update(e),yt&&((lo=e.launcher)==null?void 0:lo.title)!==void 0&&(yt.textContent=e.launcher.title),ce&&((co=e.launcher)==null?void 0:co.subtitle)!==void 0&&(ce.textContent=e.launcher.subtitle);let H=(uo=e.layout)==null?void 0:uo.header;if((H==null?void 0:H.layout)!==T&&xe){let W=H?jn(e,H,{showClose:b,onClose:()=>nt(!1,"user")}):cn({config:e,showClose:b,onClose:()=>nt(!1,"user")});xe.replaceWith(W.header),xe=W.header,ke=W.iconHolder,yt=W.headerTitle,ce=W.headerSubtitle,ee=W.closeButton,T=H==null?void 0:H.layout}else if(H&&(ke&&(ke.style.display=H.showIcon===!1?"none":""),yt&&(yt.style.display=H.showTitle===!1?"none":""),ce&&(ce.style.display=H.showSubtitle===!1?"none":""),ee&&(ee.style.display=H.showCloseButton===!1?"none":""),ye.clearChatButtonWrapper)){let W=H.showClearChat;if(W!==void 0){ye.clearChatButtonWrapper.style.display=W?"":"none";let{closeButtonWrapper:Me}=ye;Me&&!Me.classList.contains("tvw-absolute")&&(W?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let le=((po=e.layout)==null?void 0:po.showHeader)!==!1;xe&&(xe.style.display=le?"":"none");let ue=((go=e.layout)==null?void 0:go.showFooter)!==!1;Je&&(Je.style.display=ue?"":"none"),b!==Y?b?nt(E,"auto"):(I=!0,Cn()):E!==P&&nt(E,"auto"),P=E,Y=b,fn(),ds(),JSON.stringify(l.toolCall)!==JSON.stringify(g)&&O&&xn(ze,O.getMessages(),K);let ne=(mo=e.launcher)!=null?mo:{},k=(fo=ne.headerIconHidden)!=null?fo:!1,ge=(wo=(ho=e.layout)==null?void 0:ho.header)==null?void 0:wo.showIcon,we=k||ge===!1,Ve=ne.headerIconName,Pe=(vo=ne.headerIconSize)!=null?vo:"48px";if(ke){let W=Be.querySelector(".tvw-border-b-cw-divider"),Me=W==null?void 0:W.querySelector(".tvw-flex-col");if(we)ke.style.display="none",W&&Me&&!W.contains(Me)&&W.insertBefore(Me,W.firstChild);else{if(ke.style.display="",ke.style.height=Pe,ke.style.width=Pe,W&&Me&&(W.contains(ke)?ke.nextSibling!==Me&&(ke.remove(),W.insertBefore(ke,Me)):W.insertBefore(ke,Me)),Ve){let ve=parseFloat(Pe)||24,Re=re(Ve,ve*.6,"#ffffff",2);Re?ke.replaceChildren(Re):ke.textContent=(yo=ne.agentIconText)!=null?yo:"\u{1F4AC}"}else if(ne.iconUrl){let ve=ke.querySelector("img");if(ve)ve.src=ne.iconUrl,ve.style.height=Pe,ve.style.width=Pe;else{let Re=document.createElement("img");Re.src=ne.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=Pe,Re.style.width=Pe,ke.replaceChildren(Re)}}else{let ve=ke.querySelector("svg"),Re=ke.querySelector("img");(ve||Re)&&ke.replaceChildren(),ke.textContent=(bo=ne.agentIconText)!=null?bo:"\u{1F4AC}"}let Ze=ke.querySelector("img");Ze&&(Ze.style.height=Pe,Ze.style.width=Pe)}}let mt=(Co=(xo=e.layout)==null?void 0:xo.header)==null?void 0:Co.showTitle,Wt=(Ao=(So=e.layout)==null?void 0:So.header)==null?void 0:Ao.showSubtitle;if(yt&&(yt.style.display=mt===!1?"none":""),ce&&(ce.style.display=Wt===!1?"none":""),ee){((To=(Eo=e.layout)==null?void 0:Eo.header)==null?void 0:To.showCloseButton)===!1?ee.style.display="none":ee.style.display="";let Me=(Mo=ne.closeButtonSize)!=null?Mo:"32px",Ze=(Lo=ne.closeButtonPlacement)!=null?Lo:"inline";ee.style.height=Me,ee.style.width=Me;let{closeButtonWrapper:ve}=ye,Re=Ze==="top-right",ft=ve==null?void 0:ve.classList.contains("tvw-absolute");if(ve&&Re!==ft)if(ve.remove(),Re)ve.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Be.style.position="relative",Be.appendChild(ve);else{let Le=(ko=(Io=ne.clearChat)==null?void 0:Io.placement)!=null?ko:"inline",Ct=(Po=(Wo=ne.clearChat)==null?void 0:Wo.enabled)!=null?Po:!0;ve.className=Ct&&Le==="inline"?"":"tvw-ml-auto";let Dt=Be.querySelector(".tvw-border-b-cw-divider");Dt&&Dt.appendChild(ve)}if(ne.closeButtonColor?(ee.style.color=ne.closeButtonColor,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),ne.closeButtonBackgroundColor?(ee.style.backgroundColor=ne.closeButtonBackgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),ne.closeButtonBorderWidth||ne.closeButtonBorderColor){let Le=ne.closeButtonBorderWidth||"0px",Ct=ne.closeButtonBorderColor||"transparent";ee.style.border=`${Le} solid ${Ct}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");ne.closeButtonBorderRadius?(ee.style.borderRadius=ne.closeButtonBorderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),ne.closeButtonPaddingX?(ee.style.paddingLeft=ne.closeButtonPaddingX,ee.style.paddingRight=ne.closeButtonPaddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),ne.closeButtonPaddingY?(ee.style.paddingTop=ne.closeButtonPaddingY,ee.style.paddingBottom=ne.closeButtonPaddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let kt=(Ho=ne.closeButtonIconName)!=null?Ho:"x",qt=(Bo=ne.closeButtonIconText)!=null?Bo:"\xD7";ee.innerHTML="";let $t=re(kt,"20px",ne.closeButtonColor||"",2);$t?ee.appendChild($t):ee.textContent=qt;let at=(Ro=ne.closeButtonTooltipText)!=null?Ro:"Close chat",Ut=(Fo=ne.closeButtonShowTooltip)!=null?Fo:!0;if(ee.setAttribute("aria-label",at),ve&&(ve._cleanupTooltip&&(ve._cleanupTooltip(),delete ve._cleanupTooltip),Ut&&at)){let Le=null,Ct=()=>{if(Le||!ee)return;Le=p("div","tvw-clear-chat-tooltip"),Le.textContent=at;let xs=p("div");xs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(xs);let Tn=ee.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Tn.left+Tn.width/2}px`,Le.style.top=`${Tn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Dt=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};ve.addEventListener("mouseenter",Ct),ve.addEventListener("mouseleave",Dt),ee.addEventListener("focus",Ct),ee.addEventListener("blur",Dt),ve._cleanupTooltip=()=>{Dt(),ve&&(ve.removeEventListener("mouseenter",Ct),ve.removeEventListener("mouseleave",Dt)),ee&&(ee.removeEventListener("focus",Ct),ee.removeEventListener("blur",Dt))}}}let{clearChatButton:Z,clearChatButtonWrapper:_e}=ye;if(Z){let W=($o=ne.clearChat)!=null?$o:{},Me=(Oo=W.enabled)!=null?Oo:!0,Ze=(Do=(No=e.layout)==null?void 0:No.header)==null?void 0:Do.showClearChat,ve=Ze!==void 0?Ze:Me,Re=(_o=W.placement)!=null?_o:"inline";if(_e){_e.style.display=ve?"":"none";let{closeButtonWrapper:ft}=ye;ft&&!ft.classList.contains("tvw-absolute")&&(ve?ft.classList.remove("tvw-ml-auto"):ft.classList.add("tvw-ml-auto"));let kt=Re==="top-right",qt=_e.classList.contains("tvw-absolute");if(kt!==qt&&ve){if(_e.remove(),kt)_e.className="tvw-absolute tvw-top-4 tvw-z-50",_e.style.right="48px",Be.style.position="relative",Be.appendChild(_e);else{_e.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",_e.style.right="";let at=Be.querySelector(".tvw-border-b-cw-divider"),Ut=ye.closeButtonWrapper;at&&Ut&&Ut.parentElement===at?at.insertBefore(_e,Ut):at&&at.appendChild(_e)}let $t=ye.closeButtonWrapper;$t&&!$t.classList.contains("tvw-absolute")&&(kt?$t.classList.add("tvw-ml-auto"):$t.classList.remove("tvw-ml-auto"))}}if(ve){let ft=(jo=W.size)!=null?jo:"32px";Z.style.height=ft,Z.style.width=ft;let kt=(qo=W.iconName)!=null?qo:"refresh-cw",qt=(Uo=W.iconColor)!=null?Uo:"";Z.innerHTML="";let $t=re(kt,"20px",qt||"",2);if($t&&Z.appendChild($t),qt?(Z.style.color=qt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),W.backgroundColor?(Z.style.backgroundColor=W.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let Le=W.borderWidth||"0px",Ct=W.borderColor||"transparent";Z.style.border=`${Le} solid ${Ct}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");W.borderRadius?(Z.style.borderRadius=W.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),W.paddingX?(Z.style.paddingLeft=W.paddingX,Z.style.paddingRight=W.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),W.paddingY?(Z.style.paddingTop=W.paddingY,Z.style.paddingBottom=W.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let at=(zo=W.tooltipText)!=null?zo:"Clear chat",Ut=(Jo=W.showTooltip)!=null?Jo:!0;if(Z.setAttribute("aria-label",at),_e&&(_e._cleanupTooltip&&(_e._cleanupTooltip(),delete _e._cleanupTooltip),Ut&&at)){let Le=null,Ct=()=>{if(Le||!Z)return;Le=p("div","tvw-clear-chat-tooltip"),Le.textContent=at;let xs=p("div");xs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(xs);let Tn=Z.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Tn.left+Tn.width/2}px`,Le.style.top=`${Tn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Dt=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};_e.addEventListener("mouseenter",Ct),_e.addEventListener("mouseleave",Dt),Z.addEventListener("focus",Ct),Z.addEventListener("blur",Dt),_e._cleanupTooltip=()=>{Dt(),_e&&(_e.removeEventListener("mouseenter",Ct),_e.removeEventListener("mouseleave",Dt)),Z&&(Z.removeEventListener("focus",Ct),Z.removeEventListener("blur",Dt))}}}}let Zt=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Is],Yt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Pn.message,Pn.messageAndClick];C=ks({parsers:Zt,handlers:Yt,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),K=ua(e,C,ie),O.updateConfig(e),xn(ze,O.getMessages(),K),gn.render(e.suggestionChips,O,de,void 0,e.suggestionChipsConfig),ss(),$n(O.isStreaming());let hn=((Ko=e.voiceRecognition)==null?void 0:Ko.enabled)===!0,js=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(hn&&js)if(!z||!et){let W=Ns(e.voiceRecognition,e.sendButton);W&&(z=W.micButton,et=W.micButtonWrapper,_t.insertBefore(et,ot),z.addEventListener("click",Nn),z.disabled=O.isStreaming())}else{let W=(Yo=e.voiceRecognition)!=null?Yo:{},Me=(Vo=e.sendButton)!=null?Vo:{},Ze=(Xo=W.iconName)!=null?Xo:"mic",ve=(Go=Me.size)!=null?Go:"40px",Re=(Qo=W.iconSize)!=null?Qo:ve,ft=parseFloat(Re)||24;z.style.width=Re,z.style.height=Re,z.style.minWidth=Re,z.style.minHeight=Re;let kt=(ei=(Zo=W.iconColor)!=null?Zo:Me.textColor)!=null?ei:"currentColor";z.innerHTML="";let qt=re(Ze,ft,kt,2);qt?z.appendChild(qt):z.textContent="\u{1F3A4}";let $t=(ti=W.backgroundColor)!=null?ti:Me.backgroundColor;$t?(z.style.backgroundColor=$t,z.classList.remove("tvw-bg-cw-primary")):(z.style.backgroundColor="",z.classList.add("tvw-bg-cw-primary")),kt?(z.style.color=kt,z.classList.remove("tvw-text-white")):!kt&&!Me.textColor&&(z.style.color="",z.classList.add("tvw-text-white")),W.borderWidth?(z.style.borderWidth=W.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),W.borderColor?z.style.borderColor=W.borderColor:z.style.borderColor="",W.paddingX?(z.style.paddingLeft=W.paddingX,z.style.paddingRight=W.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),W.paddingY?(z.style.paddingTop=W.paddingY,z.style.paddingBottom=W.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let at=et==null?void 0:et.querySelector(".tvw-send-button-tooltip"),Ut=(ni=W.tooltipText)!=null?ni:"Start voice recognition";if(((si=W.showTooltip)!=null?si:!1)&&Ut)if(at)at.textContent=Ut,at.style.display="";else{let Ct=document.createElement("div");Ct.className="tvw-send-button-tooltip",Ct.textContent=Ut,et==null||et.insertBefore(Ct,z)}else at&&(at.style.display="none");et.style.display="",z.disabled=O.isStreaming()}else z&&et&&(et.style.display="none",jt&&Kt());if(((ri=e.attachments)==null?void 0:ri.enabled)===!0)if(!Q||!F){let W=(oi=e.attachments)!=null?oi:{},Ze=(ai=((ii=e.sendButton)!=null?ii:{}).size)!=null?ai:"40px";$e||($e=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),$e.style.display="none",wt.insertBefore($e,de)),se||(se=document.createElement("input"),se.type="file",se.accept=((li=W.allowedTypes)!=null?li:wn).join(","),se.multiple=((di=W.maxFiles)!=null?di:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),wt.insertBefore(se,de)),Q=p("div","tvw-send-button-wrapper"),F=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),F.type="button",F.setAttribute("aria-label",(ci=W.buttonTooltipText)!=null?ci:"Attach file");let ve=(ui=W.buttonIconName)!=null?ui:"paperclip",Re=Ze,ft=parseFloat(Re)||40,kt=Math.round(ft*.6);F.style.width=Re,F.style.height=Re,F.style.minWidth=Re,F.style.minHeight=Re,F.style.fontSize="18px",F.style.lineHeight="1",F.style.backgroundColor="transparent",F.style.color="var(--cw-primary, #111827)",F.style.border="none",F.style.borderRadius="6px",F.style.transition="background-color 0.15s ease",F.addEventListener("mouseenter",()=>{F.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),F.addEventListener("mouseleave",()=>{F.style.backgroundColor="transparent"});let qt=re(ve,kt,"currentColor",1.5);qt?F.appendChild(qt):F.textContent="\u{1F4CE}",F.addEventListener("click",Ut=>{Ut.preventDefault(),se==null||se.click()}),Q.appendChild(F);let $t=(pi=W.buttonTooltipText)!=null?pi:"Attach file",at=p("div","tvw-send-button-tooltip");at.textContent=$t,Q.appendChild(at),Mt.append(Q),!U&&se&&$e&&(U=In.fromConfig(W),U.setPreviewsContainer($e),se.addEventListener("change",async()=>{U&&(se!=null&&se.files)&&(await U.handleFileSelect(se.files),se.value="")}))}else{Q.style.display="";let W=(gi=e.attachments)!=null?gi:{};se&&(se.accept=((mi=W.allowedTypes)!=null?mi:wn).join(","),se.multiple=((fi=W.maxFiles)!=null?fi:4)>1),U&&U.updateConfig({allowedTypes:W.allowedTypes,maxFileSize:W.maxFileSize,maxFiles:W.maxFiles})}else Q&&(Q.style.display="none"),U&&U.clearAttachments();let ct=(hi=e.sendButton)!=null?hi:{},qs=(wi=ct.useIcon)!=null?wi:!1,ws=(vi=ct.iconText)!=null?vi:"\u2191",An=ct.iconName,En=(yi=ct.tooltipText)!=null?yi:"Send message",ba=(bi=ct.showTooltip)!=null?bi:!1,vs=(xi=ct.size)!=null?xi:"40px",Us=ct.backgroundColor,en=ct.textColor;if(qs){if(G.style.width=vs,G.style.height=vs,G.style.minWidth=vs,G.style.minHeight=vs,G.style.fontSize="18px",G.style.lineHeight="1",G.innerHTML="",An){let W=parseFloat(vs)||24,Me=en&&typeof en=="string"&&en.trim()?en.trim():"currentColor",Ze=re(An,W,Me,2);Ze?(G.appendChild(Ze),G.style.color=Me):(G.textContent=ws,en?G.style.color=en:G.classList.add("tvw-text-white"))}else G.textContent=ws,en?G.style.color=en:G.classList.add("tvw-text-white");G.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Us?(G.style.backgroundColor=Us,G.classList.remove("tvw-bg-cw-primary")):G.classList.add("tvw-bg-cw-primary")}else G.textContent=(Si=(Ci=e.copy)==null?void 0:Ci.sendButtonLabel)!=null?Si:"Send",G.style.width="",G.style.height="",G.style.minWidth="",G.style.minHeight="",G.style.fontSize="",G.style.lineHeight="",G.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",Us?(G.style.backgroundColor=Us,G.classList.remove("tvw-bg-cw-accent")):G.classList.add("tvw-bg-cw-accent"),en?G.style.color=en:G.classList.add("tvw-text-white");ct.borderWidth?(G.style.borderWidth=ct.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ct.borderColor?G.style.borderColor=ct.borderColor:G.style.borderColor="",ct.paddingX?(G.style.paddingLeft=ct.paddingX,G.style.paddingRight=ct.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ct.paddingY?(G.style.paddingTop=ct.paddingY,G.style.paddingBottom=ct.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let ys=ot==null?void 0:ot.querySelector(".tvw-send-button-tooltip");if(ba&&En)if(ys)ys.textContent=En,ys.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=En,ot==null||ot.insertBefore(W,G)}else ys&&(ys.style.display="none");let bs=(Ai=e.statusIndicator)!=null?Ai:{},xa=(Ei=bs.visible)!=null?Ei:!0;if(Tt.style.display=xa?"":"none",O){let W=O.getStatus(),Me=Ze=>{var ve,Re,ft,kt;return Ze==="idle"?(ve=bs.idleText)!=null?ve:Pt.idle:Ze==="connecting"?(Re=bs.connectingText)!=null?Re:Pt.connecting:Ze==="connected"?(ft=bs.connectedText)!=null?ft:Pt.connected:Ze==="error"?(kt=bs.errorText)!=null?kt:Pt.error:Pt[Ze]};Tt.textContent=Me(W)}},open(){b&&nt(!0,"api")},close(){b&&nt(!1,"api")},toggle(){b&&nt(!I,"api")},clearChat(){O.clearMessages();try{localStorage.removeItem(Xn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xn}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Xn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(w=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}a={},C.syncFromMetadata(),$==null||$.clear(),ae==null||ae.update()},setMessage(l){return!de||O.isStreaming()?!1:(!I&&b&&nt(!0,"system"),de.value=l,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let g=(l==null?void 0:l.trim())||de.value.trim();return g?(!I&&b&&nt(!0,"system"),de.value="",de.style.height="auto",O.sendMessage(g),!0):!1},startVoiceRecognition(){return jt||O.isStreaming()||!as()?!1:(!I&&b&&nt(!0,"system"),Ke.manuallyDeactivated=!1,rn(),Sn("user"),!0)},stopVoiceRecognition(){return jt?(Ke.manuallyDeactivated=!0,rn(),Kt("user"),!0):!1},injectMessage(l){return!I&&b&&nt(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!I&&b&&nt(!0,"system");let g=O.injectAssistantMessage(l);return M&&(M=!1,R&&(clearTimeout(R),R=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),g},injectUserMessage(l){return!I&&b&&nt(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!I&&b&&nt(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!I&&b&&nt(!0,"system"),O.injectMessageBatch(l)},injectTestMessage(l){!I&&b&&nt(!0,"system"),O.injectTestEvent(l)},async connectStream(l,g){return O.connectStream(l,g)},__pushEventStreamEvent(l){$&&$.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!N||!$||je()},hideEventStream(){fe&&Ce()},isEventStreamVisible(){return fe},focusInput(){return b&&!I||!de?!1:(de.focus(),!0)},async resolveApproval(l,g){let A=O.getMessages().find(S=>{var H;return S.variant==="approval"&&((H=S.approval)==null?void 0:H.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return O.resolveApproval(A.approval,g)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){d(l)},on(l,g){return s.on(l,g)},off(l,g){s.off(l,g)},isOpen(){return b&&I},isVoiceActive(){return Ke.active},getState(){return{open:b&&I,launcherEnabled:b,voiceActive:Ke.active,streaming:O.isStreaming()}},showCSATFeedback(l){!I&&b&&nt(!0,"system");let g=ze.querySelector(".tvw-feedback-container");g&&g.remove();let w=ur({onSubmit:async(A,S)=>{var H;O.isClientTokenMode()&&await O.submitCSATFeedback(A,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,A,S)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&b&&nt(!0,"system");let g=ze.querySelector(".tvw-feedback-container");g&&g.remove();let w=pr({onSubmit:async(A,S)=>{var H;O.isClientTokenMode()&&await O.submitNPSFeedback(A,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,A,S)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return O.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return O.submitNPSFeedback(l,g)},destroy(){ut.forEach(l=>l()),Oe.remove(),Ge==null||Ge.destroy(),Qe==null||Qe.remove(),Gt&&ee.removeEventListener("click",Gt)}};if((((qe=r==null?void 0:r.debugTools)!=null?qe:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:w=>w?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ut.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=w=>{let A=w.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",g),ut.push(()=>{window.removeEventListener("persona:focusInput",g)}),N){let w=S=>{let H=S.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&Lt.showEventStream()},A=S=>{let H=S.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",w),window.addEventListener("persona:hideEventStream",A),ut.push(()=>{window.removeEventListener("persona:showEventStream",w),window.removeEventListener("persona:hideEventStream",A)})}}let Ft=yl(e.persistState);if(Ft&&b){let l=bl(Ft.storage),g=`${Ft.keyPrefix}widget-open`,w=`${Ft.keyPrefix}widget-voice`,A=`${Ft.keyPrefix}widget-voice-mode`;if(l){let S=((dt=Ft.persist)==null?void 0:dt.openState)&&l.getItem(g)==="true",H=((Ue=Ft.persist)==null?void 0:Ue.voiceState)&&l.getItem(w)==="true",he=((xt=Ft.persist)==null?void 0:xt.voiceState)&&l.getItem(A)==="true";if(S&&setTimeout(()=>{Lt.open(),setTimeout(()=>{var le;if(H||he)Lt.startVoiceRecognition();else if((le=Ft.persist)!=null&&le.focusInput){let ue=t.querySelector("textarea");ue&&ue.focus()}},100)},0),(Nt=Ft.persist)!=null&&Nt.openState&&(s.on("widget:opened",()=>{l.setItem(g,"true")}),s.on("widget:closed",()=>{l.setItem(g,"false")})),(Jt=Ft.persist)!=null&&Jt.voiceState&&(s.on("voice:state",le=>{l.setItem(w,le.active?"true":"false")}),s.on("user:message",le=>{l.setItem(A,le.viaVoice?"true":"false")})),Ft.clearOnChatClear){let le=()=>{l.removeItem(g),l.removeItem(w),l.removeItem(A)},ue=()=>le();window.addEventListener("persona:clear-chat",ue),ut.push(()=>{window.removeEventListener("persona:clear-chat",ue)})}}}return Lt};var Ur={},xl=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let n=document.querySelector(t);if(!n)throw new Error(`Chat widget target "${t}" was not found`);return n}return t},Cl=()=>{try{if(typeof Ur!="undefined"&&Ur.url)return new URL("../widget.css",Ur.url).href}catch{}return null},pa=t=>{let n=Cl(),r=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);t.insertBefore(o,t.firstChild)};if(t instanceof ShadowRoot)if(n){let e=document.createElement("link");e.rel="stylesheet",e.href=n,e.setAttribute("data-persona","true"),t.insertBefore(e,t.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)}},zr=t=>{var c,v,d,f;let n=xl(t.target),r=document.createElement("div");r.className="persona-host";let e=(d=(v=(c=t.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?d:!0;e||(r.style.height="100%"),n.appendChild(r);let o=t.useShadowDom===!0,s,i;if(o){let h=r.attachShadow({mode:"open"});i=h,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),h.appendChild(s),pa(h)}else i=r,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),pa(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=gr(s,t.config,{debugTools:t.debugTools});(f=t.onReady)==null||f.call(t);let u={...a,host:r,destroy(){a.destroy(),r.remove(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}};return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=u),u};var ga={name:"@runtypelabs/persona",version:"1.46.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 Hn=ga.version;function un(t){if(t!==void 0)return typeof t=="string"?t:Array.isArray(t)?`[${t.map(n=>n.toString()).join(", ")}]`:t.toString()}function Al(t){if(t)return{getHeaders:un(t.getHeaders),onFeedback:un(t.onFeedback),onCopy:un(t.onCopy),requestMiddleware:un(t.requestMiddleware),actionHandlers:un(t.actionHandlers),actionParsers:un(t.actionParsers),postprocessMessage:un(t.postprocessMessage),contextProviders:un(t.contextProviders),streamParser:un(t.streamParser)}}var ma=`({ text, message }: any) => {
60
+ `}if(!k){let An="max-height: -moz-available !important; max-height: stretch !important;",En=l?"":"padding-top: 1.25em !important;";Oe.style.cssText+=An+En}};pn(),sr(t,e);let ut=[];N&&ut.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),ae==null||ae.destroy(),ae=null,$==null||$.destroy(),$=null,J=null});let Xt=null,Gn=()=>{Xt&&(Xt(),Xt=null),e.colorScheme==="auto"&&(Xt=Yi(()=>{sr(t,e)}))};Gn(),ut.push(()=>{Xt&&(Xt(),Xt=null)});let gn=sa(Ot),Gt=null,O,mn=!1,tn=!0,yn=0,Qn=0,nn=null,sn=!1,Bn=0,Rn=!1,Ws=125,Ps=2e3,Hs=5,Zn=50,Fn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},es=(Ne=(gt=e.voiceRecognition)==null?void 0:gt.autoResume)!=null?Ne:!1,ts=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},rn=()=>{d(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Bs=()=>{var A,S;if(((A=e.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=qr(a.voiceState),g=!!l.active,w=Number((S=l.timestamp)!=null?S:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-w<hl&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,Sn("restore"))},1e3)},Rs=()=>O?ca(O.getMessages()).filter(l=>!l.__skipPersist):[];function ns(l){if(!(i!=null&&i.save))return;let w={messages:l?ca(l):O?Rs():[],metadata:a};try{let A=i.save(w);A instanceof Promise&&A.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let bn=(l=!1)=>{if(!tn)return;let g=Date.now();sn&&g<Bn&&!l||(sn&&g>=Bn&&(sn=!1),!(!l&&!mn)&&(g-Qn<Ws||(Qn=g,nn&&cancelAnimationFrame(nn),nn=requestAnimationFrame(()=>{sn||!tn||(Rn=!0,Fe.scrollTop=Fe.scrollHeight,yn=Fe.scrollTop,requestAnimationFrame(()=>{Rn=!1}),nn=null)}))))},on=null,Fs=()=>Oe.querySelector("#persona-scroll-container")||Fe,$s=(l,g=500)=>{let w=l.scrollTop,A=l.clientHeight,S=l.scrollHeight,H=S-w;if(w+A>=S-2||Math.abs(H)<5)return;on!==null&&(cancelAnimationFrame(on),on=null);let le=performance.now(),ue=pe=>1-Math.pow(1-pe,3),be=pe=>{let Ae=l.scrollHeight;Ae!==S&&(S=Ae,H=S-w);let ne=pe-le,k=Math.min(ne/g,1),ge=ue(k),we=w+H*ge;l.scrollTop=we,k<1?on=requestAnimationFrame(be):(l.scrollTop=l.scrollHeight,on=null)};on=requestAnimationFrame(be)},Os=l=>{let g=new Map;l.forEach(w=>{let A=Fn.get(w.id);g.set(w.id,{streaming:w.streaming,role:w.role}),!A&&w.role==="assistant"&&s.emit("assistant:message",w),w.role==="assistant"&&(A!=null&&A.streaming)&&w.streaming===!1&&s.emit("assistant:complete",w),w.variant==="approval"&&w.approval&&(A?w.approval.status!=="pending"&&s.emit("approval:resolved",{approval:w.approval,decision:w.approval.status}):s.emit("approval:requested",{approval:w.approval,message:w}))}),Fn.clear(),g.forEach((w,A)=>{Fn.set(A,w)})},xn=(l,g,w)=>{var be,pe,Ae,ne;let A=document.createElement("div"),H=(()=>{var ge;let k=o.find(we=>we.renderLoadingIndicator);if(k!=null&&k.renderLoadingIndicator)return k.renderLoadingIndicator;if((ge=e.loadingIndicator)!=null&&ge.render)return e.loadingIndicator.render})();g.forEach(k=>{var mt,Wt;let ge=null,we=o.find(Z=>!!(k.variant==="reasoning"&&Z.renderReasoning||k.variant==="tool"&&Z.renderToolCall||k.variant==="approval"&&Z.renderApproval||!k.variant&&Z.renderMessage)),Ve=(mt=e.layout)==null?void 0:mt.messages;if(we)if(k.variant==="reasoning"&&k.reasoning&&we.renderReasoning){if(!q)return;ge=we.renderReasoning({message:k,defaultRenderer:()=>Hr(k),config:e})}else if(k.variant==="tool"&&k.toolCall&&we.renderToolCall){if(!V)return;ge=we.renderToolCall({message:k,defaultRenderer:()=>Br(k,e),config:e})}else if(k.variant==="approval"&&k.approval&&we.renderApproval){if(e.approval===!1)return;ge=we.renderApproval({message:k,defaultRenderer:()=>Rr(k,e),config:e})}else we.renderMessage&&(ge=we.renderMessage({message:k,defaultRenderer:()=>{let Z=Un(k,w,Ve,e.messageActions,ht,{loadingIndicatorRenderer:H,widgetConfig:e});return k.role!=="user"&&$r(Z,k,e,O),Z},config:e}));if(!ge&&k.role==="assistant"&&!k.variant&&e.enableComponentStreaming!==!1&&dr(k)){let _e=cr(k);if(_e){let Zt=lr(_e,{config:e,message:k,transform:w});if(Zt){let Yt=document.createElement("div");if(Yt.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(" "),Yt.id=`bubble-${k.id}`,Yt.setAttribute("data-message-id",k.id),k.content&&k.content.trim()){let hn=document.createElement("div");hn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",hn.innerHTML=w({text:k.content,message:k,streaming:!!k.streaming,raw:k.rawContent}),Yt.appendChild(hn)}Yt.appendChild(Zt),ge=Yt}}}if(!ge)if(k.variant==="reasoning"&&k.reasoning){if(!q)return;ge=Hr(k)}else if(k.variant==="tool"&&k.toolCall){if(!V)return;ge=Br(k,e)}else if(k.variant==="approval"&&k.approval){if(e.approval===!1)return;ge=Rr(k,e)}else{let Z=(Wt=e.layout)==null?void 0:Wt.messages;Z!=null&&Z.renderUserMessage&&k.role==="user"?ge=Z.renderUserMessage({message:k,config:e,streaming:!!k.streaming}):Z!=null&&Z.renderAssistantMessage&&k.role==="assistant"?ge=Z.renderAssistantMessage({message:k,config:e,streaming:!!k.streaming}):ge=Un(k,w,Z,e.messageActions,ht,{loadingIndicatorRenderer:H,widgetConfig:e}),k.role!=="user"&&ge&&$r(ge,k,e,O)}let Pe=document.createElement("div");Pe.className="tvw-flex",Pe.id=`wrapper-${k.id}`,Pe.setAttribute("data-wrapper-id",k.id),k.role==="user"&&Pe.classList.add("tvw-justify-end"),Pe.appendChild(ge),A.appendChild(Pe)});let he=g.some(k=>k.role==="assistant"&&k.streaming),le=g[g.length-1],ue=(le==null?void 0:le.role)==="assistant"&&!le.streaming&&le.variant!=="approval";if(mn&&g.some(k=>k.role==="user")&&!he&&!ue){let k={config:e,streaming:!0,location:"standalone",defaultRenderer:Wn},ge=o.find(Ve=>Ve.renderLoadingIndicator),we=null;if(ge!=null&&ge.renderLoadingIndicator&&(we=ge.renderLoadingIndicator(k)),we===null&&((be=e.loadingIndicator)!=null&&be.render)&&(we=e.loadingIndicator.render(k)),we===null&&(we=Wn()),we){let Ve=document.createElement("div"),Pe=((pe=e.loadingIndicator)==null?void 0:pe.showBubble)!==!1;Ve.className=Pe?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(we);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Ve),A.appendChild(mt)}}if(!mn&&g.length>0){let k=g[g.length-1],ge={config:e,lastMessage:k,messageCount:g.length},we=o.find(Pe=>Pe.renderIdleIndicator),Ve=null;if(we!=null&&we.renderIdleIndicator&&(Ve=we.renderIdleIndicator(ge)),Ve===null&&((Ae=e.loadingIndicator)!=null&&Ae.renderIdle)&&(Ve=e.loadingIndicator.renderIdle(ge)),Ve){let Pe=document.createElement("div"),mt=((ne=e.loadingIndicator)==null?void 0:ne.showBubble)!==!1;Pe.className=mt?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(Ve);let Wt=document.createElement("div");Wt.className="tvw-flex",Wt.id="wrapper-idle-indicator",Wt.setAttribute("data-wrapper-id","idle-indicator"),Wt.appendChild(Pe),A.appendChild(Wt)}}Xi(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let k=Fs();$s(k)})})},Cn=()=>{b&&(I?(Oe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),te.classList.remove("tvw-scale-95","tvw-opacity-0"),te.classList.add("tvw-scale-100","tvw-opacity-100"),Ge?Ge.element.style.display="none":Qe&&(Qe.style.display="none")):(Oe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),te.classList.remove("tvw-scale-100","tvw-opacity-100"),te.classList.add("tvw-scale-95","tvw-opacity-0"),Ge?Ge.element.style.display="":Qe&&(Qe.style.display="")))},nt=(l,g="user")=>{if(!b||I===l)return;let w=I;I=l,Cn(),I&&(fn(),bn(!0));let A={open:I,source:g,timestamp:Date.now()};I&&!w?s.emit("widget:opened",A):!I&&w&&s.emit("widget:closed",A),s.emit("widget:state",{open:I,launcherEnabled:b,voiceActive:Ke.active,streaming:O.isStreaming()})},$n=l=>{G.disabled=l,z&&(z.disabled=l),gn.buttons.forEach(g=>{g.disabled=l})},On=()=>{Ke.active||de&&de.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>On(),200)});let ss=()=>{var S,H,he,le,ue,be,pe,Ae,ne,k,ge,we,Ve,Pe;vt.textContent=(H=(S=e.copy)==null?void 0:S.welcomeTitle)!=null?H:"Hello \u{1F44B}",zt.textContent=(le=(he=e.copy)==null?void 0:he.welcomeSubtitle)!=null?le:"Ask anything about your account or products.",de.placeholder=(be=(ue=e.copy)==null?void 0:ue.inputPlaceholder)!=null?be:"How can I help...",((Ae=(pe=e.sendButton)==null?void 0:pe.useIcon)!=null?Ae:!1)||(G.textContent=(k=(ne=e.copy)==null?void 0:ne.sendButtonLabel)!=null?k:"Send");let g=(we=(ge=e.theme)==null?void 0:ge.inputFontFamily)!=null?we:"sans-serif",w=(Pe=(Ve=e.theme)==null?void 0:Ve.inputFontWeight)!=null?Pe:"400",A=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'}};de.style.fontFamily=A(g),de.style.fontWeight=w};e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{d(g=>({...g,sessionId:l}))}}),O=new _n(e,{onMessagesChanged(l){xn(ze,l,K),O&&(l.some(S=>S.role==="user")?gn.render([],O,de,l):gn.render(e.suggestionChips,O,de,l,e.suggestionChipsConfig)),bn(!mn),Os(l);let g=[...l].reverse().find(A=>A.role==="user"),w=Ke.lastUserMessageId;g&&g.id!==w&&(Ke.lastUserMessageId=g.id,s.emit("user:message",g)),Ke.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),ns(l)},onStatusChanged(l){var A;let g=(A=e.statusIndicator)!=null?A:{},w=S=>{var H,he,le,ue;return S==="idle"?(H=g.idleText)!=null?H:Pt.idle:S==="connecting"?(he=g.connectingText)!=null?he:Pt.connecting:S==="connected"?(le=g.connectedText)!=null?le:Pt.connected:S==="error"?(ue=g.errorText)!=null?ue:Pt.error:Pt[S]};Tt.textContent=w(l)},onStreamingChanged(l){mn=l,$n(l),O&&xn(ze,O.getMessages(),K),l||bn(!0)}}),e.clientToken&&O.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),$&&O.setSSEEventCallback((l,g)=>{$==null||$.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),u&&u.then(l=>{var g;l&&(l.metadata&&(a=qr(l.metadata),C.syncFromMetadata()),(g=l.messages)!=null&&g.length&&O.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let rs=l=>{var S;l.preventDefault();let g=de.value.trim(),w=(S=U==null?void 0:U.hasAttachments())!=null?S:!1;if(!g&&!w)return;let A;w&&(A=[],A.push(...U.getContentParts()),g&&A.push(er(g))),de.value="",de.style.height="auto",O.sendMessage(g,{contentParts:A}),w&&U.clearAttachments()},os=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),G.click())},is=async l=>{var w;if(((w=e.attachments)==null?void 0:w.enabled)!==!0||!U)return;let g=vl(l.clipboardData);g.length!==0&&(l.preventDefault(),await U.handleFiles(g))},Rt=null,jt=!1,an=null,Qt=null,as=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Sn=(l="user")=>{var H,he,le,ue;if(jt||O.isStreaming())return;let g=as();if(!g)return;Rt=new g;let A=(he=((H=e.voiceRecognition)!=null?H:{}).pauseDuration)!=null?he:2e3;Rt.continuous=!0,Rt.interimResults=!0,Rt.lang="en-US";let S=de.value;Rt.onresult=be=>{let pe="",Ae="";for(let k=0;k<be.results.length;k++){let ge=be.results[k],we=ge[0].transcript;ge.isFinal?pe+=we+" ":Ae=we}let ne=S+pe+Ae;de.value=ne,an&&clearTimeout(an),(pe||Ae)&&(an=window.setTimeout(()=>{let k=de.value.trim();k&&Rt&&jt&&(Kt(),de.value="",de.style.height="auto",O.sendMessage(k,{viaVoice:!0}))},A))},Rt.onerror=be=>{be.error!=="no-speech"&&Kt()},Rt.onend=()=>{if(jt){let be=de.value.trim();be&&be!==S.trim()&&(de.value="",de.style.height="auto",O.sendMessage(be,{viaVoice:!0})),Kt()}};try{if(Rt.start(),jt=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),ts(l),rn(),z){Qt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor};let be=(le=e.voiceRecognition)!=null?le:{},pe=(ue=be.recordingBackgroundColor)!=null?ue:"#ef4444",Ae=be.recordingIconColor,ne=be.recordingBorderColor;if(z.classList.add("tvw-voice-recording"),z.style.backgroundColor=pe,Ae){z.style.color=Ae;let k=z.querySelector("svg");k&&k.setAttribute("stroke",Ae)}ne&&(z.style.borderColor=ne),z.setAttribute("aria-label","Stop voice recognition")}}catch{Kt("system")}},Kt=(l="user")=>{if(jt){if(jt=!1,an&&(clearTimeout(an),an=null),Rt){try{Rt.stop()}catch{}Rt=null}if(Ke.active=!1,ts(l),rn(),z){if(z.classList.remove("tvw-voice-recording"),Qt){z.style.backgroundColor=Qt.backgroundColor,z.style.color=Qt.color,z.style.borderColor=Qt.borderColor;let g=z.querySelector("svg");g&&g.setAttribute("stroke",Qt.color||"currentColor"),Qt=null}z.setAttribute("aria-label","Start voice recognition")}}},Ns=(l,g)=>{var we,Ve,Pe,mt,Wt,Z,_e;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let A=p("div","tvw-send-button-wrapper"),S=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");S.type="button",S.setAttribute("aria-label","Start voice recognition");let H=(we=l==null?void 0:l.iconName)!=null?we:"mic",he=(Ve=g==null?void 0:g.size)!=null?Ve:"40px",le=(Pe=l==null?void 0:l.iconSize)!=null?Pe:he,ue=parseFloat(le)||24,be=(mt=l==null?void 0:l.backgroundColor)!=null?mt:g==null?void 0:g.backgroundColor,pe=(Wt=l==null?void 0:l.iconColor)!=null?Wt:g==null?void 0:g.textColor;S.style.width=le,S.style.height=le,S.style.minWidth=le,S.style.minHeight=le,S.style.fontSize="18px",S.style.lineHeight="1";let Ae=pe||"currentColor",ne=re(H,ue,Ae,1.5);ne?(S.appendChild(ne),S.style.color=Ae):(S.textContent="\u{1F3A4}",S.style.color=Ae),be?S.style.backgroundColor=be:S.classList.add("tvw-bg-cw-primary"),pe?S.style.color=pe:!pe&&!(g!=null&&g.textColor)&&S.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(S.style.borderWidth=l.borderWidth,S.style.borderStyle="solid"),l!=null&&l.borderColor&&(S.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(S.style.paddingLeft=l.paddingX,S.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(S.style.paddingTop=l.paddingY,S.style.paddingBottom=l.paddingY),A.appendChild(S);let k=(Z=l==null?void 0:l.tooltipText)!=null?Z:"Start voice recognition";if(((_e=l==null?void 0:l.showTooltip)!=null?_e:!1)&&k){let Zt=p("div","tvw-send-button-tooltip");Zt.textContent=k,A.appendChild(Zt)}return{micButton:S,micButtonWrapper:A}},Nn=()=>{if(jt){let l=de.value.trim();Ke.manuallyDeactivated=!0,rn(),Kt("user"),l&&(de.value="",de.style.height="auto",O.sendMessage(l))}else Ke.manuallyDeactivated=!1,rn(),Sn("user")};z&&(z.addEventListener("click",Nn),ut.push(()=>{Kt("system"),z&&z.removeEventListener("click",Nn)}));let Ds=s.on("assistant:complete",()=>{es&&(Ke.active||Ke.manuallyDeactivated||es==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&Sn("auto")},600))});ut.push(Ds);let _s=s.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});ut.push(_s);let ln=()=>{nt(!I,"user")},Ge=null,Qe=null;if(b){let l=o.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:e,defaultRenderer:()=>Es(e,ln).element,onToggle:ln});g&&(Qe=g)}Qe||(Ge=Es(e,ln))}Ge?t.appendChild(Ge.element):Qe&&t.appendChild(Qe),Cn(),gn.render(e.suggestionChips,O,de,void 0,e.suggestionChipsConfig),ss(),$n(O.isStreaming()),bn(!0),Bs(),x&&(b?I&&setTimeout(()=>On(),200):setTimeout(()=>On(),0));let fn=()=>{var w,A,S,H,he,le,ue,be;let l=(A=(w=e.launcher)==null?void 0:w.sidebarMode)!=null?A:!1,g=l||((H=(S=e.launcher)==null?void 0:S.fullHeight)!=null?H:!1);if(!b){te.style.height="",te.style.width="";return}if(!l){let pe=(le=(he=e==null?void 0:e.launcher)==null?void 0:he.width)!=null?le:e==null?void 0:e.launcherWidth,Ae=pe!=null?pe:"min(400px, calc(100vw - 24px))";te.style.width=Ae,te.style.maxWidth=Ae}if(!g){let pe=window.innerHeight,Ae=64,ne=(be=(ue=e.launcher)==null?void 0:ue.heightOffset)!=null?be:0,k=Math.max(200,pe-Ae),ge=Math.min(640,k),we=Math.max(200,ge-ne);te.style.height=`${we}px`}};fn(),window.addEventListener("resize",fn),ut.push(()=>window.removeEventListener("resize",fn)),yn=Fe.scrollTop;let ls=()=>{let l=Fe.scrollTop,g=Fe.scrollHeight,w=Fe.clientHeight,A=g-l-w,S=Math.abs(l-yn);if(yn=l,!Rn&&!(S<=Hs)){if(!tn&&A<Zn){sn=!1,tn=!0;return}tn&&A>Zn&&(sn=!0,Bn=Date.now()+Ps,tn=!1)}};Fe.addEventListener("scroll",ls,{passive:!0}),ut.push(()=>Fe.removeEventListener("scroll",ls)),ut.push(()=>{nn&&cancelAnimationFrame(nn)});let ds=()=>{ee&&(Gt&&(ee.removeEventListener("click",Gt),Gt=null),b?(ee.style.display="",Gt=()=>{I=!1,Cn()},ee.addEventListener("click",Gt)):ee.style.display="none")};ds(),(()=>{let{clearChatButton:l}=ye;l&&l.addEventListener("click",()=>{O.clearMessages();try{localStorage.removeItem(Xn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xn}`)}catch(w){console.error("[AgentWidget] Failed to clear default localStorage:",w)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Xn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(w){console.error("[AgentWidget] Failed to clear custom localStorage:",w)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let w=i.clear();w instanceof Promise&&w.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)}a={},C.syncFromMetadata(),$==null||$.clear(),ae==null||ae.update()})})(),wt.addEventListener("submit",rs),de.addEventListener("keydown",os),de.addEventListener("paste",is),ut.push(()=>{wt.removeEventListener("submit",rs),de.removeEventListener("keydown",os),de.removeEventListener("paste",is)}),ut.push(()=>{O.cancel()}),Ge?ut.push(()=>{Ge==null||Ge.destroy()}):Qe&&ut.push(()=>{Qe==null||Qe.remove()});let Lt={update(l){var Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,fo,ho,wo,vo,yo,bo,xo,Co,So,Ao,Eo,To,Mo,Lo,Io,ko,Wo,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,_o,jo,qo,Uo,zo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,fi,hi,wi,vi,yi,bi,xi,Ci,Si,Ai,Ei;let g=e.toolCall,w=e.colorScheme;e={...e,...l},pn(),sr(t,e),e.colorScheme!==w&&Gn();let A=Ls.getForInstance(e.plugins);o.length=0,o.push(...A),b=(Yr=(Kr=e.launcher)==null?void 0:Kr.enabled)!=null?Yr:!0,E=(Xr=(Vr=e.launcher)==null?void 0:Vr.autoExpand)!=null?Xr:!1,q=(Qr=(Gr=e.features)==null?void 0:Gr.showReasoning)!=null?Qr:!0,V=(eo=(Zr=e.features)==null?void 0:Zr.showToolCalls)!=null?eo:!0;let S=N;if(N=(no=(to=e.features)==null?void 0:to.showEventStreamToggle)!=null?no:!1,N&&!S){if($||(J=new Ms(_),$=new Ts(X,J),J.open().then(()=>$==null?void 0:$.restore()).catch(()=>{}),O.setSSEEventCallback((W,Me)=>{$.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:W,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!D&&xe){let W=(ro=(so=e.features)==null?void 0:so.eventStream)==null?void 0:ro.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"+(W!=null&&W.toggleButton?" "+W.toggleButton:"");D=p("button",Me),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let Ze=re("activity","18px","currentColor",1.5);Ze&&D.appendChild(Ze);let ve=ye.clearChatButtonWrapper,Re=ye.closeButtonWrapper,ft=ve||Re;ft&&ft.parentNode===xe?xe.insertBefore(D,ft):xe.appendChild(D),D.addEventListener("click",()=>{fe?Ce():je()})}}else!N&&S&&(Ce(),D&&(D.remove(),D=null),$==null||$.clear(),J==null||J.destroy(),$=null,J=null);if(((oo=e.launcher)==null?void 0:oo.enabled)===!1&&Ge&&(Ge.destroy(),Ge=null),((io=e.launcher)==null?void 0:io.enabled)===!1&&Qe&&(Qe.remove(),Qe=null),((ao=e.launcher)==null?void 0:ao.enabled)!==!1&&!Ge&&!Qe){let W=o.find(Me=>Me.renderLauncher);if(W!=null&&W.renderLauncher){let Me=W.renderLauncher({config:e,defaultRenderer:()=>Es(e,ln).element,onToggle:ln});Me&&(Qe=Me,t.appendChild(Qe))}Qe||(Ge=Es(e,ln),t.appendChild(Ge.element))}Ge&&Ge.update(e),yt&&((lo=e.launcher)==null?void 0:lo.title)!==void 0&&(yt.textContent=e.launcher.title),ce&&((co=e.launcher)==null?void 0:co.subtitle)!==void 0&&(ce.textContent=e.launcher.subtitle);let H=(uo=e.layout)==null?void 0:uo.header;if((H==null?void 0:H.layout)!==T&&xe){let W=H?jn(e,H,{showClose:b,onClose:()=>nt(!1,"user")}):cn({config:e,showClose:b,onClose:()=>nt(!1,"user")});xe.replaceWith(W.header),xe=W.header,ke=W.iconHolder,yt=W.headerTitle,ce=W.headerSubtitle,ee=W.closeButton,T=H==null?void 0:H.layout}else if(H&&(ke&&(ke.style.display=H.showIcon===!1?"none":""),yt&&(yt.style.display=H.showTitle===!1?"none":""),ce&&(ce.style.display=H.showSubtitle===!1?"none":""),ee&&(ee.style.display=H.showCloseButton===!1?"none":""),ye.clearChatButtonWrapper)){let W=H.showClearChat;if(W!==void 0){ye.clearChatButtonWrapper.style.display=W?"":"none";let{closeButtonWrapper:Me}=ye;Me&&!Me.classList.contains("tvw-absolute")&&(W?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let le=((po=e.layout)==null?void 0:po.showHeader)!==!1;xe&&(xe.style.display=le?"":"none");let ue=((go=e.layout)==null?void 0:go.showFooter)!==!1;Je&&(Je.style.display=ue?"":"none"),b!==Y?b?nt(E,"auto"):(I=!0,Cn()):E!==P&&nt(E,"auto"),P=E,Y=b,fn(),ds(),JSON.stringify(l.toolCall)!==JSON.stringify(g)&&O&&xn(ze,O.getMessages(),K);let ne=(mo=e.launcher)!=null?mo:{},k=(fo=ne.headerIconHidden)!=null?fo:!1,ge=(wo=(ho=e.layout)==null?void 0:ho.header)==null?void 0:wo.showIcon,we=k||ge===!1,Ve=ne.headerIconName,Pe=(vo=ne.headerIconSize)!=null?vo:"48px";if(ke){let W=Be.querySelector(".tvw-border-b-cw-divider"),Me=W==null?void 0:W.querySelector(".tvw-flex-col");if(we)ke.style.display="none",W&&Me&&!W.contains(Me)&&W.insertBefore(Me,W.firstChild);else{if(ke.style.display="",ke.style.height=Pe,ke.style.width=Pe,W&&Me&&(W.contains(ke)?ke.nextSibling!==Me&&(ke.remove(),W.insertBefore(ke,Me)):W.insertBefore(ke,Me)),Ve){let ve=parseFloat(Pe)||24,Re=re(Ve,ve*.6,"#ffffff",2);Re?ke.replaceChildren(Re):ke.textContent=(yo=ne.agentIconText)!=null?yo:"\u{1F4AC}"}else if(ne.iconUrl){let ve=ke.querySelector("img");if(ve)ve.src=ne.iconUrl,ve.style.height=Pe,ve.style.width=Pe;else{let Re=document.createElement("img");Re.src=ne.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=Pe,Re.style.width=Pe,ke.replaceChildren(Re)}}else{let ve=ke.querySelector("svg"),Re=ke.querySelector("img");(ve||Re)&&ke.replaceChildren(),ke.textContent=(bo=ne.agentIconText)!=null?bo:"\u{1F4AC}"}let Ze=ke.querySelector("img");Ze&&(Ze.style.height=Pe,Ze.style.width=Pe)}}let mt=(Co=(xo=e.layout)==null?void 0:xo.header)==null?void 0:Co.showTitle,Wt=(Ao=(So=e.layout)==null?void 0:So.header)==null?void 0:Ao.showSubtitle;if(yt&&(yt.style.display=mt===!1?"none":""),ce&&(ce.style.display=Wt===!1?"none":""),ee){((To=(Eo=e.layout)==null?void 0:Eo.header)==null?void 0:To.showCloseButton)===!1?ee.style.display="none":ee.style.display="";let Me=(Mo=ne.closeButtonSize)!=null?Mo:"32px",Ze=(Lo=ne.closeButtonPlacement)!=null?Lo:"inline";ee.style.height=Me,ee.style.width=Me;let{closeButtonWrapper:ve}=ye,Re=Ze==="top-right",ft=ve==null?void 0:ve.classList.contains("tvw-absolute");if(ve&&Re!==ft)if(ve.remove(),Re)ve.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Be.style.position="relative",Be.appendChild(ve);else{let Le=(ko=(Io=ne.clearChat)==null?void 0:Io.placement)!=null?ko:"inline",Ct=(Po=(Wo=ne.clearChat)==null?void 0:Wo.enabled)!=null?Po:!0;ve.className=Ct&&Le==="inline"?"":"tvw-ml-auto";let Dt=Be.querySelector(".tvw-border-b-cw-divider");Dt&&Dt.appendChild(ve)}if(ne.closeButtonColor?(ee.style.color=ne.closeButtonColor,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),ne.closeButtonBackgroundColor?(ee.style.backgroundColor=ne.closeButtonBackgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),ne.closeButtonBorderWidth||ne.closeButtonBorderColor){let Le=ne.closeButtonBorderWidth||"0px",Ct=ne.closeButtonBorderColor||"transparent";ee.style.border=`${Le} solid ${Ct}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");ne.closeButtonBorderRadius?(ee.style.borderRadius=ne.closeButtonBorderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),ne.closeButtonPaddingX?(ee.style.paddingLeft=ne.closeButtonPaddingX,ee.style.paddingRight=ne.closeButtonPaddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),ne.closeButtonPaddingY?(ee.style.paddingTop=ne.closeButtonPaddingY,ee.style.paddingBottom=ne.closeButtonPaddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let kt=(Ho=ne.closeButtonIconName)!=null?Ho:"x",qt=(Bo=ne.closeButtonIconText)!=null?Bo:"\xD7";ee.innerHTML="";let $t=re(kt,"20px",ne.closeButtonColor||"",2);$t?ee.appendChild($t):ee.textContent=qt;let at=(Ro=ne.closeButtonTooltipText)!=null?Ro:"Close chat",Ut=(Fo=ne.closeButtonShowTooltip)!=null?Fo:!0;if(ee.setAttribute("aria-label",at),ve&&(ve._cleanupTooltip&&(ve._cleanupTooltip(),delete ve._cleanupTooltip),Ut&&at)){let Le=null,Ct=()=>{if(Le||!ee)return;Le=p("div","tvw-clear-chat-tooltip"),Le.textContent=at;let xs=p("div");xs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(xs);let Tn=ee.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Tn.left+Tn.width/2}px`,Le.style.top=`${Tn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Dt=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};ve.addEventListener("mouseenter",Ct),ve.addEventListener("mouseleave",Dt),ee.addEventListener("focus",Ct),ee.addEventListener("blur",Dt),ve._cleanupTooltip=()=>{Dt(),ve&&(ve.removeEventListener("mouseenter",Ct),ve.removeEventListener("mouseleave",Dt)),ee&&(ee.removeEventListener("focus",Ct),ee.removeEventListener("blur",Dt))}}}let{clearChatButton:Z,clearChatButtonWrapper:_e}=ye;if(Z){let W=($o=ne.clearChat)!=null?$o:{},Me=(Oo=W.enabled)!=null?Oo:!0,Ze=(Do=(No=e.layout)==null?void 0:No.header)==null?void 0:Do.showClearChat,ve=Ze!==void 0?Ze:Me,Re=(_o=W.placement)!=null?_o:"inline";if(_e){_e.style.display=ve?"":"none";let{closeButtonWrapper:ft}=ye;ft&&!ft.classList.contains("tvw-absolute")&&(ve?ft.classList.remove("tvw-ml-auto"):ft.classList.add("tvw-ml-auto"));let kt=Re==="top-right",qt=_e.classList.contains("tvw-absolute");if(kt!==qt&&ve){if(_e.remove(),kt)_e.className="tvw-absolute tvw-top-4 tvw-z-50",_e.style.right="48px",Be.style.position="relative",Be.appendChild(_e);else{_e.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",_e.style.right="";let at=Be.querySelector(".tvw-border-b-cw-divider"),Ut=ye.closeButtonWrapper;at&&Ut&&Ut.parentElement===at?at.insertBefore(_e,Ut):at&&at.appendChild(_e)}let $t=ye.closeButtonWrapper;$t&&!$t.classList.contains("tvw-absolute")&&(kt?$t.classList.add("tvw-ml-auto"):$t.classList.remove("tvw-ml-auto"))}}if(ve){let ft=(jo=W.size)!=null?jo:"32px";Z.style.height=ft,Z.style.width=ft;let kt=(qo=W.iconName)!=null?qo:"refresh-cw",qt=(Uo=W.iconColor)!=null?Uo:"";Z.innerHTML="";let $t=re(kt,"20px",qt||"",2);if($t&&Z.appendChild($t),qt?(Z.style.color=qt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),W.backgroundColor?(Z.style.backgroundColor=W.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let Le=W.borderWidth||"0px",Ct=W.borderColor||"transparent";Z.style.border=`${Le} solid ${Ct}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");W.borderRadius?(Z.style.borderRadius=W.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),W.paddingX?(Z.style.paddingLeft=W.paddingX,Z.style.paddingRight=W.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),W.paddingY?(Z.style.paddingTop=W.paddingY,Z.style.paddingBottom=W.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let at=(zo=W.tooltipText)!=null?zo:"Clear chat",Ut=(Jo=W.showTooltip)!=null?Jo:!0;if(Z.setAttribute("aria-label",at),_e&&(_e._cleanupTooltip&&(_e._cleanupTooltip(),delete _e._cleanupTooltip),Ut&&at)){let Le=null,Ct=()=>{if(Le||!Z)return;Le=p("div","tvw-clear-chat-tooltip"),Le.textContent=at;let xs=p("div");xs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(xs);let Tn=Z.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Tn.left+Tn.width/2}px`,Le.style.top=`${Tn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Dt=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};_e.addEventListener("mouseenter",Ct),_e.addEventListener("mouseleave",Dt),Z.addEventListener("focus",Ct),Z.addEventListener("blur",Dt),_e._cleanupTooltip=()=>{Dt(),_e&&(_e.removeEventListener("mouseenter",Ct),_e.removeEventListener("mouseleave",Dt)),Z&&(Z.removeEventListener("focus",Ct),Z.removeEventListener("blur",Dt))}}}}let Zt=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Is],Yt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Pn.message,Pn.messageAndClick];C=ks({parsers:Zt,handlers:Yt,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),K=ua(e,C,ie),O.updateConfig(e),xn(ze,O.getMessages(),K),gn.render(e.suggestionChips,O,de,void 0,e.suggestionChipsConfig),ss(),$n(O.isStreaming());let hn=((Ko=e.voiceRecognition)==null?void 0:Ko.enabled)===!0,js=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(hn&&js)if(!z||!et){let W=Ns(e.voiceRecognition,e.sendButton);W&&(z=W.micButton,et=W.micButtonWrapper,_t.insertBefore(et,ot),z.addEventListener("click",Nn),z.disabled=O.isStreaming())}else{let W=(Yo=e.voiceRecognition)!=null?Yo:{},Me=(Vo=e.sendButton)!=null?Vo:{},Ze=(Xo=W.iconName)!=null?Xo:"mic",ve=(Go=Me.size)!=null?Go:"40px",Re=(Qo=W.iconSize)!=null?Qo:ve,ft=parseFloat(Re)||24;z.style.width=Re,z.style.height=Re,z.style.minWidth=Re,z.style.minHeight=Re;let kt=(ei=(Zo=W.iconColor)!=null?Zo:Me.textColor)!=null?ei:"currentColor";z.innerHTML="";let qt=re(Ze,ft,kt,2);qt?z.appendChild(qt):z.textContent="\u{1F3A4}";let $t=(ti=W.backgroundColor)!=null?ti:Me.backgroundColor;$t?(z.style.backgroundColor=$t,z.classList.remove("tvw-bg-cw-primary")):(z.style.backgroundColor="",z.classList.add("tvw-bg-cw-primary")),kt?(z.style.color=kt,z.classList.remove("tvw-text-white")):!kt&&!Me.textColor&&(z.style.color="",z.classList.add("tvw-text-white")),W.borderWidth?(z.style.borderWidth=W.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),W.borderColor?z.style.borderColor=W.borderColor:z.style.borderColor="",W.paddingX?(z.style.paddingLeft=W.paddingX,z.style.paddingRight=W.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),W.paddingY?(z.style.paddingTop=W.paddingY,z.style.paddingBottom=W.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let at=et==null?void 0:et.querySelector(".tvw-send-button-tooltip"),Ut=(ni=W.tooltipText)!=null?ni:"Start voice recognition";if(((si=W.showTooltip)!=null?si:!1)&&Ut)if(at)at.textContent=Ut,at.style.display="";else{let Ct=document.createElement("div");Ct.className="tvw-send-button-tooltip",Ct.textContent=Ut,et==null||et.insertBefore(Ct,z)}else at&&(at.style.display="none");et.style.display="",z.disabled=O.isStreaming()}else z&&et&&(et.style.display="none",jt&&Kt());if(((ri=e.attachments)==null?void 0:ri.enabled)===!0)if(!Q||!F){let W=(oi=e.attachments)!=null?oi:{},Ze=(ai=((ii=e.sendButton)!=null?ii:{}).size)!=null?ai:"40px";$e||($e=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),$e.style.display="none",wt.insertBefore($e,de)),se||(se=document.createElement("input"),se.type="file",se.accept=((li=W.allowedTypes)!=null?li:wn).join(","),se.multiple=((di=W.maxFiles)!=null?di:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),wt.insertBefore(se,de)),Q=p("div","tvw-send-button-wrapper"),F=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),F.type="button",F.setAttribute("aria-label",(ci=W.buttonTooltipText)!=null?ci:"Attach file");let ve=(ui=W.buttonIconName)!=null?ui:"paperclip",Re=Ze,ft=parseFloat(Re)||40,kt=Math.round(ft*.6);F.style.width=Re,F.style.height=Re,F.style.minWidth=Re,F.style.minHeight=Re,F.style.fontSize="18px",F.style.lineHeight="1",F.style.backgroundColor="transparent",F.style.color="var(--cw-primary, #111827)",F.style.border="none",F.style.borderRadius="6px",F.style.transition="background-color 0.15s ease",F.addEventListener("mouseenter",()=>{F.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),F.addEventListener("mouseleave",()=>{F.style.backgroundColor="transparent"});let qt=re(ve,kt,"currentColor",1.5);qt?F.appendChild(qt):F.textContent="\u{1F4CE}",F.addEventListener("click",Ut=>{Ut.preventDefault(),se==null||se.click()}),Q.appendChild(F);let $t=(pi=W.buttonTooltipText)!=null?pi:"Attach file",at=p("div","tvw-send-button-tooltip");at.textContent=$t,Q.appendChild(at),Mt.append(Q),!U&&se&&$e&&(U=In.fromConfig(W),U.setPreviewsContainer($e),se.addEventListener("change",async()=>{U&&(se!=null&&se.files)&&(await U.handleFileSelect(se.files),se.value="")}))}else{Q.style.display="";let W=(gi=e.attachments)!=null?gi:{};se&&(se.accept=((mi=W.allowedTypes)!=null?mi:wn).join(","),se.multiple=((fi=W.maxFiles)!=null?fi:4)>1),U&&U.updateConfig({allowedTypes:W.allowedTypes,maxFileSize:W.maxFileSize,maxFiles:W.maxFiles})}else Q&&(Q.style.display="none"),U&&U.clearAttachments();let ct=(hi=e.sendButton)!=null?hi:{},qs=(wi=ct.useIcon)!=null?wi:!1,ws=(vi=ct.iconText)!=null?vi:"\u2191",An=ct.iconName,En=(yi=ct.tooltipText)!=null?yi:"Send message",ba=(bi=ct.showTooltip)!=null?bi:!1,vs=(xi=ct.size)!=null?xi:"40px",Us=ct.backgroundColor,en=ct.textColor;if(qs){if(G.style.width=vs,G.style.height=vs,G.style.minWidth=vs,G.style.minHeight=vs,G.style.fontSize="18px",G.style.lineHeight="1",G.innerHTML="",An){let W=parseFloat(vs)||24,Me=en&&typeof en=="string"&&en.trim()?en.trim():"currentColor",Ze=re(An,W,Me,2);Ze?(G.appendChild(Ze),G.style.color=Me):(G.textContent=ws,en?G.style.color=en:G.classList.add("tvw-text-white"))}else G.textContent=ws,en?G.style.color=en:G.classList.add("tvw-text-white");G.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Us?(G.style.backgroundColor=Us,G.classList.remove("tvw-bg-cw-primary")):G.classList.add("tvw-bg-cw-primary")}else G.textContent=(Si=(Ci=e.copy)==null?void 0:Ci.sendButtonLabel)!=null?Si:"Send",G.style.width="",G.style.height="",G.style.minWidth="",G.style.minHeight="",G.style.fontSize="",G.style.lineHeight="",G.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",Us?(G.style.backgroundColor=Us,G.classList.remove("tvw-bg-cw-accent")):G.classList.add("tvw-bg-cw-accent"),en?G.style.color=en:G.classList.add("tvw-text-white");ct.borderWidth?(G.style.borderWidth=ct.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ct.borderColor?G.style.borderColor=ct.borderColor:G.style.borderColor="",ct.paddingX?(G.style.paddingLeft=ct.paddingX,G.style.paddingRight=ct.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ct.paddingY?(G.style.paddingTop=ct.paddingY,G.style.paddingBottom=ct.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let ys=ot==null?void 0:ot.querySelector(".tvw-send-button-tooltip");if(ba&&En)if(ys)ys.textContent=En,ys.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=En,ot==null||ot.insertBefore(W,G)}else ys&&(ys.style.display="none");let bs=(Ai=e.statusIndicator)!=null?Ai:{},xa=(Ei=bs.visible)!=null?Ei:!0;if(Tt.style.display=xa?"":"none",O){let W=O.getStatus(),Me=Ze=>{var ve,Re,ft,kt;return Ze==="idle"?(ve=bs.idleText)!=null?ve:Pt.idle:Ze==="connecting"?(Re=bs.connectingText)!=null?Re:Pt.connecting:Ze==="connected"?(ft=bs.connectedText)!=null?ft:Pt.connected:Ze==="error"?(kt=bs.errorText)!=null?kt:Pt.error:Pt[Ze]};Tt.textContent=Me(W)}},open(){b&&nt(!0,"api")},close(){b&&nt(!1,"api")},toggle(){b&&nt(!I,"api")},clearChat(){O.clearMessages();try{localStorage.removeItem(Xn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xn}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Xn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(w=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}a={},C.syncFromMetadata(),$==null||$.clear(),ae==null||ae.update()},setMessage(l){return!de||O.isStreaming()?!1:(!I&&b&&nt(!0,"system"),de.value=l,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let g=(l==null?void 0:l.trim())||de.value.trim();return g?(!I&&b&&nt(!0,"system"),de.value="",de.style.height="auto",O.sendMessage(g),!0):!1},startVoiceRecognition(){return jt||O.isStreaming()||!as()?!1:(!I&&b&&nt(!0,"system"),Ke.manuallyDeactivated=!1,rn(),Sn("user"),!0)},stopVoiceRecognition(){return jt?(Ke.manuallyDeactivated=!0,rn(),Kt("user"),!0):!1},injectMessage(l){return!I&&b&&nt(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!I&&b&&nt(!0,"system");let g=O.injectAssistantMessage(l);return M&&(M=!1,R&&(clearTimeout(R),R=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),g},injectUserMessage(l){return!I&&b&&nt(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!I&&b&&nt(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!I&&b&&nt(!0,"system"),O.injectMessageBatch(l)},injectTestMessage(l){!I&&b&&nt(!0,"system"),O.injectTestEvent(l)},async connectStream(l,g){return O.connectStream(l,g)},__pushEventStreamEvent(l){$&&$.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!N||!$||je()},hideEventStream(){fe&&Ce()},isEventStreamVisible(){return fe},focusInput(){return b&&!I||!de?!1:(de.focus(),!0)},async resolveApproval(l,g){let A=O.getMessages().find(S=>{var H;return S.variant==="approval"&&((H=S.approval)==null?void 0:H.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return O.resolveApproval(A.approval,g)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){d(l)},on(l,g){return s.on(l,g)},off(l,g){s.off(l,g)},isOpen(){return b&&I},isVoiceActive(){return Ke.active},getState(){return{open:b&&I,launcherEnabled:b,voiceActive:Ke.active,streaming:O.isStreaming()}},showCSATFeedback(l){!I&&b&&nt(!0,"system");let g=ze.querySelector(".tvw-feedback-container");g&&g.remove();let w=ur({onSubmit:async(A,S)=>{var H;O.isClientTokenMode()&&await O.submitCSATFeedback(A,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,A,S)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&b&&nt(!0,"system");let g=ze.querySelector(".tvw-feedback-container");g&&g.remove();let w=pr({onSubmit:async(A,S)=>{var H;O.isClientTokenMode()&&await O.submitNPSFeedback(A,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,A,S)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return O.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return O.submitNPSFeedback(l,g)},destroy(){ut.forEach(l=>l()),Oe.remove(),Ge==null||Ge.destroy(),Qe==null||Qe.remove(),Gt&&ee.removeEventListener("click",Gt)}};if((((qe=r==null?void 0:r.debugTools)!=null?qe:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:w=>w?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ut.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=w=>{let A=w.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",g),ut.push(()=>{window.removeEventListener("persona:focusInput",g)}),N){let w=S=>{let H=S.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&Lt.showEventStream()},A=S=>{let H=S.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",w),window.addEventListener("persona:hideEventStream",A),ut.push(()=>{window.removeEventListener("persona:showEventStream",w),window.removeEventListener("persona:hideEventStream",A)})}}let Ft=yl(e.persistState);if(Ft&&b){let l=bl(Ft.storage),g=`${Ft.keyPrefix}widget-open`,w=`${Ft.keyPrefix}widget-voice`,A=`${Ft.keyPrefix}widget-voice-mode`;if(l){let S=((dt=Ft.persist)==null?void 0:dt.openState)&&l.getItem(g)==="true",H=((Ue=Ft.persist)==null?void 0:Ue.voiceState)&&l.getItem(w)==="true",he=((xt=Ft.persist)==null?void 0:xt.voiceState)&&l.getItem(A)==="true";if(S&&setTimeout(()=>{Lt.open(),setTimeout(()=>{var le;if(H||he)Lt.startVoiceRecognition();else if((le=Ft.persist)!=null&&le.focusInput){let ue=t.querySelector("textarea");ue&&ue.focus()}},100)},0),(Nt=Ft.persist)!=null&&Nt.openState&&(s.on("widget:opened",()=>{l.setItem(g,"true")}),s.on("widget:closed",()=>{l.setItem(g,"false")})),(Jt=Ft.persist)!=null&&Jt.voiceState&&(s.on("voice:state",le=>{l.setItem(w,le.active?"true":"false")}),s.on("user:message",le=>{l.setItem(A,le.viaVoice?"true":"false")})),Ft.clearOnChatClear){let le=()=>{l.removeItem(g),l.removeItem(w),l.removeItem(A)},ue=()=>le();window.addEventListener("persona:clear-chat",ue),ut.push(()=>{window.removeEventListener("persona:clear-chat",ue)})}}}return Lt};var Ur={},xl=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let n=document.querySelector(t);if(!n)throw new Error(`Chat widget target "${t}" was not found`);return n}return t},Cl=()=>{try{if(typeof Ur!="undefined"&&Ur.url)return new URL("../widget.css",Ur.url).href}catch{}return null},pa=t=>{let n=Cl(),r=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);t.insertBefore(o,t.firstChild)};if(t instanceof ShadowRoot)if(n){let e=document.createElement("link");e.rel="stylesheet",e.href=n,e.setAttribute("data-persona","true"),t.insertBefore(e,t.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)}},zr=t=>{var c,v,d,f;let n=xl(t.target),r=document.createElement("div");r.className="persona-host";let e=(d=(v=(c=t.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?d:!0;e||(r.style.height="100%"),n.appendChild(r);let o=t.useShadowDom===!0,s,i;if(o){let h=r.attachShadow({mode:"open"});i=h,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),h.appendChild(s),pa(h)}else i=r,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),pa(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=gr(s,t.config,{debugTools:t.debugTools});(f=t.onReady)==null||f.call(t);let u={...a,host:r,destroy(){a.destroy(),r.remove(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}};return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=u),u};var ga={name:"@runtypelabs/persona",version:"1.46.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 Hn=ga.version;function un(t){if(t!==void 0)return typeof t=="string"?t:Array.isArray(t)?`[${t.map(n=>n.toString()).join(", ")}]`:t.toString()}function Al(t){if(t)return{getHeaders:un(t.getHeaders),onFeedback:un(t.onFeedback),onCopy:un(t.onCopy),requestMiddleware:un(t.requestMiddleware),actionHandlers:un(t.actionHandlers),actionParsers:un(t.actionParsers),postprocessMessage:un(t.postprocessMessage),contextProviders:un(t.contextProviders),streamParser:un(t.streamParser)}}var ma=`({ 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