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