@runtypelabs/persona 1.44.1 → 1.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +29 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +141 -2
- package/dist/index.d.ts +141 -2
- package/dist/index.global.js +53 -53
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +29 -29
- package/dist/index.js.map +1 -1
- package/dist/widget.css +68 -0
- package/package.json +1 -1
- package/src/client.ts +123 -0
- package/src/components/approval-bubble.ts +223 -0
- package/src/components/message-bubble.ts +128 -2
- package/src/components/reasoning-bubble.ts +1 -1
- package/src/components/tool-bubble.ts +4 -4
- package/src/index.ts +3 -0
- package/src/plugins/types.ts +10 -0
- package/src/session.ts +122 -1
- package/src/styles/widget.css +68 -0
- package/src/types.ts +80 -1
- package/src/ui.ts +159 -0
- package/src/utils/attachment-manager.ts +8 -2
- package/src/utils/content.ts +5 -0
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
3
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},ks=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ws=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Is=()=>{var n;let e=La();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Ps=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=(0,sn.parse)(r,sn.STR|sn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Ls(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Ls(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Li=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Ls(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ls(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let a=(0,sn.parse)(s,sn.STR|sn.OBJ),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Hs=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var ka="https://api.runtype.com/v1/dispatch",ki="https://api.runtype.com",sr=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Wa(e){switch(e){case"json":return Ps;case"regex-json":return Is;case"xml":return Hs;case"plain":default:return Ws}}var yn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,t,o;this.apiUrl=(r=n.apiUrl)!=null?r:ka,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Wa(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var t;let r=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(r=(n=this.config).onSessionInit)==null||r.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"nps",rating:n,comment:r})}async dispatch(n,r){return this.isAgentMode()?this.dispatchAgent(n,r):this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let f=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:f}),f}let g=await this.buildPayload(n.messages),w=g.metadata?Object.fromEntries(Object.entries(g.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,c={sessionId:d.sessionId,messages:n.messages.filter(sr).map(f=>{var x,C,E;return{id:f.id,role:f.role,content:(E=(C=(x=f.contentParts)!=null?x:f.llmContent)!=null?C:f.rawContent)!=null?E:f.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...w&&Object.keys(w).length>0&&{metadata:w},...g.context&&{context:g.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c);let h=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c),signal:t.signal});if(!h.ok){let f=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let C=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:C}),C}if(h.status===429){let C=new Error(f.hint||"Message limit reached for this session.");throw r({type:"error",error:C}),C}let x=new Error(f.error||"Failed to send message");throw r({type:"error",error:x}),x}if(!h.body){let f=new Error("No response body received");throw r({type:"error",error:f}),f}r({type:"status",status:"connected"});try{await this.streamResponse(h.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let g=d instanceof Error?d:new Error(String(d));throw!g.message.includes("Session expired")&&!g.message.includes("Message limit")&&r({type:"error",error:g}),g}}async dispatchProxy(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(sr).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),t={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}return t}async buildPayload(n){let t={messages:n.slice().filter(sr).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(n,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,t){var pe,Ue,it,Tt,$t,Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt,Q,Oe,bt,Wt,Mt,j,Ze,We,z,R,he,ue,te,Le,Ne,q,de,Be,Je,st,Tn,rt,Jt,qn,an,Kt,F,ln,Gt,un,zn,Qt,Zt,Mn,Ln,ps,gs,ms,Un,kn,Ke,Jn,Kn,en,hs,fs,Yn,pn,tn,ws,vs,ys,Zs,gn,mn,tt,Wn,Vn,Xn,Gn,Ht,Nt,nn,Yt,Qn,hn,qt,bs,In,Cs,xs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,g=()=>a+d++,w=B=>{let ne=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,ae=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Xe=B.tools?B.tools.map(pt=>({...pt,chunks:pt.chunks?[...pt.chunks]:void 0})):void 0;return{...B,reasoning:ne,toolCall:ae,tools:Xe}},c=B=>{r({type:"message",message:w(B)})},h=null,f={current:null},x=new Map,C=new Map,E={lastId:null,byStep:new Map},S={lastId:null,byCall:new Map},k=B=>{if(B==null)return null;try{return String(B)}catch{return null}},V=B=>{var ne,ae,Xe,pt,Et;return k((Et=(pt=(Xe=(ae=(ne=B.stepId)!=null?ne:B.step_id)!=null?ae:B.step)!=null?Xe:B.parentId)!=null?pt:B.flowStepId)!=null?Et:B.flow_step_id)},y=B=>{var ne,ae,Xe,pt,Et,at,m;return k((m=(at=(Et=(pt=(Xe=(ae=(ne=B.callId)!=null?ne:B.call_id)!=null?ae:B.requestId)!=null?Xe:B.request_id)!=null?pt:B.toolCallId)!=null?Et:B.tool_call_id)!=null?at:B.stepId)!=null?m:B.step_id)},O=()=>h||(h={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:g()},c(h),h),W=(B,ne)=>{E.lastId=ne,B&&E.byStep.set(B,ne)},H=(B,ne)=>{var Et;let ae=(Et=B.reasoningId)!=null?Et:B.id,Xe=V(B);if(ae){let at=String(ae);return W(Xe,at),at}if(Xe){let at=E.byStep.get(Xe);if(at)return E.lastId=at,at}if(E.lastId&&!ne)return E.lastId;if(!ne)return null;let pt=`reason-${g()}`;return W(Xe,pt),pt},oe=B=>{let ne=x.get(B);if(ne)return ne;let ae={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:g(),reasoning:{id:B,status:"streaming",chunks:[]}};return x.set(B,ae),c(ae),ae},_=(B,ne)=>{S.lastId=ne,B&&S.byCall.set(B,ne)},le=(B,ne)=>{var Et;let ae=(Et=B.toolId)!=null?Et:B.id,Xe=y(B);if(ae){let at=String(ae);return _(Xe,at),at}if(Xe){let at=S.byCall.get(Xe);if(at)return S.lastId=at,at}if(S.lastId&&!ne)return S.lastId;if(!ne)return null;let pt=`tool-${g()}`;return _(Xe,pt),pt},X=B=>{let ne=C.get(B);if(ne)return ne;let ae={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:g(),toolCall:{id:B,status:"pending"}};return C.set(B,ae),c(ae),ae},U=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let ne=Number(B);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let ae=Date.parse(B);if(!Number.isNaN(ae))return ae}return Date.now()},Se=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},N=new Map,re=new Map,D=null,Z=new Map,ve=(pe=this.config.iterationDisplay)!=null?pe:"separate";for(;;){let{done:B,value:ne}=await o.read();if(B)break;i+=s.decode(ne,{stream:!0});let ae=i.split(`
|
|
1
|
+
"use strict";var ya=Object.create;var js=Object.defineProperty;var ba=Object.getOwnPropertyDescriptor;var xa=Object.getOwnPropertyNames;var Ca=Object.getPrototypeOf,Sa=Object.prototype.hasOwnProperty;var Aa=(t,n)=>{for(var r in n)js(t,r,{get:n[r],enumerable:!0})},Si=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of xa(n))!Sa.call(t,o)&&o!==r&&js(t,o,{get:()=>n[o],enumerable:!(e=ba(n,o))||e.enumerable});return t};var Ea=(t,n,r)=>(r=t!=null?ya(Ca(t)):{},Si(n||!t||!t.__esModule?js(r,"default",{value:t,enumerable:!0}):r,t)),Ta=t=>Si(js({},"__esModule",{value:!0}),t);var Pl={};Aa(Pl,{AgentWidgetClient:()=>Cn,AgentWidgetSession:()=>$n,AttachmentManager:()=>An,DEFAULT_DARK_THEME:()=>Fr,DEFAULT_LIGHT_THEME:()=>$r,DEFAULT_WIDGET_CONFIG:()=>tt,VERSION:()=>Ln,attachHeaderToContainer:()=>En,buildComposer:()=>On,buildDefaultHeader:()=>Ar,buildExpandedHeader:()=>Tr,buildHeader:()=>an,buildHeaderWithLayout:()=>Fn,buildMinimalHeader:()=>Er,componentRegistry:()=>qn,createActionManager:()=>Ms,createAgentExperience:()=>cr,createBubbleWithLayout:()=>Gi,createCSATFeedback:()=>lr,createComponentMiddleware:()=>ia,createComponentStreamParser:()=>rr,createDirectivePostprocessor:()=>Li,createFlexibleJsonStreamParser:()=>Pi,createImagePart:()=>Oi,createJsonStreamParser:()=>Ys,createLocalStorageAdapter:()=>sr,createMarkdownProcessor:()=>ys,createMarkdownProcessorFromConfig:()=>bs,createMessageActions:()=>Ir,createNPSFeedback:()=>dr,createPlainTextParser:()=>Js,createRegexJsonParser:()=>Ks,createStandardBubble:()=>Nn,createTextPart:()=>Gs,createTypingIndicator:()=>Tn,createXmlParser:()=>Vs,default:()=>Wl,defaultActionHandlers:()=>Mn,defaultJsonActionParser:()=>Ts,directivePostprocessor:()=>Ii,escapeHtml:()=>qs,extractComponentDirectiveFromMessage:()=>ar,fileToImagePart:()=>Ni,generateAssistantMessageId:()=>Sn,generateCodeSnippet:()=>fa,generateMessageId:()=>Hi,generateUserMessageId:()=>Rn,getDisplayText:()=>Ri,getHeaderLayout:()=>Mr,getImageParts:()=>Fi,hasComponentDirective:()=>ir,hasImages:()=>$i,headerLayouts:()=>tr,initAgentWidget:()=>jr,isComponentDirectiveType:()=>oa,markdownPostprocessor:()=>br,mergeWithDefaults:()=>nr,normalizeContent:()=>Bi,pluginRegistry:()=>Es,renderComponentDirective:()=>or,renderLoadingIndicatorWithFallback:()=>Lr,validateImageFile:()=>Di});module.exports=Ta(Pl);var Ei=require("marked"),Ma=t=>{if(t)return t},ys=t=>{var o,s;let n=t==null?void 0:t.markedOptions,r=new Ei.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}),e=Ma(t==null?void 0:t.renderer);return e&&r.use({renderer:e}),i=>r.parse(i)},bs=t=>t?ys({markedOptions:t.options,renderer:t.renderer}):ys(),La=ys(),br=t=>La(t),qs=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Ti=t=>t.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Ai=t=>`%%FORM_PLACEHOLDER_${t}%%`,Mi=(t,n)=>{let r=t;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Ai(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=Ai(n.length);return n.push({token:s,type:o}),s}),r},Li=t=>{let n=bs(t);return r=>{let e=[],o=Mi(r,e),s=n(o);return e.forEach(({token:i,type:a})=>{let u=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${Ti(a)}"></div>`;s=s.replace(u,v)}),s}},Ii=t=>{let n=[],r=Mi(t,n),e=br(r);return n.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="tvw-form-directive" data-tv-form="${Ti(s)}"></div>`;e=e.replace(i,u)}),e};var on=require("partial-json"),Us=t=>t.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),xs=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Ia=t=>{var i,a;let n=(i=t.completedAt)!=null?i:Date.now(),r=(a=t.startedAt)!=null?a:n,o=(t.durationMs!==void 0?t.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`},ki=t=>t.status==="complete"?Ia(t):t.status==="pending"?"Waiting":"",ka=t=>{var o,s,i;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((i=(s=t.startedAt)!=null?s:t.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 Wi=t=>t.status==="complete"?ka(t):"Using tool...",Wa=()=>{let t=null,n=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
3
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=e.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>t,processChunk:async e=>{if(e.length<=n)return t!==null?{text:t,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(t=s),n=e.length,t!==null?{text:t,raw:e}:null},close:async()=>{}}},zs=t=>{try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Js=()=>{let t={processChunk:n=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Ks=()=>{var n;let t=Wa();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(n=t.close)==null?void 0:n.bind(t)}},Ys=()=>{let t=null,n=0;return{getExtractedText:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t!==null||t===""?{text:t||"",raw:r}:null;try{let o=(0,on.parse)(r,on.STR|on.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?Us(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=Us(o.text)))}catch{}return n=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Pi=t=>{let n=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Us(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Us(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,on.parse)(s,on.STR|on.OBJ),u=o(a);u!==null&&(n=u)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Vs=()=>{let t=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let e=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(t=e[1],{text:t,raw:n}):null},getExtractedText:()=>t}};var Pa="https://api.runtype.com/v1/dispatch",xr="https://api.runtype.com",Cr=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Ha(t){switch(t){case"json":return Ys;case"regex-json":return Ks;case"xml":return Vs;case"plain":default:return Js}}var Cn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=n.apiUrl)!=null?r:Pa,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(e=n.streamParser)!=null?e:Ha(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var e;let r=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xr;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,(r=(n=this.config).onSessionInit)==null||r.call(n,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let a=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):e.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await e.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xr}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"nps",rating:n,comment:r})}async dispatch(n,r){return this.isAgentMode()?this.dispatchAgent(n,r):this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let w=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:w}),w}let c=await this.buildPayload(n.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,d={sessionId:u.sessionId,messages:n.messages.filter(Cr).map(w=>{var S,x,E;return{id:w.id,role:w.role,content:(E=(x=(S=w.contentParts)!=null?S:w.llmContent)!=null?x:w.rawContent)!=null?E:w.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:e.signal});if(!f.ok){let w=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let x=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:x}),x}if(f.status===429){let x=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:x}),x}let S=new Error(w.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!f.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(f.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&r({type:"error",error:c}),c}}async dispatchProxy(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(n,r,e){r({type:"status",status:"connected"});try{await this.streamResponse(n,r,e)}finally{r({type:"status",status:"idle"})}}async resolveApproval(n,r){var i;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xr}/v1/agents/${n.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:r,streamResponse:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(Cr).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),e={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}return e}async buildPayload(n){let e={messages:n.slice().filter(Cr).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async handleCustomSSEEvent(n,r,e,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(e.current)return e.current;let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return e.current=u,o(u),u};if(i.text!==void 0){let u=a();u.content+=i.text,o(u)}return i.done&&(e.current&&(e.current.streaming=!1,o(e.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,e){var fe,ze,dt,Mt,Nt,$e,Se,se,he,Fe,Xe,Et,pe,G,pt,gt,vt,Dt,yt,Q,We,bt,xt,te,Oe,Ct,Wt,Lt,j,et,Ie,K,O,we,de,re,Me,Ne,J,le,Be,Je,ot,In,it,Kt,Jn,dn,Yt,$,cn,Qt,mn,Kn,Zt,en,kn,Wn,Ls,Is,ks,Yn,Pn,Ke,Vn,Xn,tn,Ws,Ps,Gn,fn,nn,Hs,Bs,Rs,hr,hn,wn,nt,Hn,Qn,Zn,es,ts,Rt,_t,sn,Vt,ns,vn,Ut,$s,Bn,Fs,Os,rn,Ge,Qe,un,ss,rs,wr,Pt,vr,$t,os,is,as,ls,ds,cs,us,ps,gs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),u=0,c=()=>a+u++,v=D=>{let ke=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,_e=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,at=D.tools?D.tools.map(mt=>({...mt,chunks:mt.chunks?[...mt.chunks]:void 0})):void 0;return{...D,reasoning:ke,toolCall:_e,tools:at}},d=D=>{r({type:"message",message:v(D)})},f=null,w={current:null},S=new Map,x=new Map,E={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},W=D=>{if(D==null)return null;try{return String(D)}catch{return null}},V=D=>{var ke,_e,at,mt,Tt;return W((Tt=(mt=(at=(_e=(ke=D.stepId)!=null?ke:D.step_id)!=null?_e:D.step)!=null?at:D.parentId)!=null?mt:D.flowStepId)!=null?Tt:D.flow_step_id)},b=D=>{var ke,_e,at,mt,Tt,st,m;return W((m=(st=(Tt=(mt=(at=(_e=(ke=D.callId)!=null?ke:D.call_id)!=null?_e:D.requestId)!=null?at:D.request_id)!=null?mt:D.toolCallId)!=null?Tt:D.tool_call_id)!=null?st:D.stepId)!=null?m:D.step_id)},N=()=>f||(f={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f),M=(D,ke)=>{E.lastId=ke,D&&E.byStep.set(D,ke)},R=(D,ke)=>{var Tt;let _e=(Tt=D.reasoningId)!=null?Tt:D.id,at=V(D);if(_e){let st=String(_e);return M(at,st),st}if(at){let st=E.byStep.get(at);if(st)return E.lastId=st,st}if(E.lastId&&!ke)return E.lastId;if(!ke)return null;let mt=`reason-${c()}`;return M(at,mt),mt},ne=D=>{let ke=S.get(D);if(ke)return ke;let _e={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:D,status:"streaming",chunks:[]}};return S.set(D,_e),d(_e),_e},Y=(D,ke)=>{C.lastId=ke,D&&C.byCall.set(D,ke)},_=(D,ke)=>{var Tt;let _e=(Tt=D.toolId)!=null?Tt:D.id,at=b(D);if(_e){let st=String(_e);return Y(at,st),st}if(at){let st=C.byCall.get(at);if(st)return C.lastId=st,st}if(C.lastId&&!ke)return C.lastId;if(!ke)return null;let mt=`tool-${c()}`;return Y(at,mt),mt},q=D=>{let ke=x.get(D);if(ke)return ke;let _e={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:D,status:"pending"}};return x.set(D,_e),d(_e),_e},U=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let ke=Number(D);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let _e=Date.parse(D);if(!Number.isNaN(_e))return _e}return Date.now()},ue=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},B=new Map,Z=new Map,P=null,z=new Map,Ce=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(;;){let{done:D,value:ke}=await o.read();if(D)break;i+=s.decode(ke,{stream:!0});let _e=i.split(`
|
|
5
5
|
|
|
6
|
-
`);i=(
|
|
7
|
-
`),Et="message",at="";for(let P of pt)P.startsWith("event:")?Et=P.replace("event:","").trim():P.startsWith("data:")&&(at+=P.replace("data:","").trim());if(!at)continue;let m;try{m=JSON.parse(at)}catch(P){r({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let _e=Et!=="message"?Et:(it=m.type)!=null?it:"message";if((Tt=this.onSSEEvent)==null||Tt.call(this,_e,m),this.parseSSEEvent){f.current=h;let P=await this.handleCustomSSEEvent(m,r,f,c,g);if(f.current&&!h&&(h=f.current),P)continue}if(_e==="reason_start"){let P=($t=H(m,!0))!=null?$t:`reason-${g()}`,v=oe(P);v.reasoning=(Fe=v.reasoning)!=null?Fe:{id:P,status:"streaming",chunks:[]},v.reasoning.startedAt=(ee=v.reasoning.startedAt)!=null?ee:U((Ae=m.startedAt)!=null?Ae:m.timestamp),v.reasoning.completedAt=void 0,v.reasoning.durationMs=void 0,v.streaming=!0,v.reasoning.status="streaming",c(v)}else if(_e==="reason_delta"||_e==="reason_chunk"){let P=($e=(ge=H(m,!1))!=null?ge:H(m,!0))!=null?$e:`reason-${g()}`,v=oe(P);v.reasoning=(Qe=v.reasoning)!=null?Qe:{id:P,status:"streaming",chunks:[]},v.reasoning.startedAt=(me=v.reasoning.startedAt)!=null?me:U((At=m.startedAt)!=null?At:m.timestamp);let T=(ut=(ct=(J=m.reasoningText)!=null?J:m.text)!=null?ct:m.delta)!=null?ut:"";if(T&&m.hidden!==!0&&v.reasoning.chunks.push(String(T)),v.reasoning.status=m.done?"complete":"streaming",m.done){v.reasoning.completedAt=U((ft=m.completedAt)!=null?ft:m.timestamp);let se=(Ot=v.reasoning.startedAt)!=null?Ot:Date.now();v.reasoning.durationMs=Math.max(0,((wt=v.reasoning.completedAt)!=null?wt:Date.now())-se)}v.streaming=v.reasoning.status!=="complete",c(v)}else if(_e==="reason_complete"){let P=(Ie=(Y=H(m,!1))!=null?Y:H(m,!0))!=null?Ie:`reason-${g()}`,v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U((vt=m.completedAt)!=null?vt:m.timestamp);let se=(yt=v.reasoning.startedAt)!=null?yt:Date.now();v.reasoning.durationMs=Math.max(0,((Q=v.reasoning.completedAt)!=null?Q:Date.now())-se),v.streaming=!1,c(v)}let T=V(m);T&&E.byStep.delete(T)}else if(_e==="tool_start"){let P=(Oe=le(m,!0))!=null?Oe:`tool-${g()}`,v=X(P),T=(bt=v.toolCall)!=null?bt:{id:P,status:"pending"};T.name=(Wt=m.toolName)!=null?Wt:T.name,T.status="running",m.args!==void 0?T.args=m.args:m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=(j=T.startedAt)!=null?j:U((Mt=m.startedAt)!=null?Mt:m.timestamp),T.completedAt=void 0,T.durationMs=void 0,v.toolCall=T,v.streaming=!0;let se=m.agentContext;(se||m.executionId)&&(v.agentMetadata={executionId:(Ze=se==null?void 0:se.executionId)!=null?Ze:m.executionId,iteration:(We=se==null?void 0:se.iteration)!=null?We:m.iteration}),c(v)}else if(_e==="tool_chunk"||_e==="tool_delta"){let P=(R=(z=le(m,!1))!=null?z:le(m,!0))!=null?R:`tool-${g()}`,v=X(P),T=(he=v.toolCall)!=null?he:{id:P,status:"running"};T.startedAt=(te=T.startedAt)!=null?te:U((ue=m.startedAt)!=null?ue:m.timestamp);let se=(q=(Ne=(Le=m.text)!=null?Le:m.delta)!=null?Ne:m.message)!=null?q:"";se&&(T.chunks=(de=T.chunks)!=null?de:[],T.chunks.push(String(se))),T.status="running",v.toolCall=T,v.streaming=!0;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(st=v.agentMetadata)!=null?st:{executionId:(Be=Ee==null?void 0:Ee.executionId)!=null?Be:m.executionId,iteration:(Je=Ee==null?void 0:Ee.iteration)!=null?Je:m.iteration}),c(v)}else if(_e==="tool_complete"){let P=(rt=(Tn=le(m,!1))!=null?Tn:le(m,!0))!=null?rt:`tool-${g()}`,v=X(P),T=(Jt=v.toolCall)!=null?Jt:{id:P,status:"running"};T.status="complete",m.result!==void 0&&(T.result=m.result),typeof m.duration=="number"&&(T.duration=m.duration),T.completedAt=U((qn=m.completedAt)!=null?qn:m.timestamp);let se=(an=m.duration)!=null?an:m.executionTime;if(typeof se=="number")T.durationMs=se;else{let Lt=(Kt=T.startedAt)!=null?Kt:Date.now();T.durationMs=Math.max(0,((F=T.completedAt)!=null?F:Date.now())-Lt)}v.toolCall=T,v.streaming=!1;let Ee=m.agentContext;(Ee||m.executionId)&&(v.agentMetadata=(un=v.agentMetadata)!=null?un:{executionId:(ln=Ee==null?void 0:Ee.executionId)!=null?ln:m.executionId,iteration:(Gt=Ee==null?void 0:Ee.iteration)!=null?Gt:m.iteration}),c(v);let Ye=y(m);Ye&&S.byCall.delete(Ye)}else if(_e==="step_chunk"||_e==="step_delta"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=O(),se=(Mn=(Zt=(Qt=(zn=m.text)!=null?zn:m.delta)!=null?Qt:m.content)!=null?Zt:m.chunk)!=null?Mn:"";if(se){let Ye=((Ln=re.get(T.id))!=null?Ln:"")+se;T.rawContent=Ye,N.has(T.id)||N.set(T.id,this.createStreamParser());let Lt=N.get(T.id),nt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(nt&&re.set(T.id,Ye),Lt.__isPlainTextParser===!0){T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T);continue}let gt=Lt.processChunk(Ye);if(gt instanceof Promise)gt.then(De=>{var lt;let qe=typeof De=="string"?De:(lt=De==null?void 0:De.text)!=null?lt:null;if(qe!==null&&qe.trim()!==""){let ze=h;ze&&ze.id===T.id&&(ze.content=qe,c(ze))}else if(!nt&&!Ye.trim().startsWith("<")){let ze=h;ze&&ze.id===T.id&&(ze.content+=se,re.delete(ze.id),N.delete(ze.id),ze.rawContent=void 0,c(ze))}}).catch(()=>{T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T)});else{let De=typeof gt=="string"?gt:(ps=gt==null?void 0:gt.text)!=null?ps:null;De!==null&&De.trim()!==""?(T.content=De,c(T)):!nt&&!Ye.trim().startsWith("<")&&(T.content+=se,re.delete(T.id),N.delete(T.id),T.rawContent=void 0,c(T))}}if(m.isComplete){let Ee=(ms=(gs=m.result)==null?void 0:gs.response)!=null?ms:T.content;if(Ee){let Ye=re.get(T.id),Lt=Ye!=null?Ye:Se(Ee);T.rawContent=Lt;let nt=N.get(T.id),Ct=null,gt=!1;if(nt&&(Ct=nt.getExtractedText(),Ct===null&&(Ct=ks(Lt)),Ct===null)){let De=nt.processChunk(Lt);De instanceof Promise?(gt=!0,De.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===T.id&&(xt.content=lt,xt.streaming=!1,N.delete(xt.id),re.delete(xt.id),c(xt))}})):Ct=typeof De=="string"?De:(Un=De==null?void 0:De.text)!=null?Un:null}if(!gt){Ct!==null&&Ct.trim()!==""?T.content=Ct:re.has(T.id)||(T.content=Se(Ee));let De=N.get(T.id);if(De){let qe=(kn=De.close)==null?void 0:kn.call(De);qe instanceof Promise&&qe.catch(()=>{}),N.delete(T.id)}re.delete(T.id),T.streaming=!1,c(T)}}}}else if(_e==="step_complete"){let P=m.stepType,v=m.executionType;if(P==="tool"||v==="context")continue;let T=(Ke=m.result)==null?void 0:Ke.response,se=O();if(T!=null){let Ee=N.get(se.id),Ye=!1,Lt=!1;if(Ee){let nt=Ee.getExtractedText(),Ct=re.get(se.id),gt=Ct!=null?Ct:Se(T);if(se.rawContent=gt,nt!==null&&nt.trim()!=="")se.content=nt,Ye=!0;else{let De=ks(gt);if(De!==null)se.content=De,Ye=!0;else{let qe=Ee.processChunk(gt);if(qe instanceof Promise)Lt=!0,qe.then(lt=>{var xt;let ze=typeof lt=="string"?lt:(xt=lt==null?void 0:lt.text)!=null?xt:null;if(ze!==null&&ze.trim()!==""){let Rt=h;Rt&&Rt.id===se.id&&(Rt.content=ze,Rt.streaming=!1,N.delete(Rt.id),re.delete(Rt.id),c(Rt))}else{let Rt=Ee.getExtractedText(),_t=h;_t&&_t.id===se.id&&(Rt!==null&&Rt.trim()!==""?_t.content=Rt:re.has(_t.id)||(_t.content=Se(T)),_t.streaming=!1,N.delete(_t.id),re.delete(_t.id),c(_t))}});else{let lt=typeof qe=="string"?qe:(Jn=qe==null?void 0:qe.text)!=null?Jn:null;if(lt!==null&<.trim()!=="")se.content=lt,Ye=!0;else{let ze=Ee.getExtractedText();ze!==null&&ze.trim()!==""&&(se.content=ze,Ye=!0)}}}}}if(!Lt){if(!se.rawContent){let nt=re.get(se.id);se.rawContent=nt!=null?nt:Se(T)}if(!Ye&&!re.has(se.id)&&(se.content=Se(T)),Ee){let nt=(Kn=Ee.close)==null?void 0:Kn.call(Ee);nt instanceof Promise&&nt.catch(()=>{})}N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}}else N.delete(se.id),re.delete(se.id),se.streaming=!1,c(se)}else if(_e==="flow_complete"){let P=(en=m.result)==null?void 0:en.response;if(P!=null){let v=O(),T=re.get(v.id),se=T!=null?T:Se(P);v.rawContent=se;let Ee=Se(P),Ye=N.get(v.id);if(Ye){let Ct=ks(se);if(Ct!==null)Ee=Ct;else{let gt=Ye.processChunk(se);gt instanceof Promise&>.then(qe=>{var ze;let lt=typeof qe=="string"?qe:(ze=qe==null?void 0:qe.text)!=null?ze:null;if(lt!==null){let xt=h;xt&&xt.id===v.id&&(xt.content=lt,xt.streaming=!1,c(xt))}});let De=Ye.getExtractedText();De!==null&&(Ee=De)}}N.delete(v.id),re.delete(v.id);let Lt=Ee!==v.content,nt=v.streaming!==!1;Lt&&(v.content=Ee),v.streaming=!1,(Lt||nt)&&c(v)}else if(h!==null){let v=h;N.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,c(v))}r({type:"status",status:"idle"})}else if(_e==="agent_start")D={executionId:m.executionId,agentId:(hs=m.agentId)!=null?hs:"virtual",agentName:(fs=m.agentName)!=null?fs:"",status:"running",currentIteration:0,maxIterations:(Yn=m.maxIterations)!=null?Yn:1,startedAt:U(m.startedAt)};else if(_e==="agent_iteration_start"){if(D&&(D.currentIteration=m.iteration),ve==="separate"&&m.iteration>1){let P=h;P&&(P.streaming=!1,c(P),Z.set(m.iteration-1,P),h=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(m.contentType==="text"){let P=O();P.content+=(pn=m.delta)!=null?pn:"",P.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:D==null?void 0:D.agentName},c(P)}else if(m.contentType==="thinking"){let P=(tn=m.turnId)!=null?tn:`agent-think-${m.iteration}`,v=oe(P);v.reasoning=(ws=v.reasoning)!=null?ws:{id:P,status:"streaming",chunks:[]},v.reasoning.chunks.push((vs=m.delta)!=null?vs:""),v.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},c(v)}else if(m.contentType==="tool_input"){let P=(ys=m.toolCallId)!=null?ys:S.lastId;if(P){let v=C.get(P);v!=null&&v.toolCall&&(v.toolCall.chunks=(Zs=v.toolCall.chunks)!=null?Zs:[],v.toolCall.chunks.push((gn=m.delta)!=null?gn:""),c(v))}}}else if(_e==="agent_turn_complete"){let P=m.turnId;if(P){let v=x.get(P);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=U(m.completedAt);let T=(mn=v.reasoning.startedAt)!=null?mn:Date.now();v.reasoning.durationMs=Math.max(0,((tt=v.reasoning.completedAt)!=null?tt:Date.now())-T),v.streaming=!1,c(v)}}}else if(_e==="agent_tool_start"){let P=(Wn=m.toolCallId)!=null?Wn:`agent-tool-${g()}`;_(y(m),P);let v=X(P),T=(Vn=v.toolCall)!=null?Vn:{id:P,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};T.name=(Xn=m.toolName)!=null?Xn:T.name,T.status="running",m.parameters!==void 0&&(T.args=m.parameters),T.startedAt=U((Gn=m.startedAt)!=null?Gn:m.timestamp),v.toolCall=T,v.streaming=!0,v.agentMetadata={executionId:m.executionId,iteration:m.iteration},c(v)}else if(_e==="agent_tool_delta"){let P=(Ht=m.toolCallId)!=null?Ht:S.lastId;if(P){let v=(Nt=C.get(P))!=null?Nt:X(P);v.toolCall&&(v.toolCall.chunks=(nn=v.toolCall.chunks)!=null?nn:[],v.toolCall.chunks.push((Yt=m.delta)!=null?Yt:""),v.toolCall.status="running",v.streaming=!0,c(v))}}else if(_e==="agent_tool_complete"){let P=(Qn=m.toolCallId)!=null?Qn:S.lastId;if(P){let v=(hn=C.get(P))!=null?hn:X(P);if(v.toolCall){v.toolCall.status="complete",m.result!==void 0&&(v.toolCall.result=m.result),typeof m.executionTime=="number"&&(v.toolCall.durationMs=m.executionTime),v.toolCall.completedAt=U((qt=m.completedAt)!=null?qt:m.timestamp),v.streaming=!1,c(v);let T=y(m);T&&S.byCall.delete(T)}}}else if(_e!=="agent_iteration_complete")if(_e==="agent_reflection"||_e==="agent_reflect"){let P=`agent-reflection-${m.executionId}-${m.iteration}`,v={id:P,role:"assistant",content:(bs=m.reflection)!=null?bs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:g(),reasoning:{id:P,status:"complete",chunks:[(In=m.reflection)!=null?In:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};c(v)}else if(_e==="agent_complete"){D&&(D.status=m.success?"complete":"error",D.completedAt=U(m.completedAt),D.stopReason=m.stopReason);let P=h;P&&(P.streaming=!1,c(P)),r({type:"status",status:"idle"})}else if(_e==="agent_error"){let P=typeof m.error=="string"?m.error:(xs=(Cs=m.error)==null?void 0:Cs.message)!=null?xs:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",P):r({type:"error",error:new Error(P)})}else _e==="agent_ping"||_e==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}};function Wi(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Pn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function bn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Hn=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,t,o,s,i,a,d;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(t=n.message.agentMetadata.agentName)!=null?t:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new yn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(r=(n=this.callbacks).onError)==null||r.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new yn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:t,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:g=!1}=n,c={id:i!=null?i:r==="user"?Pn():r==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:g,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(c),c}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let t of n){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:g,sequence:w,streaming:c=!1}=t,f={id:d!=null?d:o==="user"?Pn():o==="assistant"?bn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:g!=null?g:new Date().toISOString(),sequence:w!=null?w:this.nextSequence(),streaming:c,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(f)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var g,w,c,h,f;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(g=this.abortController)==null||g.abort();let o=Pn(),s=bn(),i={id:o,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(c=(w=this.callbacks).onError)==null||c.call(w,x):(f=(h=this.callbacks).onError)==null||f.call(h,new Error(String(x))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=bn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(g){let w={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(w),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,g):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(g)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,t)=>{var d,g;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(g=t.sequence)!=null?g:0;return i!==a?i-a:r.id.localeCompare(t.id)})}};var p=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};var Ia=xa(require("lucide"),1),ie=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ia[o];return s?Pa(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Pa(e,n,r,t){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([g,w])=>{g!=="stroke"&&d.setAttribute(g,String(w))}),o.appendChild(d)}}}),o}function Ii(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pi(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Hi(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Bi(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Bs(e){return{type:"text",text:e}}function Ri(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Fi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function $i(e,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Oi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ha=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],cn=[...Oi,...Ha];function Ba(e){return Oi.includes(e)||e.startsWith("image/")}function Rs(e){return Ba(e.type)}async function Ni(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;Rs(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function Di(e,n=cn,r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Ra(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function ji(e,n){let r=Ra(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var Fs={allowedTypes:cn,maxFileSize:10*1024*1024,maxFiles:4};function Fa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $a(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Cn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,t,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Fs.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Fs.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Fs.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Fs.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,o,s,i,a,d,g;if(!n||n.length===0)return;let r=Array.from(n);for(let w of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,w,"count");continue}let c=Di(w,this.config.allowedTypes,this.config.maxFileSize);if(!c.valid){let h=(s=c.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,w,h);continue}try{let h=await Ni(w),f=Rs(w)?URL.createObjectURL(w):null,x={id:Fa(),file:w,previewUrl:f,contentPart:h};this.attachments.push(x),this.renderPreview(x)}catch(h){console.error("[AttachmentManager] Failed to process file:",h)}}this.updatePreviewsVisibility(),(g=(d=this.config).onAttachmentsChange)==null||g.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(d=>d.id===n);if(r===-1)return;let t=this.attachments[r];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=Rs(n.file),t=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",r&&n.previewUrl){let i=p("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=p("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=$a(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let g=p("span");g.textContent=ji(n.file.type,n.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--cw-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",i.appendChild(g),t.appendChild(i)}let o=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(o),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:r})}};var rr=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Oa=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",r=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||rr()==="dark"?t:r},_i=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(rr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(rr());r.addEventListener?(r.addEventListener("change",t),n.push(()=>r.removeEventListener("change",t))):r.addListener&&(r.addListener(t),n.push(()=>r.removeListener(t)))}return()=>{n.forEach(r=>r())}},$s=(e,n)=>{let r=Oa(n);Object.entries(r).forEach(([t,o])=>{if(o==null||o==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(o))})};var qi=require("idiomorph"),zi=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;qi.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&t&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ut={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var is=(e,n)=>{let r=p("button");r.type="button",r.innerHTML=`
|
|
6
|
+
`);i=(ze=_e.pop())!=null?ze:"";for(let at of _e){let mt=at.split(`
|
|
7
|
+
`),Tt="message",st="";for(let H of mt)H.startsWith("event:")?Tt=H.replace("event:","").trim():H.startsWith("data:")&&(st+=H.replace("data:","").trim());if(!st)continue;let m;try{m=JSON.parse(st)}catch(H){r({type:"error",error:H instanceof Error?H:new Error("Failed to parse chat stream payload")});continue}let Pe=Tt!=="message"?Tt:(dt=m.type)!=null?dt:"message";if((Mt=this.onSSEEvent)==null||Mt.call(this,Pe,m),this.parseSSEEvent){w.current=f;let H=await this.handleCustomSSEEvent(m,r,w,d,c);if(w.current&&!f&&(f=w.current),H)continue}if(Pe==="reason_start"){let H=(Nt=R(m,!0))!=null?Nt:`reason-${c()}`,y=ne(H);y.reasoning=($e=y.reasoning)!=null?$e:{id:H,status:"streaming",chunks:[]},y.reasoning.startedAt=(se=y.reasoning.startedAt)!=null?se:U((Se=m.startedAt)!=null?Se:m.timestamp),y.reasoning.completedAt=void 0,y.reasoning.durationMs=void 0,y.streaming=!0,y.reasoning.status="streaming",d(y)}else if(Pe==="reason_delta"||Pe==="reason_chunk"){let H=(Fe=(he=R(m,!1))!=null?he:R(m,!0))!=null?Fe:`reason-${c()}`,y=ne(H);y.reasoning=(Xe=y.reasoning)!=null?Xe:{id:H,status:"streaming",chunks:[]},y.reasoning.startedAt=(pe=y.reasoning.startedAt)!=null?pe:U((Et=m.startedAt)!=null?Et:m.timestamp);let L=(gt=(pt=(G=m.reasoningText)!=null?G:m.text)!=null?pt:m.delta)!=null?gt:"";if(L&&m.hidden!==!0&&y.reasoning.chunks.push(String(L)),y.reasoning.status=m.done?"complete":"streaming",m.done){y.reasoning.completedAt=U((vt=m.completedAt)!=null?vt:m.timestamp);let ie=(Dt=y.reasoning.startedAt)!=null?Dt:Date.now();y.reasoning.durationMs=Math.max(0,((yt=y.reasoning.completedAt)!=null?yt:Date.now())-ie)}y.streaming=y.reasoning.status!=="complete",d(y)}else if(Pe==="reason_complete"){let H=(We=(Q=R(m,!1))!=null?Q:R(m,!0))!=null?We:`reason-${c()}`,y=S.get(H);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=U((bt=m.completedAt)!=null?bt:m.timestamp);let ie=(xt=y.reasoning.startedAt)!=null?xt:Date.now();y.reasoning.durationMs=Math.max(0,((te=y.reasoning.completedAt)!=null?te:Date.now())-ie),y.streaming=!1,d(y)}let L=V(m);L&&E.byStep.delete(L)}else if(Pe==="tool_start"){let H=(Oe=_(m,!0))!=null?Oe:`tool-${c()}`,y=q(H),L=(Ct=y.toolCall)!=null?Ct:{id:H,status:"pending"};L.name=(Wt=m.toolName)!=null?Wt:L.name,L.status="running",m.args!==void 0?L.args=m.args:m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=(j=L.startedAt)!=null?j:U((Lt=m.startedAt)!=null?Lt:m.timestamp),L.completedAt=void 0,L.durationMs=void 0,y.toolCall=L,y.streaming=!0;let ie=m.agentContext;(ie||m.executionId)&&(y.agentMetadata={executionId:(et=ie==null?void 0:ie.executionId)!=null?et:m.executionId,iteration:(Ie=ie==null?void 0:ie.iteration)!=null?Ie:m.iteration}),d(y)}else if(Pe==="tool_chunk"||Pe==="tool_delta"){let H=(O=(K=_(m,!1))!=null?K:_(m,!0))!=null?O:`tool-${c()}`,y=q(H),L=(we=y.toolCall)!=null?we:{id:H,status:"running"};L.startedAt=(re=L.startedAt)!=null?re:U((de=m.startedAt)!=null?de:m.timestamp);let ie=(J=(Ne=(Me=m.text)!=null?Me:m.delta)!=null?Ne:m.message)!=null?J:"";ie&&(L.chunks=(le=L.chunks)!=null?le:[],L.chunks.push(String(ie))),L.status="running",y.toolCall=L,y.streaming=!0;let Ae=m.agentContext;(Ae||m.executionId)&&(y.agentMetadata=(ot=y.agentMetadata)!=null?ot:{executionId:(Be=Ae==null?void 0:Ae.executionId)!=null?Be:m.executionId,iteration:(Je=Ae==null?void 0:Ae.iteration)!=null?Je:m.iteration}),d(y)}else if(Pe==="tool_complete"){let H=(it=(In=_(m,!1))!=null?In:_(m,!0))!=null?it:`tool-${c()}`,y=q(H),L=(Kt=y.toolCall)!=null?Kt:{id:H,status:"running"};L.status="complete",m.result!==void 0&&(L.result=m.result),typeof m.duration=="number"&&(L.duration=m.duration),L.completedAt=U((Jn=m.completedAt)!=null?Jn:m.timestamp);let ie=(dn=m.duration)!=null?dn:m.executionTime;if(typeof ie=="number")L.durationMs=ie;else{let It=(Yt=L.startedAt)!=null?Yt:Date.now();L.durationMs=Math.max(0,(($=L.completedAt)!=null?$:Date.now())-It)}y.toolCall=L,y.streaming=!1;let Ae=m.agentContext;(Ae||m.executionId)&&(y.agentMetadata=(mn=y.agentMetadata)!=null?mn:{executionId:(cn=Ae==null?void 0:Ae.executionId)!=null?cn:m.executionId,iteration:(Qt=Ae==null?void 0:Ae.iteration)!=null?Qt:m.iteration}),d(y);let Ye=b(m);Ye&&C.byCall.delete(Ye)}else if(Pe==="step_chunk"||Pe==="step_delta"){let H=m.stepType,y=m.executionType;if(H==="tool"||y==="context")continue;let L=N(),ie=(kn=(en=(Zt=(Kn=m.text)!=null?Kn:m.delta)!=null?Zt:m.content)!=null?en:m.chunk)!=null?kn:"";if(ie){let Ye=((Wn=Z.get(L.id))!=null?Wn:"")+ie;L.rawContent=Ye,B.has(L.id)||B.set(L.id,this.createStreamParser());let It=B.get(L.id),rt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(rt&&Z.set(L.id,Ye),It.__isPlainTextParser===!0){L.content+=ie,Z.delete(L.id),B.delete(L.id),L.rawContent=void 0,d(L);continue}let ft=It.processChunk(Ye);if(ft instanceof Promise)ft.then(De=>{var ct;let qe=typeof De=="string"?De:(ct=De==null?void 0:De.text)!=null?ct:null;if(qe!==null&&qe.trim()!==""){let Ue=f;Ue&&Ue.id===L.id&&(Ue.content=qe,d(Ue))}else if(!rt&&!Ye.trim().startsWith("<")){let Ue=f;Ue&&Ue.id===L.id&&(Ue.content+=ie,Z.delete(Ue.id),B.delete(Ue.id),Ue.rawContent=void 0,d(Ue))}}).catch(()=>{L.content+=ie,Z.delete(L.id),B.delete(L.id),L.rawContent=void 0,d(L)});else{let De=typeof ft=="string"?ft:(Ls=ft==null?void 0:ft.text)!=null?Ls:null;De!==null&&De.trim()!==""?(L.content=De,d(L)):!rt&&!Ye.trim().startsWith("<")&&(L.content+=ie,Z.delete(L.id),B.delete(L.id),L.rawContent=void 0,d(L))}}if(m.isComplete){let Ae=(ks=(Is=m.result)==null?void 0:Is.response)!=null?ks:L.content;if(Ae){let Ye=Z.get(L.id),It=Ye!=null?Ye:ue(Ae);L.rawContent=It;let rt=B.get(L.id),St=null,ft=!1;if(rt&&(St=rt.getExtractedText(),St===null&&(St=zs(It)),St===null)){let De=rt.processChunk(It);De instanceof Promise?(ft=!0,De.then(qe=>{var Ue;let ct=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(ct!==null){let l=f;l&&l.id===L.id&&(l.content=ct,l.streaming=!1,B.delete(l.id),Z.delete(l.id),d(l))}})):St=typeof De=="string"?De:(Yn=De==null?void 0:De.text)!=null?Yn:null}if(!ft){St!==null&&St.trim()!==""?L.content=St:Z.has(L.id)||(L.content=ue(Ae));let De=B.get(L.id);if(De){let qe=(Pn=De.close)==null?void 0:Pn.call(De);qe instanceof Promise&&qe.catch(()=>{}),B.delete(L.id)}Z.delete(L.id),L.streaming=!1,d(L)}}}}else if(Pe==="step_complete"){let H=m.stepType,y=m.executionType;if(H==="tool"||y==="context")continue;let L=(Ke=m.result)==null?void 0:Ke.response,ie=N();if(L!=null){let Ae=B.get(ie.id),Ye=!1,It=!1;if(Ae){let rt=Ae.getExtractedText(),St=Z.get(ie.id),ft=St!=null?St:ue(L);if(ie.rawContent=ft,rt!==null&&rt.trim()!=="")ie.content=rt,Ye=!0;else{let De=zs(ft);if(De!==null)ie.content=De,Ye=!0;else{let qe=Ae.processChunk(ft);if(qe instanceof Promise)It=!0,qe.then(ct=>{var l;let Ue=typeof ct=="string"?ct:(l=ct==null?void 0:ct.text)!=null?l:null;if(Ue!==null&&Ue.trim()!==""){let p=f;p&&p.id===ie.id&&(p.content=Ue,p.streaming=!1,B.delete(p.id),Z.delete(p.id),d(p))}else{let p=Ae.getExtractedText(),h=f;h&&h.id===ie.id&&(p!==null&&p.trim()!==""?h.content=p:Z.has(h.id)||(h.content=ue(L)),h.streaming=!1,B.delete(h.id),Z.delete(h.id),d(h))}});else{let ct=typeof qe=="string"?qe:(Vn=qe==null?void 0:qe.text)!=null?Vn:null;if(ct!==null&&ct.trim()!=="")ie.content=ct,Ye=!0;else{let Ue=Ae.getExtractedText();Ue!==null&&Ue.trim()!==""&&(ie.content=Ue,Ye=!0)}}}}}if(!It){if(!ie.rawContent){let rt=Z.get(ie.id);ie.rawContent=rt!=null?rt:ue(L)}if(!Ye&&!Z.has(ie.id)&&(ie.content=ue(L)),Ae){let rt=(Xn=Ae.close)==null?void 0:Xn.call(Ae);rt instanceof Promise&&rt.catch(()=>{})}B.delete(ie.id),Z.delete(ie.id),ie.streaming=!1,d(ie)}}else B.delete(ie.id),Z.delete(ie.id),ie.streaming=!1,d(ie)}else if(Pe==="flow_complete"){let H=(tn=m.result)==null?void 0:tn.response;if(H!=null){let y=N(),L=Z.get(y.id),ie=L!=null?L:ue(H);y.rawContent=ie;let Ae=ue(H),Ye=B.get(y.id);if(Ye){let St=zs(ie);if(St!==null)Ae=St;else{let ft=Ye.processChunk(ie);ft instanceof Promise&&ft.then(qe=>{var Ue;let ct=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(ct!==null){let l=f;l&&l.id===y.id&&(l.content=ct,l.streaming=!1,d(l))}});let De=Ye.getExtractedText();De!==null&&(Ae=De)}}B.delete(y.id),Z.delete(y.id);let It=Ae!==y.content,rt=y.streaming!==!1;It&&(y.content=Ae),y.streaming=!1,(It||rt)&&d(y)}else if(f!==null){let y=f;B.delete(y.id),Z.delete(y.id),y.streaming!==!1&&(y.streaming=!1,d(y))}r({type:"status",status:"idle"})}else if(Pe==="agent_start")P={executionId:m.executionId,agentId:(Ws=m.agentId)!=null?Ws:"virtual",agentName:(Ps=m.agentName)!=null?Ps:"",status:"running",currentIteration:0,maxIterations:(Gn=m.maxIterations)!=null?Gn:1,startedAt:U(m.startedAt)};else if(Pe==="agent_iteration_start"){if(P&&(P.currentIteration=m.iteration),Ce==="separate"&&m.iteration>1){let H=f;H&&(H.streaming=!1,d(H),z.set(m.iteration-1,H),f=null)}}else if(Pe!=="agent_turn_start"){if(Pe==="agent_turn_delta"){if(m.contentType==="text"){let H=N();H.content+=(fn=m.delta)!=null?fn:"",H.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:P==null?void 0:P.agentName},d(H)}else if(m.contentType==="thinking"){let H=(nn=m.turnId)!=null?nn:`agent-think-${m.iteration}`,y=ne(H);y.reasoning=(Hs=y.reasoning)!=null?Hs:{id:H,status:"streaming",chunks:[]},y.reasoning.chunks.push((Bs=m.delta)!=null?Bs:""),y.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},d(y)}else if(m.contentType==="tool_input"){let H=(Rs=m.toolCallId)!=null?Rs:C.lastId;if(H){let y=x.get(H);y!=null&&y.toolCall&&(y.toolCall.chunks=(hr=y.toolCall.chunks)!=null?hr:[],y.toolCall.chunks.push((hn=m.delta)!=null?hn:""),d(y))}}}else if(Pe==="agent_turn_complete"){let H=m.turnId;if(H){let y=S.get(H);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=U(m.completedAt);let L=(wn=y.reasoning.startedAt)!=null?wn:Date.now();y.reasoning.durationMs=Math.max(0,((nt=y.reasoning.completedAt)!=null?nt:Date.now())-L),y.streaming=!1,d(y)}}}else if(Pe==="agent_tool_start"){let H=(Hn=m.toolCallId)!=null?Hn:`agent-tool-${c()}`;Y(b(m),H);let y=q(H),L=(Qn=y.toolCall)!=null?Qn:{id:H,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};L.name=(Zn=m.toolName)!=null?Zn:L.name,L.status="running",m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=U((es=m.startedAt)!=null?es:m.timestamp),y.toolCall=L,y.streaming=!0,y.agentMetadata={executionId:m.executionId,iteration:m.iteration},d(y)}else if(Pe==="agent_tool_delta"){let H=(ts=m.toolCallId)!=null?ts:C.lastId;if(H){let y=(Rt=x.get(H))!=null?Rt:q(H);y.toolCall&&(y.toolCall.chunks=(_t=y.toolCall.chunks)!=null?_t:[],y.toolCall.chunks.push((sn=m.delta)!=null?sn:""),y.toolCall.status="running",y.streaming=!0,d(y))}}else if(Pe==="agent_tool_complete"){let H=(Vt=m.toolCallId)!=null?Vt:C.lastId;if(H){let y=(ns=x.get(H))!=null?ns:q(H);if(y.toolCall){y.toolCall.status="complete",m.result!==void 0&&(y.toolCall.result=m.result),typeof m.executionTime=="number"&&(y.toolCall.durationMs=m.executionTime),y.toolCall.completedAt=U((vn=m.completedAt)!=null?vn:m.timestamp),y.streaming=!1,d(y);let L=b(m);L&&C.byCall.delete(L)}}}else if(Pe!=="agent_iteration_complete"){if(Pe==="agent_reflection"||Pe==="agent_reflect"){let H=`agent-reflection-${m.executionId}-${m.iteration}`,y={id:H,role:"assistant",content:(Ut=m.reflection)!=null?Ut:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:H,status:"complete",chunks:[($s=m.reflection)!=null?$s:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};d(y)}else if(Pe==="agent_complete"){P&&(P.status=m.success?"complete":"error",P.completedAt=U(m.completedAt),P.stopReason=m.stopReason);let H=f;H&&(H.streaming=!1,d(H)),r({type:"status",status:"idle"})}else if(Pe==="agent_error"){let H=typeof m.error=="string"?m.error:(Fs=(Bn=m.error)==null?void 0:Bn.message)!=null?Fs:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",H):r({type:"error",error:new Error(H)})}else if(Pe!=="agent_ping")if(Pe==="agent_approval_start"){let H=(Os=m.approvalId)!=null?Os:`approval-${c()}`,y={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:(rn=P==null?void 0:P.agentId)!=null?rn:"virtual",executionId:(Qe=(Ge=m.executionId)!=null?Ge:P==null?void 0:P.executionId)!=null?Qe:"",toolName:(un=m.toolName)!=null?un:"",toolType:m.toolType,description:(rs=m.description)!=null?rs:`Execute ${(ss=m.toolName)!=null?ss:"tool"}`,parameters:m.parameters}};d(y)}else if(Pe==="step_await"&&m.awaitReason==="approval_required"){let H=(wr=m.approvalId)!=null?wr:`approval-${c()}`,y={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:(Pt=P==null?void 0:P.agentId)!=null?Pt:"virtual",executionId:($t=(vr=m.executionId)!=null?vr:P==null?void 0:P.executionId)!=null?$t:"",toolName:(os=m.toolName)!=null?os:"",toolType:m.toolType,description:(as=m.description)!=null?as:`Execute ${(is=m.toolName)!=null?is:"tool"}`,parameters:m.parameters}};d(y)}else if(Pe==="agent_approval_complete"){let H=m.approvalId;if(H){let L={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:(ls=m.decision)!=null?ls:"approved",agentId:(ds=P==null?void 0:P.agentId)!=null?ds:"virtual",executionId:(us=(cs=m.executionId)!=null?cs:P==null?void 0:P.executionId)!=null?us:"",toolName:(ps=m.toolName)!=null?ps:"",description:(gs=m.description)!=null?gs:"",resolvedAt:Date.now()}};d(L)}}else Pe==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}}};function Hi(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${t}_${n}`}function Rn(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${t}_${n}`}function Sn(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${t}_${n}`}var Xs="[Image]";function Bi(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Ri(t){return typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.text).join("")}function $i(t){return typeof t=="string"?!1:t.some(n=>n.type==="image")}function Fi(t){return typeof t=="string"?[]:t.filter(n=>n.type==="image")}function Gs(t){return{type:"text",text:t}}function Oi(t,n){return{type:"image",image:t,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Ni(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;n({type:"image",image:o,mimeType:t.type,alt:t.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(t)})}function Di(t,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var _i=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ba=["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"],gn=[..._i,...Ba];function Ra(t){return _i.includes(t)||t.startsWith("image/")}function Qs(t){return Ra(t.type)}async function ji(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;Qs(t)?n({type:"image",image:o,mimeType:t.type,alt:t.name}):n({type:"file",data:o,mimeType:t.type,filename:t.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(t)})}function qi(t,n=gn,r=10*1024*1024){return n.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${n.join(", ")}`}}function $a(t){let n=t.split(".");return n.length>1?n.pop().toLowerCase():""}function Ui(t,n){let r=$a(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||r||"FILE"}var $n=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,e,o,s,i,a,u;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(e=n.message.agentMetadata.agentName)!=null?e:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(u=(a=this.callbacks).onError)==null||u.call(a,n.error))};var e;this.messages=[...(e=n.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Cn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(n=this.callbacks).onError)==null||r.call(n,e instanceof Error?e:new Error(String(e))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new Cn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:u,streaming:c=!1}=n,d={id:i!=null?i:r==="user"?Rn():r==="assistant"?Sn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s}};return this.upsertMessage(d),d}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let e of n){let{role:o,content:s,llmContent:i,contentParts:a,id:u,createdAt:c,sequence:v,streaming:d=!1}=e,w={id:u!=null?u:o==="user"?Rn():o==="assistant"?Sn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:d,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(w)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var c,v,d,f,w;let e=n.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(c=this.abortController)==null||c.abort();let o=Rn(),s=Sn(),i={id:o,role:"user",content:e||Xs,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(S){let x=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));if(!x){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(S instanceof Error?(d=(v=this.callbacks).onError)==null||d.call(v,S):(w=(f=this.callbacks).onError)==null||w.call(f,new Error(String(S))))}}async continueConversation(){var o,s,i,a,u;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=Sn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let e=[...this.messages];try{await this.client.dispatch({messages:e,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(c){let v={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(v),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,c):(u=(a=this.callbacks).onError)==null||u.call(a,new Error(String(c)))}}async connectStream(n,r){var e,o,s;if(!this.streaming){(e=this.abortController)==null||e.abort(),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(s=(o=this.callbacks).onError)==null||s.call(o,i instanceof Error?i:new Error(String(i)))}}}async resolveApproval(n,r){var u,c,v;let e=`approval-${n.id}`,o={...n,status:r,resolvedAt:Date.now()},s={id:e,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let i=this.config.approval,a=i&&typeof i=="object"?i.onDecision:void 0;try{let d;if(a?d=await a({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},r):d=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},r),d){let f=null;if(d instanceof Response){if(!d.ok){let w=await d.json().catch(()=>null);throw new Error((u=w==null?void 0:w.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):r==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(v=(c=this.callbacks).onError)==null||v.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,e)=>{var u,c;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(u=r.sequence)!=null?u:0,a=(c=e.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(e.id)})}};var g=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Fa=Ea(require("lucide"),1),oe=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Fa[o];return s?Oa(s,n,r,e):(console.warn(`Lucide icon "${t}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${t}":`,o),null}};function Oa(t,n,r,e){if(!t||!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,v])=>{c!=="stroke"&&u.setAttribute(c,String(v))}),o.appendChild(u)}}}),o}var Zs={allowedTypes:gn,maxFileSize:10*1024*1024,maxFiles:4};function Na(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Da(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-json":"file"}var An=class t{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Zs.allowedTypes,maxFileSize:(e=n.maxFileSize)!=null?e:Zs.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Zs.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:Zs.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var r,e,o,s,i,a,u;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=qi(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let d=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,d);continue}try{let d=await ji(c),f=Qs(c)?URL.createObjectURL(c):null,w={id:Na(),file:c,previewUrl:f,contentPart:d};this.attachments.push(w),this.renderPreview(w)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(a=this.config).onAttachmentsChange)==null||u.call(a,this.getAttachments())}}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(u=>u.id===n);if(r===-1)return;let e=this.attachments[r];e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=Qs(n.file),e=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",n.id),e.style.width="48px",e.style.height="48px",r&&n.previewUrl){let i=g("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",e.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Da(n.file.type),u=oe(a,20,"var(--cw-muted, #6b7280)",1.5);u&&i.appendChild(u);let c=g("span");c.textContent=Ui(n.file.type,n.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--cw-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),e.appendChild(i)}let o=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=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)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new t({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:r})}};var Sr=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},_a=t=>{var s,i,a;let n=(s=t==null?void 0:t.colorScheme)!=null?s:"light",r=(i=t==null?void 0:t.theme)!=null?i:{},e=(a=t==null?void 0:t.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||Sr()==="dark"?e:r},zi=t=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Sr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>t(Sr());r.addEventListener?(r.addEventListener("change",e),n.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),n.push(()=>r.removeListener(e)))}return()=>{n.forEach(r=>r())}},er=(t,n)=>{let r=_a(n);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);t.style.setProperty(`--cw-${s}`,String(o))})};var Ji=require("idiomorph"),Ki=(t,n,r={})=>{let{preserveTypingAnimation:e=!0}=r;Ji.Idiomorph.morph(t,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&e&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Bt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Jt={"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 Cs=(t,n)=>{let r=g("button");r.type="button",r.innerHTML=`
|
|
8
8
|
<span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
9
9
|
<img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
|
|
@@ -12,16 +12,16 @@
|
|
|
12
12
|
<span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
15
|
-
`,r.addEventListener("click",n);let t=s=>{var S,k,V,y,O,W,H,oe,_,le,X,U;let i=(S=s.launcher)!=null?S:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(k=i.title)!=null?k:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(V=i.subtitle)!=null?V:"Get answers fast");let g=r.querySelector(".tvw-flex-col");g&&(i.textHidden?g.style.display="none":g.style.display="");let w=r.querySelector("[data-role='launcher-icon']");if(w)if(i.agentIconHidden)w.style.display="none";else{let Se=(y=i.agentIconSize)!=null?y:"40px";if(w.style.height=Se,w.style.width=Se,w.innerHTML="",i.agentIconName){let N=parseFloat(Se)||24,re=ie(i.agentIconName,N*.6,"#ffffff",2);re?(w.appendChild(re),w.style.display=""):(w.textContent=(O=i.agentIconText)!=null?O:"\u{1F4AC}",w.style.display="")}else i.iconUrl?w.style.display="none":(w.textContent=(W=i.agentIconText)!=null?W:"\u{1F4AC}",w.style.display="")}let c=r.querySelector("[data-role='launcher-image']");if(c){let Se=(H=i.agentIconSize)!=null?H:"40px";c.style.height=Se,c.style.width=Se,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(c.src=i.iconUrl,c.style.display="block"):c.style.display="none"}let h=r.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let Se=(oe=i.callToActionIconSize)!=null?oe:"32px";h.style.height=Se,h.style.width=Se,i.callToActionIconBackgroundColor?(h.style.backgroundColor=i.callToActionIconBackgroundColor,h.classList.remove("tvw-bg-cw-primary")):(h.style.backgroundColor="",h.classList.add("tvw-bg-cw-primary"));let N=0;if(i.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=i.callToActionIconPadding,N=(parseFloat(i.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),i.callToActionIconHidden)h.style.display="none";else if(h.style.display="",h.innerHTML="",i.callToActionIconName){let re=parseFloat(Se)||24,D=Math.max(re-N,8),Z=ie(i.callToActionIconName,D,"currentColor",2);Z?h.appendChild(Z):h.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}else h.textContent=(le=i.callToActionIconText)!=null?le:"\u2197"}let f=i.position&&Ut[i.position]?Ut[i.position]:Ut["bottom-right"],x="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${x} ${f}`;let C="1px solid #e5e7eb",E="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(X=i.border)!=null?X:C,r.style.boxShadow=(U=i.shadow)!=null?U:E},o=()=>{r.removeEventListener("click",n),r.remove()};return e&&t(e),{element:r,update:t,destroy:o}};var rn=e=>{var le,X,U,Se,N,re,D,Z,ve,pe,Ue,it,Tt,$t,Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt;let{config:n,showClose:r=!0}=e,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(le=n==null?void 0:n.launcher)!=null?le:{},s=(X=o.headerIconSize)!=null?X:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",a=(Se=o.closeButtonPlacement)!=null?Se:"inline",d=(N=o.headerIconHidden)!=null?N:!1,g=o.headerIconName,w=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(w.style.height=s,w.style.width=s,!d)if(g){let Q=parseFloat(s)||24,Oe=ie(g,Q*.6,"#ffffff",1);Oe?w.replaceChildren(Oe):w.textContent=(D=(re=n==null?void 0:n.launcher)==null?void 0:re.agentIconText)!=null?D:"\u{1F4AC}"}else if((Z=n==null?void 0:n.launcher)!=null&&Z.iconUrl){let Q=p("img");Q.src=n.launcher.iconUrl,Q.alt="",Q.className="tvw-rounded-xl tvw-object-cover",Q.style.height=s,Q.style.width=s,w.replaceChildren(Q)}else w.textContent=(pe=(ve=n==null?void 0:n.launcher)==null?void 0:ve.agentIconText)!=null?pe:"\u{1F4AC}";let c=p("div","tvw-flex tvw-flex-col"),h=p("span","tvw-text-base tvw-font-semibold");h.textContent=(it=(Ue=n==null?void 0:n.launcher)==null?void 0:Ue.title)!=null?it:"Chat Assistant";let f=p("span","tvw-text-xs tvw-text-cw-muted");f.textContent=($t=(Tt=n==null?void 0:n.launcher)==null?void 0:Tt.subtitle)!=null?$t:"Here to help you get answers fast",c.append(h,f),d?t.append(c):t.append(w,c);let x=(Fe=o.clearChat)!=null?Fe:{},C=(Ae=x.enabled)!=null?Ae:!0,E=(ee=x.placement)!=null?ee:"inline",S=null,k=null;if(C){let Q=(ge=x.size)!=null?ge:"32px",Oe=($e=x.iconName)!=null?$e:"refresh-cw",bt=(Qe=x.iconColor)!=null?Qe:"",Wt=(At=x.backgroundColor)!=null?At:"",Mt=(me=x.borderWidth)!=null?me:"",j=(J=x.borderColor)!=null?J:"",Ze=(ct=x.borderRadius)!=null?ct:"",We=(ut=x.paddingX)!=null?ut:"",z=(ft=x.paddingY)!=null?ft:"",R=(Ot=x.tooltipText)!=null?Ot:"Clear chat",he=(wt=x.showTooltip)!=null?wt:!0;k=p("div",E==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),S=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),S.style.height=Q,S.style.width=Q,S.type="button",S.setAttribute("aria-label",R);let ue=ie(Oe,"20px",bt||"",1);if(ue&&S.appendChild(ue),bt&&(S.style.color=bt,S.classList.remove("tvw-text-cw-muted")),Wt&&(S.style.backgroundColor=Wt,S.classList.remove("hover:tvw-bg-gray-100")),Mt||j){let te=Mt||"0px",Le=j||"transparent";S.style.border=`${te} solid ${Le}`,S.classList.remove("tvw-border-none")}if(Ze&&(S.style.borderRadius=Ze,S.classList.remove("tvw-rounded-full")),We?(S.style.paddingLeft=We,S.style.paddingRight=We):(S.style.paddingLeft="",S.style.paddingRight=""),z?(S.style.paddingTop=z,S.style.paddingBottom=z):(S.style.paddingTop="",S.style.paddingBottom=""),k.appendChild(S),he&&R&&S&&k){let te=null,Le=()=>{if(te||!S)return;te=p("div","tvw-clear-chat-tooltip"),te.textContent=R;let q=p("div");q.className="tvw-clear-chat-tooltip-arrow",te.appendChild(q);let de=S.getBoundingClientRect();te.style.position="fixed",te.style.left=`${de.left+de.width/2}px`,te.style.top=`${de.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Ne=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};k.addEventListener("mouseenter",Le),k.addEventListener("mouseleave",Ne),S.addEventListener("focus",Le),S.addEventListener("blur",Ne),k._cleanupTooltip=()=>{Ne(),k&&(k.removeEventListener("mouseenter",Le),k.removeEventListener("mouseleave",Ne)),S&&(S.removeEventListener("focus",Le),S.removeEventListener("blur",Ne))}}E==="inline"&&t.appendChild(k)}let V=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":C&&E==="inline"?"":"tvw-ml-auto"),y=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");y.style.height=i,y.style.width=i,y.type="button";let O=(Y=o.closeButtonTooltipText)!=null?Y:"Close chat",W=(Ie=o.closeButtonShowTooltip)!=null?Ie:!0;y.setAttribute("aria-label",O),y.style.display=r?"":"none";let H=(vt=o.closeButtonIconName)!=null?vt:"x",oe=(yt=o.closeButtonIconText)!=null?yt:"\xD7",_=ie(H,"20px",o.closeButtonColor||"",1);if(_?y.appendChild(_):y.textContent=oe,o.closeButtonColor?(y.style.color=o.closeButtonColor,y.classList.remove("tvw-text-cw-muted")):(y.style.color="",y.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(y.style.backgroundColor=o.closeButtonBackgroundColor,y.classList.remove("hover:tvw-bg-gray-100")):(y.style.backgroundColor="",y.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Q=o.closeButtonBorderWidth||"0px",Oe=o.closeButtonBorderColor||"transparent";y.style.border=`${Q} solid ${Oe}`,y.classList.remove("tvw-border-none")}else y.style.border="",y.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(y.style.borderRadius=o.closeButtonBorderRadius,y.classList.remove("tvw-rounded-full")):(y.style.borderRadius="",y.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(y.style.paddingLeft=o.closeButtonPaddingX,y.style.paddingRight=o.closeButtonPaddingX):(y.style.paddingLeft="",y.style.paddingRight=""),o.closeButtonPaddingY?(y.style.paddingTop=o.closeButtonPaddingY,y.style.paddingBottom=o.closeButtonPaddingY):(y.style.paddingTop="",y.style.paddingBottom=""),V.appendChild(y),W&&O){let Q=null,Oe=()=>{if(Q)return;Q=p("div","tvw-clear-chat-tooltip"),Q.textContent=O;let Wt=p("div");Wt.className="tvw-clear-chat-tooltip-arrow",Q.appendChild(Wt);let Mt=y.getBoundingClientRect();Q.style.position="fixed",Q.style.left=`${Mt.left+Mt.width/2}px`,Q.style.top=`${Mt.top-8}px`,Q.style.transform="translate(-50%, -100%)",document.body.appendChild(Q)},bt=()=>{Q&&Q.parentNode&&(Q.parentNode.removeChild(Q),Q=null)};V.addEventListener("mouseenter",Oe),V.addEventListener("mouseleave",bt),y.addEventListener("focus",Oe),y.addEventListener("blur",bt),V._cleanupTooltip=()=>{bt(),V.removeEventListener("mouseenter",Oe),V.removeEventListener("mouseleave",bt),y.removeEventListener("focus",Oe),y.removeEventListener("blur",bt)}}return a!=="top-right"&&t.appendChild(V),{header:t,iconHolder:w,headerTitle:h,headerSubtitle:f,closeButton:y,closeButtonWrapper:V,clearChatButton:S,clearChatButtonWrapper:k}},xn=(e,n,r)=>{var i,a,d,g;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=t.closeButtonPlacement)!=null?a:"inline",s=(g=(d=t.clearChat)==null?void 0:d.placement)!=null?g:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var or=e=>rn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),ir=e=>{var x,C,E,S;let{config:n,showClose:r=!0,onClose:t}=e,o=(x=n==null?void 0:n.launcher)!=null?x:{},s=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(C=o.title)!=null?C:"Chat Assistant",s.appendChild(i);let a=(E=o.closeButtonSize)!=null?E:"32px",d=p("div",""),g=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");g.style.height=a,g.style.width=a,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=r?"":"none";let w=(S=o.closeButtonIconName)!=null?S:"x",c=ie(w,"20px",o.closeButtonColor||"",2);c?g.appendChild(c):g.textContent="\xD7",t&&g.addEventListener("click",t),d.appendChild(g),s.appendChild(d);let h=p("div");h.style.display="none";let f=p("span");return f.style.display="none",{header:s,iconHolder:h,headerTitle:i,headerSubtitle:f,closeButton:g,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},ar=e=>{var y,O,W,H,oe,_,le,X;let{config:n,showClose:r=!0,onClose:t,onClearChat:o}=e,s=(y=n==null?void 0:n.launcher)!=null?y:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=p("div","tvw-flex tvw-items-center tvw-gap-3"),d=(O=s.headerIconSize)!=null?O:"56px",g=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");g.style.height=d,g.style.width=d;let w=s.headerIconName;if(w){let U=parseFloat(d)||24,Se=ie(w,U*.5,"#ffffff",2);Se?g.replaceChildren(Se):g.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}"}else if(s.iconUrl){let U=p("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=d,U.style.width=d,g.replaceChildren(U)}else g.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}";let c=p("div","tvw-flex tvw-flex-col tvw-flex-1"),h=p("span","tvw-text-lg tvw-font-semibold");h.textContent=(oe=s.title)!=null?oe:"Chat Assistant";let f=p("span","tvw-text-sm tvw-text-cw-muted");f.textContent=(_=s.subtitle)!=null?_:"Here to help you get answers fast",c.append(h,f),a.append(g,c);let x=(le=s.closeButtonSize)!=null?le:"32px",C=p("div",""),E=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");E.style.height=x,E.style.width=x,E.type="button",E.setAttribute("aria-label","Close chat"),E.style.display=r?"":"none";let S=(X=s.closeButtonIconName)!=null?X:"x",k=ie(S,"20px",s.closeButtonColor||"",2);k?E.appendChild(k):E.textContent="\xD7",t&&E.addEventListener("click",t),C.appendChild(E),a.appendChild(C),i.appendChild(a);let V=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return V.textContent="Online and ready to help",i.appendChild(V),{header:i,iconHolder:g,headerTitle:h,headerSubtitle:f,closeButton:E,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}},Os={default:or,minimal:ir,expanded:ar},lr=e=>{var n;return(n=Os[e])!=null?n:Os.default},Bn=(e,n,r)=>{var i,a,d;if(n!=null&&n.render){let g=n.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),w=p("div");w.style.display="none";let c=p("span"),h=p("span"),f=p("button");f.style.display="none";let x=p("div");return x.style.display="none",{header:g,iconHolder:w,headerTitle:c,headerSubtitle:h,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=lr(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Na=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Rn=e=>{var Fe,Ae,ee,ge,$e,Qe,At,me,J,ct,ut,ft,Ot,wt,Y,Ie,vt,yt,Q,Oe,bt,Wt,Mt,j,Ze,We,z,R,he,ue;let{config:n}=e,r=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=p("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=p("textarea");s.placeholder=(Ae=(Fe=n==null?void 0:n.copy)==null?void 0:Fe.inputPlaceholder)!=null?Ae:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none tvw-composer-textarea",s.rows=1;let i=(ge=(ee=n==null?void 0:n.theme)==null?void 0:ee.inputFontFamily)!=null?ge:"sans-serif",a=(Qe=($e=n==null?void 0:n.theme)==null?void 0:$e.inputFontWeight)!=null?Qe:"400";s.style.fontFamily=Na(i),s.style.fontWeight=a;let w=3*20;s.style.maxHeight=`${w}px`,s.style.overflowY="auto";let c=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,w);s.style.height=`${te}px`};s.addEventListener("input",c),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let h=(At=n==null?void 0:n.sendButton)!=null?At:{},f=(me=h.useIcon)!=null?me:!1,x=(J=h.iconText)!=null?J:"\u2191",C=h.iconName,E=(ct=h.tooltipText)!=null?ct:"Send message",S=(ut=h.showTooltip)!=null?ut:!1,k=(ft=h.size)!=null?ft:"40px",V=h.backgroundColor,y=h.textColor,O=p("div","tvw-send-button-wrapper"),W=p("button",f?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(W.type="submit",f){if(W.style.width=k,W.style.height=k,W.style.minWidth=k,W.style.minHeight=k,W.style.fontSize="18px",W.style.lineHeight="1",W.innerHTML="",C){let te=parseFloat(k)||24,Le=y&&typeof y=="string"&&y.trim()?y.trim():"currentColor",Ne=ie(C,te,Le,2);Ne?(W.appendChild(Ne),W.style.color=Le):(W.textContent=x,y?W.style.color=y:W.classList.add("tvw-text-white"))}else W.textContent=x,y?W.style.color=y:W.classList.add("tvw-text-white");V?W.style.backgroundColor=V:W.classList.add("tvw-bg-cw-primary")}else W.textContent=(wt=(Ot=n==null?void 0:n.copy)==null?void 0:Ot.sendButtonLabel)!=null?wt:"Send",y?W.style.color=y:W.classList.add("tvw-text-white");if(h.borderWidth&&(W.style.borderWidth=h.borderWidth,W.style.borderStyle="solid"),h.borderColor&&(W.style.borderColor=h.borderColor),h.paddingX?(W.style.paddingLeft=h.paddingX,W.style.paddingRight=h.paddingX):(W.style.paddingLeft="",W.style.paddingRight=""),h.paddingY?(W.style.paddingTop=h.paddingY,W.style.paddingBottom=h.paddingY):(W.style.paddingTop="",W.style.paddingBottom=""),S&&E){let te=p("div","tvw-send-button-tooltip");te.textContent=E,O.appendChild(te)}O.appendChild(W);let H=(Y=n==null?void 0:n.voiceRecognition)!=null?Y:{},oe=H.enabled===!0,_=null,le=null,X=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(oe&&X){le=p("div","tvw-send-button-wrapper"),_=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),_.type="button",_.setAttribute("aria-label","Start voice recognition");let te=(Ie=H.iconName)!=null?Ie:"mic",Le=(vt=H.iconSize)!=null?vt:k,Ne=parseFloat(Le)||24,q=(yt=H.backgroundColor)!=null?yt:V,de=(Q=H.iconColor)!=null?Q:y;_.style.width=Le,_.style.height=Le,_.style.minWidth=Le,_.style.minHeight=Le,_.style.fontSize="18px",_.style.lineHeight="1";let Be=de||"currentColor",Je=ie(te,Ne,Be,1.5);Je?(_.appendChild(Je),_.style.color=Be):(_.textContent="\u{1F3A4}",_.style.color=Be),q?_.style.backgroundColor=q:_.classList.add("tvw-bg-cw-primary"),de?_.style.color=de:!de&&!y&&_.classList.add("tvw-text-white"),H.borderWidth&&(_.style.borderWidth=H.borderWidth,_.style.borderStyle="solid"),H.borderColor&&(_.style.borderColor=H.borderColor),H.paddingX&&(_.style.paddingLeft=H.paddingX,_.style.paddingRight=H.paddingX),H.paddingY&&(_.style.paddingTop=H.paddingY,_.style.paddingBottom=H.paddingY),le.appendChild(_);let st=(Oe=H.tooltipText)!=null?Oe:"Start voice recognition";if(((bt=H.showTooltip)!=null?bt:!1)&&st){let rt=p("div","tvw-send-button-tooltip");rt.textContent=st,le.appendChild(rt)}}let U=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},Se=U.enabled===!0,N=null,re=null,D=null,Z=null;if(Se){Z=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),Z.style.display="none",D=p("input"),D.type="file",D.accept=((Mt=U.allowedTypes)!=null?Mt:cn).join(","),D.multiple=((j=U.maxFiles)!=null?j:4)>1,D.style.display="none",D.setAttribute("aria-label","Attach files"),re=p("div","tvw-send-button-wrapper"),N=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),N.type="button",N.setAttribute("aria-label",(Ze=U.buttonTooltipText)!=null?Ze:"Attach file");let te=(We=U.buttonIconName)!=null?We:"paperclip",Le=k,Ne=parseFloat(Le)||40,q=Math.round(Ne*.6);N.style.width=Le,N.style.height=Le,N.style.minWidth=Le,N.style.minHeight=Le,N.style.fontSize="18px",N.style.lineHeight="1",N.style.backgroundColor="transparent",N.style.color="var(--cw-primary, #111827)",N.style.border="none",N.style.borderRadius="6px",N.style.transition="background-color 0.15s ease",N.addEventListener("mouseenter",()=>{N.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),N.addEventListener("mouseleave",()=>{N.style.backgroundColor="transparent"});let de=ie(te,q,"currentColor",1.5);de?N.appendChild(de):N.textContent="\u{1F4CE}",N.addEventListener("click",st=>{st.preventDefault(),D==null||D.click()}),re.appendChild(N);let Be=(z=U.buttonTooltipText)!=null?z:"Attach file",Je=p("div","tvw-send-button-tooltip");Je.textContent=Be,re.appendChild(Je)}o.addEventListener("click",te=>{te.target!==W&&te.target!==O&&te.target!==_&&te.target!==le&&te.target!==N&&te.target!==re&&s.focus()}),Z&&(Z.style.gap="8px",o.append(Z)),D&&o.append(D),o.append(s);let ve=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),pe=p("div","tvw-flex tvw-items-center tvw-gap-2");re&&pe.append(re);let Ue=p("div","tvw-flex tvw-items-center tvw-gap-1");le&&Ue.append(le),Ue.append(O),ve.append(pe,Ue),o.append(ve);let it=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Tt=(R=n==null?void 0:n.statusIndicator)!=null?R:{},$t=(he=Tt.visible)!=null?he:!0;return it.style.display=$t?"":"none",it.textContent=(ue=Tt.idleText)!=null?ue:"Online",r.append(t,o,it),{footer:r,suggestions:t,composerForm:o,textarea:s,sendButton:W,sendButtonWrapper:O,micButton:_,micButtonWrapper:le,statusText:it,attachmentButton:N,attachmentButtonWrapper:re,attachmentInput:D,attachmentPreviewsContainer:Z,actionsRow:ve,leftActions:pe,rightActions:Ue}};var Ui=e=>{var d,g,w,c,h,f,x;if(!((g=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?g:!0)){let C=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),E=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),S=(c=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?c:"100%";return C.style.width=S,E.style.width="100%",C.appendChild(E),{wrapper:C,panel:E}}let r=(h=e==null?void 0:e.launcher)!=null?h:{},t=r.position&&Ut[r.position]?Ut[r.position]:Ut["bottom-right"],o=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(x=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?x:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},Ji=(e,n=!0)=>{var f,x,C,E,S,k,V;let r=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(f=e==null?void 0:e.layout)==null?void 0:f.header,o=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,s=t?Bn(e,t,{showClose:n}):rn({config:e,showClose:n}),i=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(E=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?E:"Hello \u{1F44B}";let g=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");g.textContent=(k=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",a.append(d,g);let w=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,w);let c=Rn({config:e}),h=((V=e==null?void 0:e.layout)==null?void 0:V.showFooter)!==!1;return o?xn(r,s,e):(s.header.style.display="none",xn(r,s,e)),r.append(i),h||(c.footer.style.display="none"),r.append(c.footer),{container:r,body:i,messagesWrapper:w,suggestions:c.suggestions,textarea:c.textarea,sendButton:c.sendButton,sendButtonWrapper:c.sendButtonWrapper,micButton:c.micButton,micButtonWrapper:c.micButtonWrapper,composerForm:c.composerForm,statusText:c.statusText,introTitle:d,introSubtitle:g,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:c.footer,attachmentButton:c.attachmentButton,attachmentButtonWrapper:c.attachmentButtonWrapper,attachmentInput:c.attachmentInput,attachmentPreviewsContainer:c.attachmentPreviewsContainer,actionsRow:c.actionsRow,leftActions:c.leftActions,rightActions:c.rightActions}};var Sn=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(r),e.appendChild(t),e.appendChild(o),e},dr=(e,n,r)=>{let t={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:Sn};if(n){let o=n(t);if(o!==null)return o}return Sn()},Da=(e,n)=>{let r=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=p("img");o.src=t,o.alt=n==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=n==="user"?"U":"A",r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Ki=(e,n)=>{let r=p("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?r.textContent=n.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},ja=(e,n="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},cr=(e,n,r)=>{var f,x,C,E,S,k;let t=(f=n.showCopy)!=null?f:!0,o=(x=n.showUpvote)!=null?x:!0,s=(C=n.showDownvote)!=null?C:!0,i=(E=n.visibility)!=null?E:"hover",a=(S=n.align)!=null?S:"right",d=(k=n.layout)!=null?k:"pill-inside",g={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],w={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],c=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${g} ${w} ${i==="hover"?"tvw-message-actions-hover":""}`);c.id=`actions-${e.id}`,c.setAttribute("data-actions-for",e.id);let h=(V,y,O)=>{let W=document.createElement("button");W.className="tvw-message-action-btn",W.setAttribute("aria-label",y),W.setAttribute("title",y),W.setAttribute("data-action",O);let H=ie(V,14,"currentColor",2);return H&&W.appendChild(H),W};return t&&c.appendChild(h("copy","Copy message","copy")),o&&c.appendChild(h("thumbs-up","Upvote","upvote")),s&&c.appendChild(h("thumbs-down","Downvote","downvote")),c},Fn=(e,n,r,t,o,s)=>{var y,O,W,H,oe;let i=r!=null?r:{},a=(y=i.layout)!=null?y:"bubble",d=i.avatar,g=i.timestamp,w=(O=d==null?void 0:d.show)!=null?O:!1,c=(W=g==null?void 0:g.show)!=null?W:!1,h=(H=d==null?void 0:d.position)!=null?H:"left",f=(oe=g==null?void 0:g.position)!=null?oe:"below",x=ja(e.role,a),C=p("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id);let E=document.createElement("div");if(E.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),c&&f==="inline"&&e.createdAt){let _=Ki(e,g);_.classList.add("tvw-ml-2","tvw-inline"),E.appendChild(_)}if(C.appendChild(E),c&&f==="below"&&e.createdAt){let _=Ki(e,g);_.classList.add("tvw-mt-1"),C.appendChild(_)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let _=dr("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);_&&C.appendChild(_)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let _=cr(e,t,o);C.appendChild(_)}if(!w||e.role==="system")return C;let k=p("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),V=Da(d,e.role);return h==="right"||h==="left"&&e.role==="user"?k.append(C,V):k.append(V,C),C.classList.remove("tvw-max-w-[85%]"),C.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),k},Yi=(e,n,r,t,o,s)=>{let i=r!=null?r:{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Fn(e,n,r,t,o,s)};var $n=new Set,Vi=(e,n)=>{let r=$n.has(e),t=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".tvw-border-t");if(!t||!o)return;t.setAttribute("aria-expanded",r?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},ur=e=>{let n=e.reasoning,r=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let t=$n.has(e.id),o=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=p("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Ti(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),w=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);w?d.appendChild(w):d.textContent=t?"Hide":"Show";let c=p("div","tvw-flex tvw-items-center tvw-ml-auto");c.append(d),o.append(s,c);let h=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");h.style.display=t?"":"none";let f=n.chunks.join(""),x=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return x.textContent=f||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),h.appendChild(x),(()=>{o.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let S=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);S?d.appendChild(S):d.textContent=t?"Hide":"Show",h.style.display=t?"":"none"})(),r.append(o,h),r};var On=new Set,Xi=(e,n,r)=>{var g;let t=On.has(e),o=(g=r==null?void 0:r.toolCall)!=null?g:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",t?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let w=o.toggleTextColor||o.headerTextColor||"currentColor",c=ie(t?"chevron-up":"chevron-down",16,w,2);c?d.appendChild(c):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},pr=(e,n)=>{var C;let r=e.toolCall,t=(C=n==null?void 0:n.toolCall)!=null?C:{},o=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=On.has(e.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=p("div","tvw-flex tvw-flex-col tvw-text-left"),d=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Mi(r),a.appendChild(d);let g=p("div","tvw-flex tvw-items-center"),w=t.toggleTextColor||t.headerTextColor||"currentColor",c=ie(s?"chevron-up":"chevron-down",16,w,2);c?g.appendChild(c):g.textContent=s?"Hide":"Show";let h=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");h.append(g),i.append(a,h);let f=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(f.style.display=s?"":"none",t.contentBackgroundColor&&(f.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(f.style.color=t.contentTextColor),t.contentPaddingX&&(f.style.paddingLeft=t.contentPaddingX,f.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(f.style.paddingTop=t.contentPaddingY,f.style.paddingBottom=t.contentPaddingY),r.name){let E=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?E.style.color=t.contentTextColor:t.headerTextColor&&(E.style.color=t.headerTextColor),E.textContent=r.name,f.appendChild(E)}if(r.args!==void 0){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Arguments";let k=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=nr(r.args),E.append(S,k),f.appendChild(E)}if(r.chunks&&r.chunks.length){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Activity";let k=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=r.chunks.join(`
|
|
16
|
-
`),E.append(S,k),f.appendChild(E)}if(r.status==="complete"&&r.result!==void 0){let E=p("div","tvw-space-y-1"),S=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Result";let k=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(k.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(k.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(k.style.color=t.codeBlockTextColor),k.textContent=nr(r.result),E.append(S,k),f.appendChild(E)}if(r.status==="complete"&&typeof r.duration=="number"){let E=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(E.style.color=t.contentTextColor),E.textContent=`Duration: ${r.duration}ms`,f.appendChild(E)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),g.innerHTML="";let E=t.toggleTextColor||t.headerTextColor||"currentColor",S=ie(s?"chevron-up":"chevron-down",16,E,2);S?g.appendChild(S):g.textContent=s?"Hide":"Show",f.style.display=s?"":"none"})(),o.append(i,f),o};var Gi=e=>{let n=[];return{buttons:n,render:(t,o,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(f=>f.role==="user"))return;let w=document.createDocumentFragment(),c=o?o.isStreaming():!1,h=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(f=>{let x=p("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");x.type="button",x.textContent=f,x.disabled=c,a!=null&&a.fontFamily&&(x.style.fontFamily=h(a.fontFamily)),a!=null&&a.fontWeight&&(x.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(x.style.paddingLeft=a.paddingX,x.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(x.style.paddingTop=a.paddingY,x.style.paddingBottom=a.paddingY),x.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(f))}),w.appendChild(x),n.push(x)}),e.appendChild(w)}}};var as=class{constructor(n=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=r}push(n){var r;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(r=this.store)==null||r.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let r=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let t of r)this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(t.type);return this.totalCaptured=n.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let r=this.getAll();return n>=r.length?r:r.slice(r.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ls=class{constructor(n="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=r}open(){return new Promise((n,r)=>{try{let t=indexedDB.open(this.dbName,1);t.onupgradeneeded=()=>{let o=t.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},t.onsuccess=()=>{this.db=t.result,n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}getAll(){return new Promise((n,r)=>{if(!this.db){n([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{n(i.result)},i.onerror=()=>{r(i.error)}}catch(t){r(t)}})}getCount(){return new Promise((n,r)=>{if(!this.db){n(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}clear(){return new Promise((n,r)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{r(s.error)}}catch(t){r(t)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,r)=>{try{let t=indexedDB.deleteDatabase(this.dbName);t.onsuccess=()=>{n()},t.onerror=()=>{r(t.error)}}catch(t){r(t)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)t.put(o)}catch{}}};function Nn(e,n){n&&n.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var _a={flow_:{bg:"#dcfce7",text:"#166534"},step_:{bg:"#dbeafe",text:"#1e40af"},reason_:{bg:"#ffedd5",text:"#9a3412"},tool_:{bg:"#f3e8ff",text:"#6b21a8"},agent_:{bg:"#ccfbf1",text:"#115e59"},error:{bg:"#fecaca",text:"#991b1b"}},qa={bg:"#f3f4f6",text:"#4b5563"},za=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ua=100;function Ja(e,n){let r={..._a,...n};if(r[e])return r[e];for(let t of Object.keys(r))if(t.endsWith("_")&&e.startsWith(t))return r[t];return qa}function Ka(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Ya(e){let n=new Date(e),r=String(n.getHours()).padStart(2,"0"),t=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${r}:${t}:${o}.${s}`}function Va(e,n){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let t of n){let o=t.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Xa(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),r()})}function Ga(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Qa(e,n,r){let t,o;try{o=JSON.parse(e.payload),t=JSON.stringify(o,null,2)}catch{o=e.payload,t=e.payload}let s=n.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=p("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),d=p("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return d.textContent=t,a.appendChild(d),a}}function gr(e,n,r,t,o,s,i,a){var h;let d=o.has(e.id),g=p("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");Nn(g,(h=t.classNames)==null?void 0:h.eventRow);let w=i.find(f=>f.renderEventStreamRow);if(w!=null&&w.renderEventStreamRow&&a){let f=w.renderEventStreamRow({event:e,index:n,config:a,defaultRenderer:()=>c(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return g.appendChild(f),g}return g.appendChild(c()),g;function c(){var U,Se;let f=p("div",""),x=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-3 tvw-py-3 hover:tvw-bg-cw-container tvw-cursor-pointer tvw-group");x.setAttribute("data-event-id",e.id);let C=p("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),E=ie(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&C.appendChild(E);let S=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),k=(U=t.timestampFormat)!=null?U:"relative";S.textContent=k==="relative"?Ka(e.timestamp,r):Ya(e.timestamp);let V=null;t.showSequenceNumbers!==!1&&(V=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),V.textContent=String(n+1));let y=Ja(e.type,t.badgeColors),O=p("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded tvw-text-[11px] tvw-font-mono tvw-font-medium tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-border");O.style.backgroundColor=y.bg,O.style.color=y.text,O.style.borderColor=y.text+"50",O.textContent=e.type;let W=(Se=t.descriptionFields)!=null?Se:za,H=Va(e.payload,W),oe=null;H&&(oe=p("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),oe.textContent=H);let _=p("div","tvw-flex-1 tvw-min-w-0"),le=p("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),X=ie("clipboard","12px","currentColor",1.5);return X&&le.appendChild(X),le.addEventListener("click",async N=>{N.stopPropagation(),await Xa(Ga(e)),le.innerHTML="";let re=ie("check","12px","currentColor",1.5);re&&le.appendChild(re),setTimeout(()=>{le.innerHTML="";let D=ie("clipboard","12px","currentColor",1.5);D&&le.appendChild(D)},1500)}),x.appendChild(C),x.appendChild(S),V&&x.appendChild(V),x.appendChild(O),oe&&x.appendChild(oe),x.appendChild(_),x.appendChild(le),f.appendChild(x),d&&f.appendChild(Qa(e,i,a)),f}}function Qi(e){var g,w;let{buffer:n,getFullHistory:r,onClose:t,config:o,plugins:s=[]}=e,i=(w=(g=o==null?void 0:o.features)==null?void 0:g.eventStream)!=null?w:{},a=s.find(c=>c.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let c=a.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>d().element,onClose:t});if(c)return{element:c,update:()=>{},destroy:()=>{}}}return d();function d(){let c=i.classNames,h=p("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");Nn(h,c==null?void 0:c.panel);let f=[],x="",C="",E=null,S=[],k={},V=0,y=!1,O=0,W=0,H=!1,oe=null,_=!1,le=0,X=new Set,U=new Map,Se="",N="",re=null,D,Z,ve,pe,Ue;function it(){let z=p("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),R=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-4 tvw-py-3 tvw-pb-0 tvw-border-cw-divider tvw-bg-cw-surface tvw-overflow-hidden");Nn(R,c==null?void 0:c.headerBar);let he=p("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");he.textContent="Events",D=p("span","tvw-text-[11px] tvw-font-mono tvw-bg-cw-container tvw-text-cw-muted tvw-px-2 tvw-py-0.5 tvw-rounded tvw-border tvw-border-cw-border"),D.textContent="0";let ue=p("div","tvw-flex-1");Z=p("select","tvw-text-xs tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded tvw-px-2.5 tvw-py-1 tvw-text-cw-primary tvw-cursor-pointer");let te=p("option","");te.value="",te.textContent="All events",Z.appendChild(te),ve=p("button","tvw-inline-flex tvw-items-center tvw-gap-1.5 tvw-rounded tvw-text-xs tvw-text-cw-muted hover:tvw-bg-cw-container hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border tvw-border-cw-border tvw-bg-cw-surface tvw-flex-shrink-0 tvw-px-2.5 tvw-py-1"),ve.type="button",ve.title="Copy All";let Ne=ie("clipboard-copy","12px","currentColor",1.5);Ne&&ve.appendChild(Ne);let q=p("span","tvw-text-xs");q.textContent="Copy All",ve.appendChild(q),R.appendChild(he),R.appendChild(D),R.appendChild(ue),R.appendChild(Z),R.appendChild(ve);let de=p("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");Nn(de,c==null?void 0:c.searchBar);let Be=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),Je=p("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Be&&Je.appendChild(Be),pe=p("input","tvw-text-sm tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded-md tvw-pl-8 tvw-pr-3 tvw-py-1 tvw-w-full tvw-text-cw-primary"),Nn(pe,c==null?void 0:c.searchInput),pe.type="text",pe.placeholder="Search event payloads...",Ue=p("button","tvw-absolute tvw-right-5 tvw-top-1/2 tvw--translate-y-1/2 tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-0 tvw-leading-none"),Ue.type="button",Ue.style.display="none";let st=ie("x","12px","currentColor",2);return st&&Ue.appendChild(st),de.appendChild(Je),de.appendChild(pe),de.appendChild(Ue),z.appendChild(R),z.appendChild(de),z}let Tt,$t=s.find(z=>z.renderEventStreamToolbar);if($t!=null&&$t.renderEventStreamToolbar&&o){let z=$t.renderEventStreamToolbar({config:o,defaultRenderer:()=>it(),eventCount:n.getSize(),filteredCount:0,onFilterChange:R=>{x=R,ut(),wt()},onSearchChange:R=>{C=R,ut(),wt()}});Tt=z!=null?z:it()}else Tt=it();let Fe=p("div","tvw-text-xs tvw-text-cw-muted tvw-text-center tvw-py-0.5 tvw-px-4 tvw-bg-cw-container tvw-border-b tvw-border-cw-divider tvw-italic tvw-flex-shrink-0");Fe.style.display="none";let Ae=p("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ee=p("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ee.style.height="100%";let ge=p("div","tvw-absolute tvw-bottom-3 tvw-left-1/2 tvw-transform tvw--translate-x-1/2 tvw-bg-cw-accent tvw-text-white tvw-text-xs tvw-px-3 tvw-py-1.5 tvw-rounded-full tvw-cursor-pointer tvw-shadow-md tvw-z-10 tvw-flex tvw-items-center tvw-gap-1");Nn(ge,c==null?void 0:c.scrollIndicator),ge.style.display="none";let $e=ie("arrow-down","12px","currentColor",2);$e&&ge.appendChild($e);let Qe=p("span","");ge.appendChild(Qe);let At=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");At.style.display="none",Ae.appendChild(ee),Ae.appendChild(At),Ae.appendChild(ge),h.setAttribute("tabindex","0"),h.appendChild(Tt),h.appendChild(Fe),h.appendChild(Ae);function me(){let z=n.getAll(),R={};for(let q of z)R[q.type]=(R[q.type]||0)+1;let he=Object.keys(R).sort(),ue=he.length!==S.length||!he.every((q,de)=>q===S[de]),te=!ue&&he.some(q=>R[q]!==k[q]),Le=z.length!==Object.values(k).reduce((q,de)=>q+de,0);if(!ue&&!te&&!Le||(S=he,k=R,!Z))return;let Ne=Z.value;if(Z.options[0].textContent="All events",ue){for(;Z.options.length>1;)Z.remove(1);for(let q of he){let de=p("option","");de.value=q,de.textContent=`${q} (${R[q]||0})`,Z.appendChild(de)}Ne&&he.includes(Ne)?Z.value=Ne:Ne&&(Z.value="",x="")}else for(let q=1;q<Z.options.length;q++){let de=Z.options[q];de.textContent=`${de.value} (${R[de.value]||0})`}}function J(){let z=n.getAll();if(x&&(z=z.filter(R=>R.type===x)),C){let R=C.toLowerCase();z=z.filter(he=>he.type.toLowerCase().includes(R)||he.payload.toLowerCase().includes(R))}return z}function ct(){return x!==""||C!==""}function ut(){V=0,O=0,y=!1,ge.style.display="none"}function ft(z){X.has(z)?X.delete(z):X.add(z),re=z;let R=ee.scrollTop,he=y;_=!0,y=!0,wt(),ee.scrollTop=R,y=he,_=!1}function Ot(){return ee.scrollHeight-ee.scrollTop-ee.clientHeight<=50}function wt(){W=Date.now(),H=!1,me();let z=n.getEvictedCount();z>0?(Fe.textContent=`${z.toLocaleString()} older events truncated`,Fe.style.display=""):Fe.style.display="none",f=J();let R=f.length,he=n.getSize()>0;D&&(D.textContent=String(n.getSize())),R===0&&he&&ct()?(At.textContent=C?`No events matching '${C}'`:"No events matching filter",At.style.display="",ee.style.display="none"):(At.style.display="none",ee.style.display=""),ve&&(ve.title=ct()?`Copy Filtered (${R})`:"Copy All"),y&&R>V&&(O+=R-V,Qe.textContent=`${O} new event${O===1?"":"s"}`,ge.style.display=""),V=R;let ue=n.getAll(),te=ue.length>0?ue[0].timestamp:0,Le=new Set(f.map(de=>de.id));for(let de of X)Le.has(de)||X.delete(de);let Ne=x!==Se||C!==N,q=U.size===0&&f.length>0;if(Ne||q||f.length===0){ee.innerHTML="",U.clear();let de=document.createDocumentFragment();for(let Be=0;Be<f.length;Be++){let Je=gr(f[Be],Be,te,i,X,ft,s,o);U.set(f[Be].id,Je),de.appendChild(Je)}ee.appendChild(de),Se=x,N=C,re=null}else{if(re!==null){let Be=U.get(re);if(Be&&Be.parentNode===ee){let Je=f.findIndex(st=>st.id===re);if(Je>=0){let st=gr(f[Je],Je,te,i,X,ft,s,o);ee.insertBefore(st,Be),Be.remove(),U.set(re,st)}}re=null}let de=new Set(f.map(Be=>Be.id));for(let[Be,Je]of U)de.has(Be)||(Je.remove(),U.delete(Be));for(let Be=0;Be<f.length;Be++){let Je=f[Be];if(!U.has(Je.id)){let st=gr(Je,Be,te,i,X,ft,s,o);U.set(Je.id,st),ee.appendChild(st)}}}y||(ee.scrollTop=ee.scrollHeight)}function Y(){if(Date.now()-W>=Ua){oe!==null&&(cancelAnimationFrame(oe),oe=null),wt();return}H||(H=!0,oe=requestAnimationFrame(()=>{oe=null,wt()}))}let Ie=(z,R)=>{if(!ve)return;ve.innerHTML="";let he=ie(z,"12px","currentColor",1.5);he&&ve.appendChild(he);let ue=p("span","tvw-text-xs");ue.textContent="Copy All",ve.appendChild(ue),setTimeout(()=>{ve.innerHTML="";let te=ie("clipboard-copy","12px","currentColor",1.5);te&&ve.appendChild(te);let Le=p("span","tvw-text-xs");Le.textContent="Copy All",ve.appendChild(Le),ve.disabled=!1},R)},vt=async()=>{if(ve){ve.disabled=!0;try{let z;ct()?z=f:z=r?await r():n.getAll();let R=z.map(he=>{try{return JSON.parse(he.payload)}catch{return he.payload}});await navigator.clipboard.writeText(JSON.stringify(R,null,2)),Ie("check",1500)}catch{Ie("x",1500)}}},yt=()=>{Z&&(x=Z.value,ut(),wt())},Q=()=>{!pe||!Ue||(Ue.style.display=pe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{C=pe.value,ut(),wt()},150))},Oe=()=>{!pe||!Ue||(pe.value="",C="",Ue.style.display="none",E&&clearTimeout(E),ut(),wt())},bt=()=>{if(_)return;let z=ee.scrollTop,R=z>le;le=z,Ot()&&R?(y=!1,O=0,ge.style.display="none"):Ot()||(y=!0)},Wt=z=>{z.deltaY<0&&(y=!0)},Mt=()=>{ee.scrollTop=ee.scrollHeight,y=!1,O=0,ge.style.display="none"},j=z=>{let R=z.target;if(!R||R.closest("button"))return;let he=R.closest("[data-event-id]");if(!he)return;let ue=he.getAttribute("data-event-id");ue&&ft(ue)},Ze=z=>{if((z.metaKey||z.ctrlKey)&&z.key==="f"){z.preventDefault(),pe==null||pe.focus(),pe==null||pe.select();return}z.key==="Escape"&&(pe&&document.activeElement===pe?(Oe(),pe.blur(),h.focus()):t&&t())};ve&&ve.addEventListener("click",vt),Z&&Z.addEventListener("change",yt),pe&&pe.addEventListener("input",Q),Ue&&Ue.addEventListener("click",Oe),ee.addEventListener("scroll",bt),ee.addEventListener("wheel",Wt,{passive:!0}),ee.addEventListener("click",j),ge.addEventListener("click",Mt),h.addEventListener("keydown",Ze);function We(){E&&clearTimeout(E),oe!==null&&(cancelAnimationFrame(oe),oe=null),H=!1,U.clear(),ve&&ve.removeEventListener("click",vt),Z&&Z.removeEventListener("change",yt),pe&&pe.removeEventListener("input",Q),Ue&&Ue.removeEventListener("click",Oe),ee.removeEventListener("scroll",bt),ee.removeEventListener("wheel",Wt),ee.removeEventListener("click",j),ge.removeEventListener("click",Mt),h.removeEventListener("keydown",Ze)}return{element:h,update:Y,destroy:We}}}var Zi={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},mr=(e,n,r,t)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,C,E;if(s.dataset.enhanced==="true")return;let i=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let a=(C=Zi[i])!=null?C:Zi.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),g=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(g.textContent=a.title,d.appendChild(g),a.description){let S=p("p","tvw-text-sm tvw-text-cw-muted");S.textContent=a.description,d.appendChild(S)}let w=document.createElement("form");w.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(S=>{var W,H;let k=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");k.htmlFor=`${n.id}-${i}-${S.name}`;let V=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");V.textContent=S.label,k.appendChild(V);let y=(W=S.type)!=null?W:"text",O;y==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=y),O.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",O.id=`${n.id}-${i}-${S.name}`,O.name=S.name,O.placeholder=(H=S.placeholder)!=null?H:"",S.required&&(O.required=!0),k.appendChild(O),w.appendChild(k)});let c=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),h=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),f=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");f.type="submit",f.textContent=(E=a.submitLabel)!=null?E:"Submit",c.appendChild(h),c.appendChild(f),w.appendChild(c),s.replaceChildren(d,w),w.addEventListener("submit",async S=>{var O,W;S.preventDefault();let k=(O=r.formEndpoint)!=null?O:"/form",V=new FormData(w),y={};V.forEach((H,oe)=>{y[oe]=H}),y.type=i,f.disabled=!0,h.textContent="Submitting\u2026";try{let H=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let oe=await H.json();h.textContent=(W=oe.message)!=null?W:"Thanks! We'll be in touch soon.",oe.success&&oe.nextPrompt&&await t.sendMessage(String(oe.nextPrompt))}catch(H){h.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var hr=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var t;let r=this.plugins.get(n);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let t=new Set(n.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},ds=new hr;var fr={primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},wr={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},et={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:fr,darkTheme:wr,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Ns(e){var n,r,t,o,s,i,a,d,g,w,c,h,f,x,C,E,S,k,V;return e?{...et,...e,theme:{...et.theme,...e.theme},darkTheme:{...et.darkTheme,...e.darkTheme},launcher:{...et.launcher,...e.launcher,clearChat:{...(n=et.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...et.copy,...e.copy},sendButton:{...et.sendButton,...e.sendButton},statusIndicator:{...et.statusIndicator,...e.statusIndicator},voiceRecognition:{...et.voiceRecognition,...e.voiceRecognition},features:{...et.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:et.suggestionChips,suggestionChipsConfig:{...et.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...et.layout,...e.layout,header:{...(o=et.layout)==null?void 0:o.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=et.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(g=(d=et.layout)==null?void 0:d.messages)==null?void 0:g.avatar,...(c=(w=e.layout)==null?void 0:w.messages)==null?void 0:c.avatar},timestamp:{...(f=(h=et.layout)==null?void 0:h.messages)==null?void 0:f.timestamp,...(C=(x=e.layout)==null?void 0:x.messages)==null?void 0:C.timestamp}},slots:{...(E=et.layout)==null?void 0:E.slots,...(S=e.layout)==null?void 0:S.slots}},markdown:{...et.markdown,...e.markdown,options:{...(k=et.markdown)==null?void 0:k.options,...(V=e.markdown)==null?void 0:V.options}},messageActions:{...et.messageActions,...e.messageActions}}:et}var ea=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=e.get(o))==null||i.delete(s)};return{on:n,off:r,emit:(o,s)=>{var i;(i=e.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Za=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},el=e=>{let n=e.trim(),r=n.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(r,o+1)}return null},cs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Za(e),r=el(n);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},vr=e=>typeof e=="string"?e:e==null?"":String(e),An={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:vr(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=vr(r.element);if(t&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:vr(r.text)}}},ta=e=>Array.isArray(e)?e.map(n=>String(n)):[],us=e=>{let n=new Set(ta(e.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(ta(e.getSessionMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(n);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?e.parsers.reduce((g,w)=>g||(w==null?void 0:w({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),t();let d={action:a,message:s.message};e.emit("action:detected",d);for(let g of e.handlers)if(g)try{let w=()=>{e.emit("action:resubmit",d)},c=g(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:w});if(!c)continue;if(c.handled){let h=c.persistMessage!==!1;return{text:c.displayText!==void 0?c.displayText:"",persist:h,resubmit:c.resubmit}}}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",w)}return{text:"",persist:!0}},syncFromMetadata:r}};var tl=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},nl=e=>e.map(n=>({...n,streaming:!1})),Ds=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?tl(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?nl(r.messages):void 0};t.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var yr=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([r,t])=>{this.register(r,t)})}},Dn=new yr;var jn=require("partial-json");function sl(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function rl(e,n){if(!sl(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:n}}function js(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e;try{let o=(0,jn.parse)(r,jn.STR|jn.OBJ),s=rl(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function na(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _s(e,n){let{config:r,message:t,onPropsUpdate:o}=n,s=Dn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:a=>{o&&o(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function sa(){let e=js();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function qs(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function zs(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var ol=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Us(e){let{onSubmit:n,onDismiss:r,title:t="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:g=ol}=e,w=document.createElement("div");w.className="tvw-feedback-container tvw-feedback-csat",w.setAttribute("role","dialog"),w.setAttribute("aria-label","Customer satisfaction feedback");let c=null,h=document.createElement("div");h.className="tvw-feedback-content";let f=document.createElement("div");f.className="tvw-feedback-header";let x=document.createElement("h3");x.className="tvw-feedback-title",x.textContent=t,f.appendChild(x);let C=document.createElement("p");C.className="tvw-feedback-subtitle",C.textContent=o,f.appendChild(C),h.appendChild(f);let E=document.createElement("div");E.className="tvw-feedback-rating tvw-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let W=1;W<=5;W++){let H=document.createElement("button");H.type="button",H.className="tvw-feedback-rating-btn tvw-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${g[W-1]}`),H.title=g[W-1],H.dataset.rating=String(W),H.innerHTML=`
|
|
15
|
+
`,r.addEventListener("click",n);let e=s=>{var C,W,V,b,N,M,R,ne,Y,_,q,U;let i=(C=s.launcher)!=null?C:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(W=i.title)!=null?W:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(V=i.subtitle)!=null?V:"Get answers fast");let c=r.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let v=r.querySelector("[data-role='launcher-icon']");if(v)if(i.agentIconHidden)v.style.display="none";else{let ue=(b=i.agentIconSize)!=null?b:"40px";if(v.style.height=ue,v.style.width=ue,v.innerHTML="",i.agentIconName){let B=parseFloat(ue)||24,Z=oe(i.agentIconName,B*.6,"#ffffff",2);Z?(v.appendChild(Z),v.style.display=""):(v.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(M=i.agentIconText)!=null?M:"\u{1F4AC}",v.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let ue=(R=i.agentIconSize)!=null?R:"40px";d.style.height=ue,d.style.width=ue,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(d.src=i.iconUrl,d.style.display="block"):d.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ue=(ne=i.callToActionIconSize)!=null?ne:"32px";f.style.height=ue,f.style.width=ue,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let B=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,B=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let Z=parseFloat(ue)||24,P=Math.max(Z-B,8),z=oe(i.callToActionIconName,P,"currentColor",2);z?f.appendChild(z):f.textContent=(Y=i.callToActionIconText)!=null?Y:"\u2197"}else f.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}let w=i.position&&Jt[i.position]?Jt[i.position]:Jt["bottom-right"],S="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${S} ${w}`;let x="1px solid #e5e7eb",E="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(q=i.border)!=null?q:x,r.style.boxShadow=(U=i.shadow)!=null?U:E},o=()=>{r.removeEventListener("click",n),r.remove()};return t&&e(t),{element:r,update:e,destroy:o}};var an=t=>{var _,q,U,ue,B,Z,P,z,Ce,fe,ze,dt,Mt,Nt,$e,Se,se,he,Fe,Xe,Et,pe,G,pt,gt,vt,Dt,yt,Q,We,bt,xt;let{config:n,showClose:r=!0}=t,e=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(_=n==null?void 0:n.launcher)!=null?_:{},s=(q=o.headerIconSize)!=null?q:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",a=(ue=o.closeButtonPlacement)!=null?ue:"inline",u=(B=o.headerIconHidden)!=null?B:!1,c=o.headerIconName,v=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(v.style.height=s,v.style.width=s,!u)if(c){let te=parseFloat(s)||24,Oe=oe(c,te*.6,"#ffffff",1);Oe?v.replaceChildren(Oe):v.textContent=(P=(Z=n==null?void 0:n.launcher)==null?void 0:Z.agentIconText)!=null?P:"\u{1F4AC}"}else if((z=n==null?void 0:n.launcher)!=null&&z.iconUrl){let te=g("img");te.src=n.launcher.iconUrl,te.alt="",te.className="tvw-rounded-xl tvw-object-cover",te.style.height=s,te.style.width=s,v.replaceChildren(te)}else v.textContent=(fe=(Ce=n==null?void 0:n.launcher)==null?void 0:Ce.agentIconText)!=null?fe:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col"),f=g("span","tvw-text-base tvw-font-semibold");f.textContent=(dt=(ze=n==null?void 0:n.launcher)==null?void 0:ze.title)!=null?dt:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(Nt=(Mt=n==null?void 0:n.launcher)==null?void 0:Mt.subtitle)!=null?Nt:"Here to help you get answers fast",d.append(f,w),u?e.append(d):e.append(v,d);let S=($e=o.clearChat)!=null?$e:{},x=(Se=S.enabled)!=null?Se:!0,E=(se=S.placement)!=null?se:"inline",C=null,W=null;if(x){let te=(he=S.size)!=null?he:"32px",Oe=(Fe=S.iconName)!=null?Fe:"refresh-cw",Ct=(Xe=S.iconColor)!=null?Xe:"",Wt=(Et=S.backgroundColor)!=null?Et:"",Lt=(pe=S.borderWidth)!=null?pe:"",j=(G=S.borderColor)!=null?G:"",et=(pt=S.borderRadius)!=null?pt:"",Ie=(gt=S.paddingX)!=null?gt:"",K=(vt=S.paddingY)!=null?vt:"",O=(Dt=S.tooltipText)!=null?Dt:"Clear chat",we=(yt=S.showTooltip)!=null?yt:!0;W=g("div",E==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),E==="top-right"&&(W.style.right="48px"),C=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),C.style.height=te,C.style.width=te,C.type="button",C.setAttribute("aria-label",O);let de=oe(Oe,"20px",Ct||"",1);if(de&&C.appendChild(de),Ct&&(C.style.color=Ct,C.classList.remove("tvw-text-cw-muted")),Wt&&(C.style.backgroundColor=Wt,C.classList.remove("hover:tvw-bg-gray-100")),Lt||j){let re=Lt||"0px",Me=j||"transparent";C.style.border=`${re} solid ${Me}`,C.classList.remove("tvw-border-none")}if(et&&(C.style.borderRadius=et,C.classList.remove("tvw-rounded-full")),Ie?(C.style.paddingLeft=Ie,C.style.paddingRight=Ie):(C.style.paddingLeft="",C.style.paddingRight=""),K?(C.style.paddingTop=K,C.style.paddingBottom=K):(C.style.paddingTop="",C.style.paddingBottom=""),W.appendChild(C),we&&O&&C&&W){let re=null,Me=()=>{if(re||!C)return;re=g("div","tvw-clear-chat-tooltip"),re.textContent=O;let J=g("div");J.className="tvw-clear-chat-tooltip-arrow",re.appendChild(J);let le=C.getBoundingClientRect();re.style.position="fixed",re.style.left=`${le.left+le.width/2}px`,re.style.top=`${le.top-8}px`,re.style.transform="translate(-50%, -100%)",document.body.appendChild(re)},Ne=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};W.addEventListener("mouseenter",Me),W.addEventListener("mouseleave",Ne),C.addEventListener("focus",Me),C.addEventListener("blur",Ne),W._cleanupTooltip=()=>{Ne(),W&&(W.removeEventListener("mouseenter",Me),W.removeEventListener("mouseleave",Ne)),C&&(C.removeEventListener("focus",Me),C.removeEventListener("blur",Ne))}}E==="inline"&&e.appendChild(W)}let V=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":x&&E==="inline"?"":"tvw-ml-auto"),b=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");b.style.height=i,b.style.width=i,b.type="button";let N=(Q=o.closeButtonTooltipText)!=null?Q:"Close chat",M=(We=o.closeButtonShowTooltip)!=null?We:!0;b.setAttribute("aria-label",N),b.style.display=r?"":"none";let R=(bt=o.closeButtonIconName)!=null?bt:"x",ne=(xt=o.closeButtonIconText)!=null?xt:"\xD7",Y=oe(R,"20px",o.closeButtonColor||"",1);if(Y?b.appendChild(Y):b.textContent=ne,o.closeButtonColor?(b.style.color=o.closeButtonColor,b.classList.remove("tvw-text-cw-muted")):(b.style.color="",b.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(b.style.backgroundColor=o.closeButtonBackgroundColor,b.classList.remove("hover:tvw-bg-gray-100")):(b.style.backgroundColor="",b.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let te=o.closeButtonBorderWidth||"0px",Oe=o.closeButtonBorderColor||"transparent";b.style.border=`${te} solid ${Oe}`,b.classList.remove("tvw-border-none")}else b.style.border="",b.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(b.style.borderRadius=o.closeButtonBorderRadius,b.classList.remove("tvw-rounded-full")):(b.style.borderRadius="",b.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(b.style.paddingLeft=o.closeButtonPaddingX,b.style.paddingRight=o.closeButtonPaddingX):(b.style.paddingLeft="",b.style.paddingRight=""),o.closeButtonPaddingY?(b.style.paddingTop=o.closeButtonPaddingY,b.style.paddingBottom=o.closeButtonPaddingY):(b.style.paddingTop="",b.style.paddingBottom=""),V.appendChild(b),M&&N){let te=null,Oe=()=>{if(te)return;te=g("div","tvw-clear-chat-tooltip"),te.textContent=N;let Wt=g("div");Wt.className="tvw-clear-chat-tooltip-arrow",te.appendChild(Wt);let Lt=b.getBoundingClientRect();te.style.position="fixed",te.style.left=`${Lt.left+Lt.width/2}px`,te.style.top=`${Lt.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Ct=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};V.addEventListener("mouseenter",Oe),V.addEventListener("mouseleave",Ct),b.addEventListener("focus",Oe),b.addEventListener("blur",Ct),V._cleanupTooltip=()=>{Ct(),V.removeEventListener("mouseenter",Oe),V.removeEventListener("mouseleave",Ct),b.removeEventListener("focus",Oe),b.removeEventListener("blur",Ct)}}return a!=="top-right"&&e.appendChild(V),{header:e,iconHolder:v,headerTitle:f,headerSubtitle:w,closeButton:b,closeButtonWrapper:V,clearChatButton:C,clearChatButtonWrapper:W}},En=(t,n,r)=>{var i,a,u,c;let e=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=e.closeButtonPlacement)!=null?a:"inline",s=(c=(u=e.clearChat)==null?void 0:u.placement)!=null?c:"inline";t.appendChild(n.header),o==="top-right"&&(t.style.position="relative",t.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(n.clearChatButtonWrapper))};var Ar=t=>an({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),Er=t=>{var S,x,E,C;let{config:n,showClose:r=!0,onClose:e}=t,o=(S=n==null?void 0:n.launcher)!=null?S:{},s=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=g("span","tvw-text-base tvw-font-semibold");i.textContent=(x=o.title)!=null?x:"Chat Assistant",s.appendChild(i);let a=(E=o.closeButtonSize)!=null?E:"32px",u=g("div",""),c=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=a,c.style.width=a,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=r?"":"none";let v=(C=o.closeButtonIconName)!=null?C:"x",d=oe(v,"20px",o.closeButtonColor||"",2);d?c.appendChild(d):c.textContent="\xD7",e&&c.addEventListener("click",e),u.appendChild(c),s.appendChild(u);let f=g("div");f.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:w,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Tr=t=>{var b,N,M,R,ne,Y,_,q;let{config:n,showClose:r=!0,onClose:e,onClearChat:o}=t,s=(b=n==null?void 0:n.launcher)!=null?b:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),u=(N=s.headerIconSize)!=null?N:"56px",c=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=u,c.style.width=u;let v=s.headerIconName;if(v){let U=parseFloat(u)||24,ue=oe(v,U*.5,"#ffffff",2);ue?c.replaceChildren(ue):c.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}"}else if(s.iconUrl){let U=g("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=u,U.style.width=u,c.replaceChildren(U)}else c.textContent=(R=s.agentIconText)!=null?R:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col tvw-flex-1"),f=g("span","tvw-text-lg tvw-font-semibold");f.textContent=(ne=s.title)!=null?ne:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(Y=s.subtitle)!=null?Y:"Here to help you get answers fast",d.append(f,w),a.append(c,d);let S=(_=s.closeButtonSize)!=null?_:"32px",x=g("div",""),E=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");E.style.height=S,E.style.width=S,E.type="button",E.setAttribute("aria-label","Close chat"),E.style.display=r?"":"none";let C=(q=s.closeButtonIconName)!=null?q:"x",W=oe(C,"20px",s.closeButtonColor||"",2);W?E.appendChild(W):E.textContent="\xD7",e&&E.addEventListener("click",e),x.appendChild(E),a.appendChild(x),i.appendChild(a);let V=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return V.textContent="Online and ready to help",i.appendChild(V),{header:i,iconHolder:c,headerTitle:f,headerSubtitle:w,closeButton:E,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}},tr={default:Ar,minimal:Er,expanded:Tr},Mr=t=>{var n;return(n=tr[t])!=null?n:tr.default},Fn=(t,n,r)=>{var i,a,u;if(n!=null&&n.render){let c=n.render({config:t,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),v=g("div");v.style.display="none";let d=g("span"),f=g("span"),w=g("button");w.style.display="none";let S=g("div");return S.style.display="none",{header:c,iconHolder:v,headerTitle:d,headerSubtitle:f,closeButton:w,closeButtonWrapper:S,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=n==null?void 0:n.layout)!=null?i:"default",s=Mr(e)({config:t,showClose:(u=(a=n==null?void 0:n.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?u:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ja=t=>{switch(t){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'}},On=t=>{var $e,Se,se,he,Fe,Xe,Et,pe,G,pt,gt,vt,Dt,yt,Q,We,bt,xt,te,Oe,Ct,Wt,Lt,j,et,Ie,K,O,we,de;let{config:n}=t,r=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=g("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=g("textarea");s.placeholder=(Se=($e=n==null?void 0:n.copy)==null?void 0:$e.inputPlaceholder)!=null?Se:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none tvw-composer-textarea",s.rows=1;let i=(he=(se=n==null?void 0:n.theme)==null?void 0:se.inputFontFamily)!=null?he:"sans-serif",a=(Xe=(Fe=n==null?void 0:n.theme)==null?void 0:Fe.inputFontWeight)!=null?Xe:"400";s.style.fontFamily=ja(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let d=()=>{s.style.height="auto";let re=Math.min(s.scrollHeight,v);s.style.height=`${re}px`};s.addEventListener("input",d),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let f=(Et=n==null?void 0:n.sendButton)!=null?Et:{},w=(pe=f.useIcon)!=null?pe:!1,S=(G=f.iconText)!=null?G:"\u2191",x=f.iconName,E=(pt=f.tooltipText)!=null?pt:"Send message",C=(gt=f.showTooltip)!=null?gt:!1,W=(vt=f.size)!=null?vt:"40px",V=f.backgroundColor,b=f.textColor,N=g("div","tvw-send-button-wrapper"),M=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(M.type="submit",w){if(M.style.width=W,M.style.height=W,M.style.minWidth=W,M.style.minHeight=W,M.style.fontSize="18px",M.style.lineHeight="1",M.innerHTML="",x){let re=parseFloat(W)||24,Me=b&&typeof b=="string"&&b.trim()?b.trim():"currentColor",Ne=oe(x,re,Me,2);Ne?(M.appendChild(Ne),M.style.color=Me):(M.textContent=S,b?M.style.color=b:M.classList.add("tvw-text-white"))}else M.textContent=S,b?M.style.color=b:M.classList.add("tvw-text-white");V?M.style.backgroundColor=V:M.classList.add("tvw-bg-cw-primary")}else M.textContent=(yt=(Dt=n==null?void 0:n.copy)==null?void 0:Dt.sendButtonLabel)!=null?yt:"Send",b?M.style.color=b:M.classList.add("tvw-text-white");if(f.borderWidth&&(M.style.borderWidth=f.borderWidth,M.style.borderStyle="solid"),f.borderColor&&(M.style.borderColor=f.borderColor),f.paddingX?(M.style.paddingLeft=f.paddingX,M.style.paddingRight=f.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),f.paddingY?(M.style.paddingTop=f.paddingY,M.style.paddingBottom=f.paddingY):(M.style.paddingTop="",M.style.paddingBottom=""),C&&E){let re=g("div","tvw-send-button-tooltip");re.textContent=E,N.appendChild(re)}N.appendChild(M);let R=(Q=n==null?void 0:n.voiceRecognition)!=null?Q:{},ne=R.enabled===!0,Y=null,_=null,q=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(ne&&q){_=g("div","tvw-send-button-wrapper"),Y=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),Y.type="button",Y.setAttribute("aria-label","Start voice recognition");let re=(We=R.iconName)!=null?We:"mic",Me=(bt=R.iconSize)!=null?bt:W,Ne=parseFloat(Me)||24,J=(xt=R.backgroundColor)!=null?xt:V,le=(te=R.iconColor)!=null?te:b;Y.style.width=Me,Y.style.height=Me,Y.style.minWidth=Me,Y.style.minHeight=Me,Y.style.fontSize="18px",Y.style.lineHeight="1";let Be=le||"currentColor",Je=oe(re,Ne,Be,1.5);Je?(Y.appendChild(Je),Y.style.color=Be):(Y.textContent="\u{1F3A4}",Y.style.color=Be),J?Y.style.backgroundColor=J:Y.classList.add("tvw-bg-cw-primary"),le?Y.style.color=le:!le&&!b&&Y.classList.add("tvw-text-white"),R.borderWidth&&(Y.style.borderWidth=R.borderWidth,Y.style.borderStyle="solid"),R.borderColor&&(Y.style.borderColor=R.borderColor),R.paddingX&&(Y.style.paddingLeft=R.paddingX,Y.style.paddingRight=R.paddingX),R.paddingY&&(Y.style.paddingTop=R.paddingY,Y.style.paddingBottom=R.paddingY),_.appendChild(Y);let ot=(Oe=R.tooltipText)!=null?Oe:"Start voice recognition";if(((Ct=R.showTooltip)!=null?Ct:!1)&&ot){let it=g("div","tvw-send-button-tooltip");it.textContent=ot,_.appendChild(it)}}let U=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},ue=U.enabled===!0,B=null,Z=null,P=null,z=null;if(ue){z=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),z.style.display="none",P=g("input"),P.type="file",P.accept=((Lt=U.allowedTypes)!=null?Lt:gn).join(","),P.multiple=((j=U.maxFiles)!=null?j:4)>1,P.style.display="none",P.setAttribute("aria-label","Attach files"),Z=g("div","tvw-send-button-wrapper"),B=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),B.type="button",B.setAttribute("aria-label",(et=U.buttonTooltipText)!=null?et:"Attach file");let re=(Ie=U.buttonIconName)!=null?Ie:"paperclip",Me=W,Ne=parseFloat(Me)||40,J=Math.round(Ne*.6);B.style.width=Me,B.style.height=Me,B.style.minWidth=Me,B.style.minHeight=Me,B.style.fontSize="18px",B.style.lineHeight="1",B.style.backgroundColor="transparent",B.style.color="var(--cw-primary, #111827)",B.style.border="none",B.style.borderRadius="6px",B.style.transition="background-color 0.15s ease",B.addEventListener("mouseenter",()=>{B.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),B.addEventListener("mouseleave",()=>{B.style.backgroundColor="transparent"});let le=oe(re,J,"currentColor",1.5);le?B.appendChild(le):B.textContent="\u{1F4CE}",B.addEventListener("click",ot=>{ot.preventDefault(),P==null||P.click()}),Z.appendChild(B);let Be=(K=U.buttonTooltipText)!=null?K:"Attach file",Je=g("div","tvw-send-button-tooltip");Je.textContent=Be,Z.appendChild(Je)}o.addEventListener("click",re=>{re.target!==M&&re.target!==N&&re.target!==Y&&re.target!==_&&re.target!==B&&re.target!==Z&&s.focus()}),z&&(z.style.gap="8px",o.append(z)),P&&o.append(P),o.append(s);let Ce=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),fe=g("div","tvw-flex tvw-items-center tvw-gap-2");Z&&fe.append(Z);let ze=g("div","tvw-flex tvw-items-center tvw-gap-1");_&&ze.append(_),ze.append(N),Ce.append(fe,ze),o.append(Ce);let dt=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Mt=(O=n==null?void 0:n.statusIndicator)!=null?O:{},Nt=(we=Mt.visible)!=null?we:!0;return dt.style.display=Nt?"":"none",dt.textContent=(de=Mt.idleText)!=null?de:"Online",r.append(e,o,dt),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:M,sendButtonWrapper:N,micButton:Y,micButtonWrapper:_,statusText:dt,attachmentButton:B,attachmentButtonWrapper:Z,attachmentInput:P,attachmentPreviewsContainer:z,actionsRow:Ce,leftActions:fe,rightActions:ze}};var Yi=t=>{var u,c,v,d,f,w,S;if(!((c=(u=t==null?void 0:t.launcher)==null?void 0:u.enabled)!=null?c:!0)){let x=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),E=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),C=(d=(v=t==null?void 0:t.launcher)==null?void 0:v.width)!=null?d:"100%";return x.style.width=C,E.style.width="100%",x.appendChild(E),{wrapper:x,panel:E}}let r=(f=t==null?void 0:t.launcher)!=null?f:{},e=r.position&&Jt[r.position]?Jt[r.position]:Jt["bottom-right"],o=g("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(S=(w=t==null?void 0:t.launcher)==null?void 0:w.width)!=null?S:t==null?void 0:t.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},Vi=(t,n=!0)=>{var w,S,x,E,C,W,V;let r=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),e=(w=t==null?void 0:t.layout)==null?void 0:w.header,o=((S=t==null?void 0:t.layout)==null?void 0:S.showHeader)!==!1,s=e?Fn(t,e,{showClose:n}):an({config:t,showClose:n}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),u=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");u.textContent=(E=(x=t==null?void 0:t.copy)==null?void 0:x.welcomeTitle)!=null?E:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(W=(C=t==null?void 0:t.copy)==null?void 0:C.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",a.append(u,c);let v=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let d=On({config:t}),f=((V=t==null?void 0:t.layout)==null?void 0:V.showFooter)!==!1;return o?En(r,s,t):(s.header.style.display="none",En(r,s,t)),r.append(i),f||(d.footer.style.display="none"),r.append(d.footer),{container:r,body:i,messagesWrapper:v,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:u,introSubtitle:c,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:d.footer,attachmentButton:d.attachmentButton,attachmentButtonWrapper:d.attachmentButtonWrapper,attachmentInput:d.attachmentInput,attachmentPreviewsContainer:d.attachmentPreviewsContainer,actionsRow:d.actionsRow,leftActions:d.leftActions,rightActions:d.rightActions}};var qa=320,Ua=320,za=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Ja=(t,n,r)=>{if(t.length===0)return null;try{let e=g("div","tvw-flex tvw-flex-col tvw-gap-2");e.setAttribute("data-message-attachments","images"),n&&(e.style.marginBottom="8px");let o=0,s=!1,i=()=>{s||(s=!0,e.remove(),r==null||r())};return t.forEach((a,u)=>{var d;let c=g("img");c.alt=((d=a.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${qa}px`,c.style.maxHeight=`${Ua}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--cw-container, #f3f4f6)",c.style.border="1px solid var(--cw-border, #e5e7eb)";let v=!1;o+=1,c.addEventListener("error",()=>{v||(v=!0,o=Math.max(0,o-1),c.remove(),o===0&&i())}),c.addEventListener("load",()=>{v=!0}),c.src=a.image,e.appendChild(c)}),o===0?(i(),null):e}catch{return r==null||r(),null}},Tn=()=>{let t=document.createElement("div");t.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",t.appendChild(n),t.appendChild(r),t.appendChild(e),t.appendChild(o),t},Lr=(t,n,r)=>{let e={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:Tn};if(n){let o=n(e);if(o!==null)return o}return Tn()},Ka=(t,n)=>{let r=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=n==="user"?t.userAvatar:t.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let o=g("img");o.src=e,o.alt=n==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=e,r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=n==="user"?"U":"A",r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Xi=(t,n)=>{let r=g("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(t.createdAt);return n.format?r.textContent=n.format(e):r.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Ya=(t,n="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":t==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),t==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),t==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},Ir=(t,n,r)=>{var w,S,x,E,C,W;let e=(w=n.showCopy)!=null?w:!0,o=(S=n.showUpvote)!=null?S:!0,s=(x=n.showDownvote)!=null?x:!0,i=(E=n.visibility)!=null?E:"hover",a=(C=n.align)!=null?C:"right",u=(W=n.layout)!=null?W:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],v={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[u],d=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);d.id=`actions-${t.id}`,d.setAttribute("data-actions-for",t.id);let f=(V,b,N)=>{let M=document.createElement("button");M.className="tvw-message-action-btn",M.setAttribute("aria-label",b),M.setAttribute("title",b),M.setAttribute("data-action",N);let R=oe(V,14,"currentColor",2);return R&&M.appendChild(R),M};return e&&d.appendChild(f("copy","Copy message","copy")),o&&d.appendChild(f("thumbs-up","Upvote","upvote")),s&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},Nn=(t,n,r,e,o,s)=>{var _,q,U,ue,B,Z,P;let i=r!=null?r:{},a=(_=i.layout)!=null?_:"bubble",u=i.avatar,c=i.timestamp,v=(q=u==null?void 0:u.show)!=null?q:!1,d=(U=c==null?void 0:c.show)!=null?U:!1,f=(ue=u==null?void 0:u.position)!=null?ue:"left",w=(B=c==null?void 0:c.position)!=null?B:"below",S=Ya(t.role,a),x=g("div",S.join(" "));x.id=`bubble-${t.id}`,x.setAttribute("data-message-id",t.id);let E=za(t),C=(P=(Z=t.content)==null?void 0:Z.trim())!=null?P:"",V=E.length>0&&C===Xs,b=document.createElement("div"),N=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),M=null;if(V?(M=document.createElement("div"),M.innerHTML=N,M.style.display="none",b.appendChild(M)):b.innerHTML=N,d&&w==="inline"&&t.createdAt){let z=Xi(t,c);z.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(z)}if(E.length>0){let z=Ja(E,!V&&!!C,()=>{V&&M&&(M.style.display="")});z?x.appendChild(z):V&&M&&(M.style.display="")}if(x.appendChild(b),d&&w==="below"&&t.createdAt){let z=Xi(t,c);z.classList.add("tvw-mt-1"),x.appendChild(z)}if(t.streaming&&t.role==="assistant"&&(!t.content||!t.content.trim())){let z=Lr("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);z&&x.appendChild(z)}if(t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let z=Ir(t,e,o);x.appendChild(z)}if(!v||t.role==="system")return x;let ne=g("div",`tvw-flex tvw-gap-2 ${t.role==="user"?"tvw-flex-row-reverse":""}`),Y=Ka(u,t.role);return f==="right"||f==="left"&&t.role==="user"?ne.append(x,Y):ne.append(Y,x),x.classList.remove("tvw-max-w-[85%]"),x.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),ne},Gi=(t,n,r,e,o,s)=>{let i=r!=null?r:{};return t.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:t,config:{},streaming:!!t.streaming}):t.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:t,config:{},streaming:!!t.streaming}):Nn(t,n,r,e,o,s)};var Dn=new Set,Qi=(t,n)=>{let r=Dn.has(t),e=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".tvw-border-t");if(!e||!o)return;e.setAttribute("aria-expanded",r?"true":"false");let s=e.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let u=oe(r?"chevron-up":"chevron-down",16,"currentColor",2);u?i.appendChild(u):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},kr=t=>{let n=t.reasoning,r=g("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),!n)return r;let e=Dn.has(t.id),o=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=ki(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let u=g("div","tvw-flex tvw-items-center"),v=oe(e?"chevron-up":"chevron-down",16,"currentColor",2);v?u.appendChild(v):u.textContent=e?"Hide":"Show";let d=g("div","tvw-flex tvw-items-center tvw-ml-auto");d.append(u),o.append(s,d);let f=g("div","tvw-border-t tvw-px-4 tvw-py-3");f.style.display=e?"":"none";let w=n.chunks.join(""),S=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return S.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(S),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),u.innerHTML="";let C=oe(e?"chevron-up":"chevron-down",16,"currentColor",2);C?u.appendChild(C):u.textContent=e?"Hide":"Show",f.style.display=e?"":"none"})(),r.append(o,f),r};var _n=new Set,Zi=(t,n,r)=>{var c;let e=_n.has(t),o=(c=r==null?void 0:r.toolCall)!=null?c:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",e?"true":"false");let a=s.querySelector(".tvw-ml-auto"),u=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(u){u.innerHTML="";let v=o.toggleTextColor||o.headerTextColor||"currentColor",d=oe(e?"chevron-up":"chevron-down",16,v,2);d?u.appendChild(d):u.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},Wr=(t,n)=>{var x;let r=t.toolCall,e=(x=n==null?void 0:n.toolCall)!=null?x:{},o=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=_n.has(t.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),u=g("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(u.style.color=e.headerTextColor),u.textContent=Wi(r),a.appendChild(u);let c=g("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",d=oe(s?"chevron-up":"chevron-down",16,v,2);d?c.appendChild(d):c.textContent=s?"Hide":"Show";let f=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(c),i.append(a,f);let w=g("div","tvw-border-t tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",e.contentBackgroundColor&&(w.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(w.style.color=e.contentTextColor),e.contentPaddingX&&(w.style.paddingLeft=e.contentPaddingX,w.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(w.style.paddingTop=e.contentPaddingY,w.style.paddingBottom=e.contentPaddingY),r.name){let E=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?E.style.color=e.contentTextColor:e.headerTextColor&&(E.style.color=e.headerTextColor),E.textContent=r.name,w.appendChild(E)}if(r.args!==void 0){let E=g("div","tvw-space-y-1"),C=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(C.style.color=e.labelTextColor),C.textContent="Arguments";let W=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=xs(r.args),E.append(C,W),w.appendChild(E)}if(r.chunks&&r.chunks.length){let E=g("div","tvw-space-y-1"),C=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(C.style.color=e.labelTextColor),C.textContent="Activity";let W=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=r.chunks.join(`
|
|
16
|
+
`),E.append(C,W),w.appendChild(E)}if(r.status==="complete"&&r.result!==void 0){let E=g("div","tvw-space-y-1"),C=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(C.style.color=e.labelTextColor),C.textContent="Result";let W=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=xs(r.result),E.append(C,W),w.appendChild(E)}if(r.status==="complete"&&typeof r.duration=="number"){let E=g("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(E.style.color=e.contentTextColor),E.textContent=`Duration: ${r.duration}ms`,w.appendChild(E)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let E=e.toggleTextColor||e.headerTextColor||"currentColor",C=oe(s?"chevron-up":"chevron-down",16,E,2);C?c.appendChild(C):c.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var Pr=(t,n)=>{var x,E,C,W,V,b,N,M,R,ne,Y;let r=t.approval,e=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=g("div",["vanilla-message-bubble","vanilla-approval-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-border","tvw-shadow-sm","tvw-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),e!=null&&e.backgroundColor&&(s.style.backgroundColor=e.backgroundColor),e!=null&&e.borderColor&&(s.style.borderColor=e.borderColor),!r)return s;let i=g("div","tvw-flex tvw-items-start tvw-gap-3 tvw-px-4 tvw-py-3"),a=g("div","tvw-flex-shrink-0 tvw-mt-0.5");a.setAttribute("data-approval-icon","true");let u=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",c=r.status==="approved"?"#16a34a":r.status==="denied"?"#dc2626":r.status==="timeout"?"#ca8a04":(x=e==null?void 0:e.titleColor)!=null?x:"currentColor",v=oe(u,20,c,2);v&&a.appendChild(v);let d=g("div","tvw-flex-1 tvw-min-w-0"),f=g("div","tvw-flex tvw-items-center tvw-gap-2"),w=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary");if(e!=null&&e.titleColor&&(w.style.color=e.titleColor),w.textContent=(E=e==null?void 0:e.title)!=null?E:"Approval Required",f.appendChild(w),!o){let _=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");_.setAttribute("data-approval-status",r.status),r.status==="approved"?(_.className+=" tvw-approval-badge-approved",_.textContent="Approved"):r.status==="denied"?(_.className+=" tvw-approval-badge-denied",_.textContent="Denied"):r.status==="timeout"&&(_.className+=" tvw-approval-badge-timeout",_.textContent="Timeout"),f.appendChild(_)}d.appendChild(f);let S=g("p","tvw-text-sm tvw-mt-0.5 tvw-text-cw-muted");if(e!=null&&e.descriptionColor&&(S.style.color=e.descriptionColor),S.textContent=r.description,d.appendChild(S),r.parameters){let _=g("pre","tvw-mt-2 tvw-text-xs tvw-p-2 tvw-rounded tvw-overflow-x-auto tvw-max-h-32 tvw-bg-cw-container tvw-text-cw-primary");e!=null&&e.parameterBackgroundColor&&(_.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(_.style.color=e.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=xs(r.parameters),d.appendChild(_)}if(o){let _=g("div","tvw-flex tvw-gap-2 tvw-mt-2");_.setAttribute("data-approval-buttons","true");let q=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-border-none tvw-cursor-pointer");q.type="button",q.style.backgroundColor=(C=e==null?void 0:e.approveButtonColor)!=null?C:"#16a34a",q.style.color=(W=e==null?void 0:e.approveButtonTextColor)!=null?W:"#ffffff",q.setAttribute("data-approval-action","approve");let U=oe("shield-check",14,(V=e==null?void 0:e.approveButtonTextColor)!=null?V:"#ffffff",2);U&&(U.style.marginRight="4px",q.appendChild(U));let ue=document.createTextNode((b=e==null?void 0:e.approveLabel)!=null?b:"Approve");q.appendChild(ue);let B=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-cursor-pointer");B.type="button",B.style.backgroundColor=(N=e==null?void 0:e.denyButtonColor)!=null?N:"transparent",B.style.color=(M=e==null?void 0:e.denyButtonTextColor)!=null?M:"#dc2626",B.style.border=`1px solid ${(R=e==null?void 0:e.denyButtonTextColor)!=null?R:"#fca5a5"}`,B.setAttribute("data-approval-action","deny");let Z=oe("shield-x",14,(ne=e==null?void 0:e.denyButtonTextColor)!=null?ne:"#dc2626",2);Z&&(Z.style.marginRight="4px",B.appendChild(Z));let P=document.createTextNode((Y=e==null?void 0:e.denyLabel)!=null?Y:"Deny");B.appendChild(P),_.append(q,B),d.appendChild(_)}return i.append(a,d),s.appendChild(i),s};var ea=t=>{let n=[];return{buttons:n,render:(e,o,s,i,a)=>{if(t.innerHTML="",n.length=0,!e||!e.length||(i!=null?i:o?o.getMessages():[]).some(w=>w.role==="user"))return;let v=document.createDocumentFragment(),d=o?o.isStreaming():!1,f=w=>{switch(w){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'}};e.forEach(w=>{let S=g("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");S.type="button",S.textContent=w,S.disabled=d,a!=null&&a.fontFamily&&(S.style.fontFamily=f(a.fontFamily)),a!=null&&a.fontWeight&&(S.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(S.style.paddingLeft=a.paddingX,S.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(S.style.paddingTop=a.paddingY,S.style.paddingBottom=a.paddingY),S.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),v.appendChild(S),n.push(S)}),t.appendChild(v)}}};var Ss=class{constructor(n=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=r}push(n){var r;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(r=this.store)==null||r.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let r=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let e of r)this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(e.type);return this.totalCaptured=n.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let r=this.getAll();return n>=r.length?r:r.slice(r.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var As=class{constructor(n="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=r}open(){return new Promise((n,r)=>{try{let e=indexedDB.open(this.dbName,1);e.onupgradeneeded=()=>{let o=e.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},e.onsuccess=()=>{this.db=e.result,n()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)e.put(o)}catch{}}getAll(){return new Promise((n,r)=>{if(!this.db){n([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{n(i.result)},i.onerror=()=>{r(i.error)}}catch(e){r(e)}})}getCount(){return new Promise((n,r)=>{if(!this.db){n(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}clear(){return new Promise((n,r)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,r)=>{try{let e=indexedDB.deleteDatabase(this.dbName);e.onsuccess=()=>{n()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)e.put(o)}catch{}}};function jn(t,n){n&&n.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var Va={flow_:{bg:"#dcfce7",text:"#166534"},step_:{bg:"#dbeafe",text:"#1e40af"},reason_:{bg:"#ffedd5",text:"#9a3412"},tool_:{bg:"#f3e8ff",text:"#6b21a8"},agent_:{bg:"#ccfbf1",text:"#115e59"},error:{bg:"#fecaca",text:"#991b1b"}},Xa={bg:"#f3f4f6",text:"#4b5563"},Ga=["flowName","stepName","reasoningText","text","name","tool","toolName"],Qa=100;function Za(t,n){let r={...Va,...n};if(r[t])return r[t];for(let e of Object.keys(r))if(e.endsWith("_")&&t.startsWith(e))return r[e];return Xa}function el(t,n){return`+${((t-n)/1e3).toFixed(3)}s`}function tl(t){let n=new Date(t),r=String(n.getHours()).padStart(2,"0"),e=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${r}:${e}:${o}.${s}`}function nl(t,n){try{let r=JSON.parse(t);if(typeof r!="object"||r===null)return null;for(let e of n){let o=e.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function sl(t){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(t):new Promise(r=>{let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),r()})}function rl(t){let n;try{n=JSON.parse(t.payload)}catch{n=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:n},null,2)}function ol(t,n,r){let e,o;try{o=JSON.parse(t.payload),e=JSON.stringify(o,null,2)}catch{o=t.payload,e=t.payload}let s=n.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:t,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=g("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),u=g("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return u.textContent=e,a.appendChild(u),a}}function Hr(t,n,r,e,o,s,i,a){var f;let u=o.has(t.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");jn(c,(f=e.classNames)==null?void 0:f.eventRow);let v=i.find(w=>w.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let w=v.renderEventStreamRow({event:t,index:n,config:a,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>s(t.id)});if(w)return c.appendChild(w),c}return c.appendChild(d()),c;function d(){var U,ue;let w=g("div",""),S=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-3 tvw-py-3 hover:tvw-bg-cw-container tvw-cursor-pointer tvw-group");S.setAttribute("data-event-id",t.id);let x=g("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),E=oe(u?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let C=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),W=(U=e.timestampFormat)!=null?U:"relative";C.textContent=W==="relative"?el(t.timestamp,r):tl(t.timestamp);let V=null;e.showSequenceNumbers!==!1&&(V=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),V.textContent=String(n+1));let b=Za(t.type,e.badgeColors),N=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded tvw-text-[11px] tvw-font-mono tvw-font-medium tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-border");N.style.backgroundColor=b.bg,N.style.color=b.text,N.style.borderColor=b.text+"50",N.textContent=t.type;let M=(ue=e.descriptionFields)!=null?ue:Ga,R=nl(t.payload,M),ne=null;R&&(ne=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),ne.textContent=R);let Y=g("div","tvw-flex-1 tvw-min-w-0"),_=g("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),q=oe("clipboard","12px","currentColor",1.5);return q&&_.appendChild(q),_.addEventListener("click",async B=>{B.stopPropagation(),await sl(rl(t)),_.innerHTML="";let Z=oe("check","12px","currentColor",1.5);Z&&_.appendChild(Z),setTimeout(()=>{_.innerHTML="";let P=oe("clipboard","12px","currentColor",1.5);P&&_.appendChild(P)},1500)}),S.appendChild(x),S.appendChild(C),V&&S.appendChild(V),S.appendChild(N),ne&&S.appendChild(ne),S.appendChild(Y),S.appendChild(_),w.appendChild(S),u&&w.appendChild(ol(t,i,a)),w}}function ta(t){var c,v;let{buffer:n,getFullHistory:r,onClose:e,config:o,plugins:s=[]}=t,i=(v=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?v:{},a=s.find(d=>d.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let d=a.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>u().element,onClose:e});if(d)return{element:d,update:()=>{},destroy:()=>{}}}return u();function u(){let d=i.classNames,f=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");jn(f,d==null?void 0:d.panel);let w=[],S="",x="",E=null,C=[],W={},V=0,b=!1,N=0,M=0,R=!1,ne=null,Y=!1,_=0,q=new Set,U=new Map,ue="",B="",Z=null,P,z,Ce,fe,ze;function dt(){let K=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),O=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-4 tvw-py-3 tvw-pb-0 tvw-border-cw-divider tvw-bg-cw-surface tvw-overflow-hidden");jn(O,d==null?void 0:d.headerBar);let we=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");we.textContent="Events",P=g("span","tvw-text-[11px] tvw-font-mono tvw-bg-cw-container tvw-text-cw-muted tvw-px-2 tvw-py-0.5 tvw-rounded tvw-border tvw-border-cw-border"),P.textContent="0";let de=g("div","tvw-flex-1");z=g("select","tvw-text-xs tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded tvw-px-2.5 tvw-py-1 tvw-text-cw-primary tvw-cursor-pointer");let re=g("option","");re.value="",re.textContent="All events",z.appendChild(re),Ce=g("button","tvw-inline-flex tvw-items-center tvw-gap-1.5 tvw-rounded tvw-text-xs tvw-text-cw-muted hover:tvw-bg-cw-container hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border tvw-border-cw-border tvw-bg-cw-surface tvw-flex-shrink-0 tvw-px-2.5 tvw-py-1"),Ce.type="button",Ce.title="Copy All";let Ne=oe("clipboard-copy","12px","currentColor",1.5);Ne&&Ce.appendChild(Ne);let J=g("span","tvw-text-xs");J.textContent="Copy All",Ce.appendChild(J),O.appendChild(we),O.appendChild(P),O.appendChild(de),O.appendChild(z),O.appendChild(Ce);let le=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");jn(le,d==null?void 0:d.searchBar);let Be=oe("search","14px","var(--cw-muted, #9ca3af)",1.5),Je=g("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Be&&Je.appendChild(Be),fe=g("input","tvw-text-sm tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded-md tvw-pl-8 tvw-pr-3 tvw-py-1 tvw-w-full tvw-text-cw-primary"),jn(fe,d==null?void 0:d.searchInput),fe.type="text",fe.placeholder="Search event payloads...",ze=g("button","tvw-absolute tvw-right-5 tvw-top-1/2 tvw--translate-y-1/2 tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-0 tvw-leading-none"),ze.type="button",ze.style.display="none";let ot=oe("x","12px","currentColor",2);return ot&&ze.appendChild(ot),le.appendChild(Je),le.appendChild(fe),le.appendChild(ze),K.appendChild(O),K.appendChild(le),K}let Mt,Nt=s.find(K=>K.renderEventStreamToolbar);if(Nt!=null&&Nt.renderEventStreamToolbar&&o){let K=Nt.renderEventStreamToolbar({config:o,defaultRenderer:()=>dt(),eventCount:n.getSize(),filteredCount:0,onFilterChange:O=>{S=O,gt(),yt()},onSearchChange:O=>{x=O,gt(),yt()}});Mt=K!=null?K:dt()}else Mt=dt();let $e=g("div","tvw-text-xs tvw-text-cw-muted tvw-text-center tvw-py-0.5 tvw-px-4 tvw-bg-cw-container tvw-border-b tvw-border-cw-divider tvw-italic tvw-flex-shrink-0");$e.style.display="none";let Se=g("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),se=g("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");se.style.height="100%";let he=g("div","tvw-absolute tvw-bottom-3 tvw-left-1/2 tvw-transform tvw--translate-x-1/2 tvw-bg-cw-accent tvw-text-white tvw-text-xs tvw-px-3 tvw-py-1.5 tvw-rounded-full tvw-cursor-pointer tvw-shadow-md tvw-z-10 tvw-flex tvw-items-center tvw-gap-1");jn(he,d==null?void 0:d.scrollIndicator),he.style.display="none";let Fe=oe("arrow-down","12px","currentColor",2);Fe&&he.appendChild(Fe);let Xe=g("span","");he.appendChild(Xe);let Et=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");Et.style.display="none",Se.appendChild(se),Se.appendChild(Et),Se.appendChild(he),f.setAttribute("tabindex","0"),f.appendChild(Mt),f.appendChild($e),f.appendChild(Se);function pe(){let K=n.getAll(),O={};for(let J of K)O[J.type]=(O[J.type]||0)+1;let we=Object.keys(O).sort(),de=we.length!==C.length||!we.every((J,le)=>J===C[le]),re=!de&&we.some(J=>O[J]!==W[J]),Me=K.length!==Object.values(W).reduce((J,le)=>J+le,0);if(!de&&!re&&!Me||(C=we,W=O,!z))return;let Ne=z.value;if(z.options[0].textContent="All events",de){for(;z.options.length>1;)z.remove(1);for(let J of we){let le=g("option","");le.value=J,le.textContent=`${J} (${O[J]||0})`,z.appendChild(le)}Ne&&we.includes(Ne)?z.value=Ne:Ne&&(z.value="",S="")}else for(let J=1;J<z.options.length;J++){let le=z.options[J];le.textContent=`${le.value} (${O[le.value]||0})`}}function G(){let K=n.getAll();if(S&&(K=K.filter(O=>O.type===S)),x){let O=x.toLowerCase();K=K.filter(we=>we.type.toLowerCase().includes(O)||we.payload.toLowerCase().includes(O))}return K}function pt(){return S!==""||x!==""}function gt(){V=0,N=0,b=!1,he.style.display="none"}function vt(K){q.has(K)?q.delete(K):q.add(K),Z=K;let O=se.scrollTop,we=b;Y=!0,b=!0,yt(),se.scrollTop=O,b=we,Y=!1}function Dt(){return se.scrollHeight-se.scrollTop-se.clientHeight<=50}function yt(){M=Date.now(),R=!1,pe();let K=n.getEvictedCount();K>0?($e.textContent=`${K.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",w=G();let O=w.length,we=n.getSize()>0;P&&(P.textContent=String(n.getSize())),O===0&&we&&pt()?(Et.textContent=x?`No events matching '${x}'`:"No events matching filter",Et.style.display="",se.style.display="none"):(Et.style.display="none",se.style.display=""),Ce&&(Ce.title=pt()?`Copy Filtered (${O})`:"Copy All"),b&&O>V&&(N+=O-V,Xe.textContent=`${N} new event${N===1?"":"s"}`,he.style.display=""),V=O;let de=n.getAll(),re=de.length>0?de[0].timestamp:0,Me=new Set(w.map(le=>le.id));for(let le of q)Me.has(le)||q.delete(le);let Ne=S!==ue||x!==B,J=U.size===0&&w.length>0;if(Ne||J||w.length===0){se.innerHTML="",U.clear();let le=document.createDocumentFragment();for(let Be=0;Be<w.length;Be++){let Je=Hr(w[Be],Be,re,i,q,vt,s,o);U.set(w[Be].id,Je),le.appendChild(Je)}se.appendChild(le),ue=S,B=x,Z=null}else{if(Z!==null){let Be=U.get(Z);if(Be&&Be.parentNode===se){let Je=w.findIndex(ot=>ot.id===Z);if(Je>=0){let ot=Hr(w[Je],Je,re,i,q,vt,s,o);se.insertBefore(ot,Be),Be.remove(),U.set(Z,ot)}}Z=null}let le=new Set(w.map(Be=>Be.id));for(let[Be,Je]of U)le.has(Be)||(Je.remove(),U.delete(Be));for(let Be=0;Be<w.length;Be++){let Je=w[Be];if(!U.has(Je.id)){let ot=Hr(Je,Be,re,i,q,vt,s,o);U.set(Je.id,ot),se.appendChild(ot)}}}b||(se.scrollTop=se.scrollHeight)}function Q(){if(Date.now()-M>=Qa){ne!==null&&(cancelAnimationFrame(ne),ne=null),yt();return}R||(R=!0,ne=requestAnimationFrame(()=>{ne=null,yt()}))}let We=(K,O)=>{if(!Ce)return;Ce.innerHTML="";let we=oe(K,"12px","currentColor",1.5);we&&Ce.appendChild(we);let de=g("span","tvw-text-xs");de.textContent="Copy All",Ce.appendChild(de),setTimeout(()=>{Ce.innerHTML="";let re=oe("clipboard-copy","12px","currentColor",1.5);re&&Ce.appendChild(re);let Me=g("span","tvw-text-xs");Me.textContent="Copy All",Ce.appendChild(Me),Ce.disabled=!1},O)},bt=async()=>{if(Ce){Ce.disabled=!0;try{let K;pt()?K=w:K=r?await r():n.getAll();let O=K.map(we=>{try{return JSON.parse(we.payload)}catch{return we.payload}});await navigator.clipboard.writeText(JSON.stringify(O,null,2)),We("check",1500)}catch{We("x",1500)}}},xt=()=>{z&&(S=z.value,gt(),yt())},te=()=>{!fe||!ze||(ze.style.display=fe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{x=fe.value,gt(),yt()},150))},Oe=()=>{!fe||!ze||(fe.value="",x="",ze.style.display="none",E&&clearTimeout(E),gt(),yt())},Ct=()=>{if(Y)return;let K=se.scrollTop,O=K>_;_=K,Dt()&&O?(b=!1,N=0,he.style.display="none"):Dt()||(b=!0)},Wt=K=>{K.deltaY<0&&(b=!0)},Lt=()=>{se.scrollTop=se.scrollHeight,b=!1,N=0,he.style.display="none"},j=K=>{let O=K.target;if(!O||O.closest("button"))return;let we=O.closest("[data-event-id]");if(!we)return;let de=we.getAttribute("data-event-id");de&&vt(de)},et=K=>{if((K.metaKey||K.ctrlKey)&&K.key==="f"){K.preventDefault(),fe==null||fe.focus(),fe==null||fe.select();return}K.key==="Escape"&&(fe&&document.activeElement===fe?(Oe(),fe.blur(),f.focus()):e&&e())};Ce&&Ce.addEventListener("click",bt),z&&z.addEventListener("change",xt),fe&&fe.addEventListener("input",te),ze&&ze.addEventListener("click",Oe),se.addEventListener("scroll",Ct),se.addEventListener("wheel",Wt,{passive:!0}),se.addEventListener("click",j),he.addEventListener("click",Lt),f.addEventListener("keydown",et);function Ie(){E&&clearTimeout(E),ne!==null&&(cancelAnimationFrame(ne),ne=null),R=!1,U.clear(),Ce&&Ce.removeEventListener("click",bt),z&&z.removeEventListener("change",xt),fe&&fe.removeEventListener("input",te),ze&&ze.removeEventListener("click",Oe),se.removeEventListener("scroll",Ct),se.removeEventListener("wheel",Wt),se.removeEventListener("click",j),he.removeEventListener("click",Lt),f.removeEventListener("keydown",et)}return{element:f,update:Q,destroy:Ie}}}var na={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Br=(t,n,r,e)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var S,x,E;if(s.dataset.enhanced==="true")return;let i=(S=s.dataset.tvForm)!=null?S:"init";s.dataset.enhanced="true";let a=(x=na[i])!=null?x:na.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=g("div","tvw-space-y-1"),c=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,u.appendChild(c),a.description){let C=g("p","tvw-text-sm tvw-text-cw-muted");C.textContent=a.description,u.appendChild(C)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(C=>{var M,R;let W=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");W.htmlFor=`${n.id}-${i}-${C.name}`;let V=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");V.textContent=C.label,W.appendChild(V);let b=(M=C.type)!=null?M:"text",N;b==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=b),N.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",N.id=`${n.id}-${i}-${C.name}`,N.name=C.name,N.placeholder=(R=C.placeholder)!=null?R:"",C.required&&(N.required=!0),W.appendChild(N),v.appendChild(W)});let d=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(E=a.submitLabel)!=null?E:"Submit",d.appendChild(f),d.appendChild(w),v.appendChild(d),s.replaceChildren(u,v),v.addEventListener("submit",async C=>{var N,M;C.preventDefault();let W=(N=r.formEndpoint)!=null?N:"/form",V=new FormData(v),b={};V.forEach((R,ne)=>{b[ne]=R}),b.type=i,w.disabled=!0,f.textContent="Submitting\u2026";try{let R=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let ne=await R.json();f.textContent=(M=ne.message)!=null?M:"Thanks! We'll be in touch soon.",ne.success&&ne.nextPrompt&&await e.sendMessage(String(ne.nextPrompt))}catch(R){f.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Rr=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var e;let r=this.plugins.get(n);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let e=new Set(n.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...n].sort((s,i)=>{var a,u;return((a=i.priority)!=null?a:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},Es=new Rr;var $r={primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},Fr={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},tt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:$r,darkTheme:Fr,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function nr(t){var n,r,e,o,s,i,a,u,c,v,d,f,w,S,x,E,C,W,V;return t?{...tt,...t,theme:{...tt.theme,...t.theme},darkTheme:{...tt.darkTheme,...t.darkTheme},launcher:{...tt.launcher,...t.launcher,clearChat:{...(n=tt.launcher)==null?void 0:n.clearChat,...(r=t.launcher)==null?void 0:r.clearChat}},copy:{...tt.copy,...t.copy},sendButton:{...tt.sendButton,...t.sendButton},statusIndicator:{...tt.statusIndicator,...t.statusIndicator},voiceRecognition:{...tt.voiceRecognition,...t.voiceRecognition},features:{...tt.features,...t.features},suggestionChips:(e=t.suggestionChips)!=null?e:tt.suggestionChips,suggestionChipsConfig:{...tt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...tt.layout,...t.layout,header:{...(o=tt.layout)==null?void 0:o.header,...(s=t.layout)==null?void 0:s.header},messages:{...(i=tt.layout)==null?void 0:i.messages,...(a=t.layout)==null?void 0:a.messages,avatar:{...(c=(u=tt.layout)==null?void 0:u.messages)==null?void 0:c.avatar,...(d=(v=t.layout)==null?void 0:v.messages)==null?void 0:d.avatar},timestamp:{...(w=(f=tt.layout)==null?void 0:f.messages)==null?void 0:w.timestamp,...(x=(S=t.layout)==null?void 0:S.messages)==null?void 0:x.timestamp}},slots:{...(E=tt.layout)==null?void 0:E.slots,...(C=t.layout)==null?void 0:C.slots}},markdown:{...tt.markdown,...t.markdown,options:{...(W=tt.markdown)==null?void 0:W.options,...(V=t.markdown)==null?void 0:V.options}},messageActions:{...tt.messageActions,...t.messageActions}}:tt}var sa=()=>{let t=new Map,n=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=t.get(o))==null||i.delete(s)};return{on:n,off:r,emit:(o,s)=>{var i;(i=t.get(o))==null||i.forEach(a=>{try{a(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var il=t=>{let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:t},al=t=>{let n=t.trim(),r=n.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return n.slice(r,o+1)}return null},Ts=({text:t})=>{if(!t||!t.includes("{"))return null;try{let n=il(t),r=al(n);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},Or=t=>typeof t=="string"?t:t==null?"":String(t),Mn={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Or(t.payload.text)},messageAndClick:(t,n)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,e=Or(r.element);if(e&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Or(r.text)}}},ra=t=>Array.isArray(t)?t.map(n=>String(n)):[],Ms=t=>{let n=new Set(ra(t.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(ra(t.getSessionMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(n);t.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?t.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),e();let u={action:a,message:s.message};t.emit("action:detected",u);for(let c of t.handlers)if(c)try{let v=()=>{t.emit("action:resubmit",u)},d=c(a,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:v});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var ll=t=>{if(!t)return null;try{return JSON.parse(t)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},dl=t=>t.map(n=>({...n,streaming:!1})),sr=(t="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?ll(r.getItem(t)):null},save:r=>{let e=n();if(e)try{let o={...r,messages:r.messages?dl(r.messages):void 0};e.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(t)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Nr=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([r,e])=>{this.register(r,e)})}},qn=new Nr;var Un=require("partial-json");function cl(t){if(!t||typeof t!="object"||!("component"in t))return!1;let n=t.component;return typeof n=="string"&&n.length>0}function ul(t,n){if(!cl(t))return null;let r=t.props&&typeof t.props=="object"&&t.props!==null?t.props:{};return{component:t.component,props:r,raw:n}}function rr(){let t=null,n=0;return{getExtractedDirective:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t;try{let o=(0,Un.parse)(r,Un.STR|Un.OBJ),s=ul(o,r);s&&(t=s)}catch{}return n=r.length,t},reset:()=>{t=null,n=0}}}function oa(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function or(t,n){let{config:r,message:e,onPropsUpdate:o}=n,s=qn.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let i={message:e,config:r,updateProps:a=>{o&&o(a)}};try{return s(t.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,a),null}}function ia(){let t=rr();return{processChunk:n=>t.processChunk(n),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function ir(t){if(!t.rawContent)return!1;try{let n=JSON.parse(t.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ar(t){if(!t.rawContent)return null;try{let n=JSON.parse(t.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t.rawContent}}catch{}return null}var pl=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function lr(t){let{onSubmit:n,onDismiss:r,title:e="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:u=!0,ratingLabels:c=pl}=t,v=document.createElement("div");v.className="tvw-feedback-container tvw-feedback-csat",v.setAttribute("role","dialog"),v.setAttribute("aria-label","Customer satisfaction feedback");let d=null,f=document.createElement("div");f.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let S=document.createElement("h3");S.className="tvw-feedback-title",S.textContent=e,w.appendChild(S);let x=document.createElement("p");x.className="tvw-feedback-subtitle",x.textContent=o,w.appendChild(x),f.appendChild(w);let E=document.createElement("div");E.className="tvw-feedback-rating tvw-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];for(let M=1;M<=5;M++){let R=document.createElement("button");R.type="button",R.className="tvw-feedback-rating-btn tvw-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${M} star${M>1?"s":""}: ${c[M-1]}`),R.title=c[M-1],R.dataset.rating=String(M),R.innerHTML=`
|
|
17
17
|
<svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
18
18
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
19
19
|
</svg>
|
|
20
|
-
`,H.addEventListener("click",()=>{c=W,S.forEach((oe,_)=>{let le=_<W;oe.classList.toggle("selected",le),oe.setAttribute("aria-checked",_===W-1?"true":"false")})}),S.push(H),E.appendChild(H)}h.appendChild(E);let k=null;if(d){let W=document.createElement("div");W.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),W.appendChild(k),h.appendChild(W)}let V=document.createElement("div");V.className="tvw-feedback-actions";let y=document.createElement("button");y.type="button",y.className="tvw-feedback-btn tvw-feedback-btn-skip",y.textContent=a,y.addEventListener("click",()=>{r==null||r(),w.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(c===null){E.classList.add("tvw-feedback-shake"),setTimeout(()=>E.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let W=(k==null?void 0:k.value.trim())||void 0;await n(c,W),w.remove()}catch(W){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",W)}}),V.appendChild(y),V.appendChild(O),h.appendChild(V),w.appendChild(h),w}function Js(e){let{onSubmit:n,onDismiss:r,title:t="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:g="Not likely",highLabel:w="Very likely"}=e,c=document.createElement("div");c.className="tvw-feedback-container tvw-feedback-nps",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Net Promoter Score feedback");let h=null,f=document.createElement("div");f.className="tvw-feedback-content";let x=document.createElement("div");x.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=t,x.appendChild(C);let E=document.createElement("p");E.className="tvw-feedback-subtitle",E.textContent=o,x.appendChild(E),f.appendChild(x);let S=document.createElement("div");S.className="tvw-feedback-rating tvw-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="tvw-feedback-labels";let V=document.createElement("span");V.className="tvw-feedback-label-low",V.textContent=g;let y=document.createElement("span");y.className="tvw-feedback-label-high",y.textContent=w,k.appendChild(V),k.appendChild(y);let O=document.createElement("div");O.className="tvw-feedback-numbers";let W=[];for(let X=0;X<=10;X++){let U=document.createElement("button");U.type="button",U.className="tvw-feedback-rating-btn tvw-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${X} out of 10`),U.textContent=String(X),U.dataset.rating=String(X),X<=6?U.classList.add("tvw-feedback-detractor"):X<=8?U.classList.add("tvw-feedback-passive"):U.classList.add("tvw-feedback-promoter"),U.addEventListener("click",()=>{h=X,W.forEach((Se,N)=>{Se.classList.toggle("selected",N===X),Se.setAttribute("aria-checked",N===X?"true":"false")})}),W.push(U),O.appendChild(U)}S.appendChild(k),S.appendChild(O),f.appendChild(S);let H=null;if(d){let X=document.createElement("div");X.className="tvw-feedback-comment-container",H=document.createElement("textarea"),H.className="tvw-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),X.appendChild(H),f.appendChild(X)}let oe=document.createElement("div");oe.className="tvw-feedback-actions";let _=document.createElement("button");_.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-skip",_.textContent=a,_.addEventListener("click",()=>{r==null||r(),c.remove()});let le=document.createElement("button");return le.type="button",le.className="tvw-feedback-btn tvw-feedback-btn-submit",le.textContent=i,le.addEventListener("click",async()=>{if(h===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}le.disabled=!0,le.textContent="Submitting...";try{let X=(H==null?void 0:H.value.trim())||void 0;await n(h,X),c.remove()}catch(X){le.disabled=!1,le.textContent=i,console.error("[NPS Feedback] Failed to submit:",X)}}),oe.appendChild(_),oe.appendChild(le),f.appendChild(oe),c.appendChild(f),c}var _n="persona-chat-history",il=30*1e3;function al(e){var n,r,t,o,s,i,a,d,g;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(t=e.persist)==null?void 0:t.openState)!=null?o:!0,voiceState:(i=(s=e.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=e.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(g=e.clearOnChatClear)!=null?g:!0}:null}function ll(e){try{let n=e==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var br=e=>!e||typeof e!="object"?{}:{...e},ra=e=>e.map(n=>({...n,streaming:!1})),oa=(e,n,r)=>{let t=e!=null&&e.markdown?os(e.markdown):null;return o=>{var a,d,g;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(n){let w=n.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});w!==null&&(s=w.text,w.persist||(o.message.__skipPersist=!0),w.resubmit&&!o.streaming&&r&&r())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(g=i!=null?i:o.text)!=null?g:""}):t?t(s):Ms(s)}},Ks=(e,n,r)=>{var v,T,se,Ee,Ye,Lt,nt,Ct,gt,De,qe,lt,ze,xt,Rt,_t,Ar,Er,Tr,Mr,Lr,kr,Wr,Ir,Pr,Hr,Br,Rr,Fr,$r,Or,Nr;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let t=Ns(n),o=ds.getForInstance(t.plugins);t.components&&Dn.registerAll(t.components);let s=ea(),i=(v=t.storageAdapter)!=null?v:Ds(),a={},d=null,g=l=>{if(t.onStateLoaded)try{return t.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(u=>{let b=u!=null?u:{messages:[],metadata:{}};return g(b)});else{let u=l!=null?l:{messages:[],metadata:{}},b=g(u);b.metadata&&(a=br(b.metadata)),(T=b.messages)!=null&&T.length&&(t={...t,initialMessages:b.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(t.onStateLoaded)try{let l=g({messages:[],metadata:{}});(se=l.messages)!=null&&se.length&&(t={...t,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let w=()=>a,c=l=>{var b;a=(b=l({...a}))!=null?b:{},Yn()},h=t.actionParsers&&t.actionParsers.length?t.actionParsers:[cs],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[An.message,An.messageAndClick],x=us({parsers:h,handlers:f,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null});x.syncFromMetadata();let C=(Ye=(Ee=t.launcher)==null?void 0:Ee.enabled)!=null?Ye:!0,E=(nt=(Lt=t.launcher)==null?void 0:Lt.autoExpand)!=null?nt:!1,S=E,k=C,V=(gt=(Ct=t.layout)==null?void 0:Ct.header)==null?void 0:gt.layout,y=C?E:!0,O=!1,W=null,H=()=>{O=!0,W&&clearTimeout(W),W=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},oe=oa(t,x,H),_=(qe=(De=t.features)==null?void 0:De.showReasoning)!=null?qe:!0,le=(ze=(lt=t.features)==null?void 0:lt.showToolCalls)!=null?ze:!0,X=(Rt=(xt=t.features)==null?void 0:xt.showEventStreamToggle)!=null?Rt:!1,Se=`${(Ar=typeof t.persistState=="object"?(_t=t.persistState)==null?void 0:_t.keyPrefix:void 0)!=null?Ar:"persona-"}event-stream`,N=X?new ls(Se):null,re=(Mr=(Tr=(Er=t.features)==null?void 0:Er.eventStream)==null?void 0:Tr.maxEvents)!=null?Mr:2e3,D=X?new as(re,N):null,Z=null,ve=!1,pe=null,Ue=0;N==null||N.open().then(()=>D==null?void 0:D.restore()).catch(l=>{t.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let it={onCopy:l=>{var u,b;s.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(L=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",L)}),(b=(u=t.messageActions)==null?void 0:u.onCopy)==null||b.call(u,l)},onFeedback:l=>{var u,b;s.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(L=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",L)}),(b=(u=t.messageActions)==null?void 0:u.onFeedback)==null||b.call(u,l)}},Tt=(Lr=t.statusIndicator)!=null?Lr:{},$t=l=>{var u,b,L,A;return l==="idle"?(u=Tt.idleText)!=null?u:Pt.idle:l==="connecting"?(b=Tt.connectingText)!=null?b:Pt.connecting:l==="connected"?(L=Tt.connectedText)!=null?L:Pt.connected:l==="error"?(A=Tt.errorText)!=null?A:Pt.error:Pt[l]},{wrapper:Fe,panel:Ae}=Ui(t),ee=Ji(t,C),{container:ge,body:$e,messagesWrapper:Qe,suggestions:At,textarea:me,sendButton:J,sendButtonWrapper:ct,composerForm:ut,statusText:ft,introTitle:Ot,introSubtitle:wt,closeButton:Y,iconHolder:Ie,headerTitle:vt,headerSubtitle:yt,header:Q,footer:Oe,actionsRow:bt,leftActions:Wt,rightActions:Mt}=ee,j=ee.micButton,Ze=ee.micButtonWrapper,We=ee.attachmentButton,z=ee.attachmentButtonWrapper,R=ee.attachmentInput,he=ee.attachmentPreviewsContainer,ue=null;(kr=t.attachments)!=null&&kr.enabled&&R&&he&&(ue=Cn.fromConfig(t.attachments),ue.setPreviewsContainer(he),R.addEventListener("change",l=>{let u=l.target;ue==null||ue.handleFileSelect(u.files),u.value=""}));let te=o.find(l=>l.renderHeader);if(te!=null&&te.renderHeader){let l=te.renderHeader({config:t,defaultRenderer:()=>{let u=rn({config:t,showClose:C});return xn(ge,u,t),u.header},onClose:()=>tt(!1,"user")});if(l){let u=ge.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),Q=l)}}let Le=()=>{var u,b,L,A;if(!D)return;if(ve=!0,!Z&&D&&(Z=Qi({buffer:D,getFullHistory:()=>D.getAllFromStore(),onClose:()=>Ne(),config:t,plugins:o})),Z&&($e.style.display="none",(u=Oe.parentNode)==null||u.insertBefore(Z.element,Oe),Z.update()),q){q.classList.remove("tvw-text-cw-muted"),q.classList.add("tvw-text-cw-accent"),q.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let $=(A=(L=(b=t.features)==null?void 0:b.eventStream)==null?void 0:L.classNames)==null?void 0:A.toggleButtonActive;$&&$.split(/\s+/).forEach(ye=>ye&&q.classList.add(ye))}let l=()=>{if(!ve)return;let $=Date.now();$-Ue>=200&&(Z==null||Z.update(),Ue=$),pe=requestAnimationFrame(l)};Ue=0,pe=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},Ne=()=>{var l,u,b;if(ve){if(ve=!1,Z&&Z.element.remove(),$e.style.display="",q){q.classList.remove("tvw-text-cw-accent"),q.classList.add("tvw-text-cw-muted"),q.style.boxShadow="";let L=(b=(u=(l=t.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:b.toggleButtonActive;L&&L.split(/\s+/).forEach(A=>A&&q.classList.remove(A))}pe!==null&&(cancelAnimationFrame(pe),pe=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},q=null;if(X){let l=(Ir=(Wr=t.features)==null?void 0:Wr.eventStream)==null?void 0:Ir.classNames,u="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");q=p("button",u),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let b=ie("activity","18px","currentColor",1.5);b&&q.appendChild(b);let L=ee.clearChatButtonWrapper,A=ee.closeButtonWrapper,$=L||A;$&&$.parentNode===Q?Q.insertBefore(q,$):Q.appendChild(q),q.addEventListener("click",()=>{ve?Ne():Le()})}let de=o.find(l=>l.renderComposer);if(de!=null&&de.renderComposer){let l=de.renderComposer({config:t,defaultRenderer:()=>Rn({config:t}).footer,onSubmit:u=>{F&&!F.isStreaming()&&F.sendMessage(u)},disabled:!1});l&&(Oe.replaceWith(l),Oe=l)}(()=>{var L,A;let l=(A=(L=t.layout)==null?void 0:L.slots)!=null?A:{},u=$=>{switch($){case"body-top":return ge.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Qe;case"footer-top":return At;case"composer":return ut;case"footer-bottom":return ft;default:return null}},b=($,ye)=>{var ce;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Q.insertBefore(ye,Q.firstChild);else if($==="header-right")Q.appendChild(ye);else{let be=Q.querySelector(".tvw-flex-col");be?(ce=be.parentNode)==null||ce.insertBefore(ye,be.nextSibling):Q.appendChild(ye)}break;case"body-top":{let be=$e.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");be?be.replaceWith(ye):$e.insertBefore(ye,$e.firstChild);break}case"body-bottom":$e.appendChild(ye);break;case"footer-top":At.replaceWith(ye);break;case"footer-bottom":ft.replaceWith(ye);break;default:break}};for(let[$,ye]of Object.entries(l))if(ye)try{let ce=ye({config:t,defaultContent:()=>u($)});ce&&b($,ce)}catch(ce){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,ce)}})();let Je=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let L=b.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!L)return;let A=L.getAttribute("data-message-id");if(!A)return;let $=b.getAttribute("data-bubble-type");$==="reasoning"?($n.has(A)?$n.delete(A):$n.add(A),Vi(A,L)):$==="tool"&&(On.has(A)?On.delete(A):On.add(A),Xi(A,L,t))};Qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),Qe.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))});let st=new Map;Qe.addEventListener("click",l=>{var ye;let b=l.target.closest(".tvw-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let L=b.closest("[data-actions-for]");if(!L)return;let A=L.getAttribute("data-actions-for");if(!A)return;let $=b.getAttribute("data-action");if($==="copy"){let be=F.getMessages().find(Te=>Te.id===A);if(be&&it.onCopy){let Te=be.content||"";navigator.clipboard.writeText(Te).then(()=>{b.classList.add("tvw-message-action-success");let Ce=ie("check",14,"currentColor",2);Ce&&(b.innerHTML="",b.appendChild(Ce)),setTimeout(()=>{b.classList.remove("tvw-message-action-success");let Pe=ie("copy",14,"currentColor",2);Pe&&(b.innerHTML="",b.appendChild(Pe))},2e3)}).catch(Ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ce)}),it.onCopy(be)}}else if($==="upvote"||$==="downvote")if(((ye=st.get(A))!=null?ye:null)===$)st.delete(A),b.classList.remove("tvw-message-action-active");else{let Te=$==="upvote"?"downvote":"upvote",Ce=L.querySelector(`[data-action="${Te}"]`);Ce&&Ce.classList.remove("tvw-message-action-active"),st.set(A,$),b.classList.add("tvw-message-action-active");let G=F.getMessages().find(I=>I.id===A);G&&it.onFeedback&&it.onFeedback({type:$,messageId:G.id,message:G})}}),Ae.appendChild(ge),e.appendChild(Fe);let Tn=()=>{var we,xe,Ve,He,mt,It,K,je,Vt,zt,dn,Ss,er,dt,As,Zn;let l=(xe=(we=t.launcher)==null?void 0:we.sidebarMode)!=null?xe:!1,u=l||((He=(Ve=t.launcher)==null?void 0:Ve.fullHeight)!=null?He:!1),b=(mt=t.theme)!=null?mt:{},L=(K=(It=t.launcher)==null?void 0:It.position)!=null?K:"bottom-left",A=L==="bottom-left"||L==="top-left",$=l?"none":"1px solid var(--tvw-cw-border)",ye=l?A?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",ce=l?"0":"16px",be=(je=b.panelBorder)!=null?je:$,Te=(Vt=b.panelShadow)!=null?Vt:ye,Ce=(zt=b.panelBorderRadius)!=null?zt:ce;e.style.cssText="",Fe.style.cssText="",Ae.style.cssText="",ge.style.cssText="",$e.style.cssText="",Oe.style.cssText="";let Pe=(Ss=(dn=t==null?void 0:t.launcher)==null?void 0:dn.width)!=null?Ss:t==null?void 0:t.launcherWidth,G=Pe!=null?Pe:"min(400px, calc(100vw - 24px))";l||(Ae.style.width=G,Ae.style.maxWidth=G),Ae.style.boxShadow=Te,Ae.style.borderRadius=Ce,ge.style.border=be,ge.style.borderRadius=Ce;let I=((er=t.launcher)==null?void 0:er.enabled)===!1;if(u&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",Fe.style.display="flex",Fe.style.flexDirection="column",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.maxHeight="100%",Fe.style.height="100%",I&&(Fe.style.overflow="hidden"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",Ae.style.overflow="hidden",ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.overflow="hidden",$e.style.flex="1 1 0%",$e.style.minHeight="0",$e.style.overflowY="auto",Oe.style.flexShrink="0"),Fe.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!I&&((dt=Ut[L])!=null?dt:Ut["bottom-right"]).split(" ").forEach(wn=>Fe.classList.add(wn)),l){let fn=(Zn=(As=t.launcher)==null?void 0:As.sidebarWidth)!=null?Zn:"420px";Fe.style.cssText=`
|
|
20
|
+
`,R.addEventListener("click",()=>{d=M,C.forEach((ne,Y)=>{let _=Y<M;ne.classList.toggle("selected",_),ne.setAttribute("aria-checked",Y===M-1?"true":"false")})}),C.push(R),E.appendChild(R)}f.appendChild(E);let W=null;if(u){let M=document.createElement("div");M.className="tvw-feedback-comment-container",W=document.createElement("textarea"),W.className="tvw-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),M.appendChild(W),f.appendChild(M)}let V=document.createElement("div");V.className="tvw-feedback-actions";let b=document.createElement("button");b.type="button",b.className="tvw-feedback-btn tvw-feedback-btn-skip",b.textContent=a,b.addEventListener("click",()=>{r==null||r(),v.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(d===null){E.classList.add("tvw-feedback-shake"),setTimeout(()=>E.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let M=(W==null?void 0:W.value.trim())||void 0;await n(d,M),v.remove()}catch(M){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",M)}}),V.appendChild(b),V.appendChild(N),f.appendChild(V),v.appendChild(f),v}function dr(t){let{onSubmit:n,onDismiss:r,title:e="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:v="Very likely"}=t,d=document.createElement("div");d.className="tvw-feedback-container tvw-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,w=document.createElement("div");w.className="tvw-feedback-content";let S=document.createElement("div");S.className="tvw-feedback-header";let x=document.createElement("h3");x.className="tvw-feedback-title",x.textContent=e,S.appendChild(x);let E=document.createElement("p");E.className="tvw-feedback-subtitle",E.textContent=o,S.appendChild(E),w.appendChild(S);let C=document.createElement("div");C.className="tvw-feedback-rating tvw-feedback-rating-nps",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="tvw-feedback-labels";let V=document.createElement("span");V.className="tvw-feedback-label-low",V.textContent=c;let b=document.createElement("span");b.className="tvw-feedback-label-high",b.textContent=v,W.appendChild(V),W.appendChild(b);let N=document.createElement("div");N.className="tvw-feedback-numbers";let M=[];for(let q=0;q<=10;q++){let U=document.createElement("button");U.type="button",U.className="tvw-feedback-rating-btn tvw-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${q} out of 10`),U.textContent=String(q),U.dataset.rating=String(q),q<=6?U.classList.add("tvw-feedback-detractor"):q<=8?U.classList.add("tvw-feedback-passive"):U.classList.add("tvw-feedback-promoter"),U.addEventListener("click",()=>{f=q,M.forEach((ue,B)=>{ue.classList.toggle("selected",B===q),ue.setAttribute("aria-checked",B===q?"true":"false")})}),M.push(U),N.appendChild(U)}C.appendChild(W),C.appendChild(N),w.appendChild(C);let R=null;if(u){let q=document.createElement("div");q.className="tvw-feedback-comment-container",R=document.createElement("textarea"),R.className="tvw-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),q.appendChild(R),w.appendChild(q)}let ne=document.createElement("div");ne.className="tvw-feedback-actions";let Y=document.createElement("button");Y.type="button",Y.className="tvw-feedback-btn tvw-feedback-btn-skip",Y.textContent=a,Y.addEventListener("click",()=>{r==null||r(),d.remove()});let _=document.createElement("button");return _.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-submit",_.textContent=i,_.addEventListener("click",async()=>{if(f===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let q=(R==null?void 0:R.value.trim())||void 0;await n(f,q),d.remove()}catch(q){_.disabled=!1,_.textContent=i,console.error("[NPS Feedback] Failed to submit:",q)}}),ne.appendChild(Y),ne.appendChild(_),w.appendChild(ne),d.appendChild(w),d}var zn="persona-chat-history",gl=30*1e3,ml={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function fl(t){var e,o,s;if(!t)return[];let n=[],r=Array.from((e=t.items)!=null?e:[]);for(let i of r){if(i.kind!=="file"||!i.type.startsWith("image/"))continue;let a=i.getAsFile();if(!a)continue;if(a.name){n.push(a);continue}let u=(o=ml[a.type])!=null?o:"png";n.push(new File([a],`clipboard-image-${Date.now()}.${u}`,{type:a.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let i of Array.from((s=t.files)!=null?s:[]))i.type.startsWith("image/")&&n.push(i);return n}function hl(t){var n,r,e,o,s,i,a,u,c;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=t.storage)!=null?n:"session",keyPrefix:(r=t.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(e=t.persist)==null?void 0:e.openState)!=null?o:!0,voiceState:(i=(s=t.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(u=(a=t.persist)==null?void 0:a.focusInput)!=null?u:!0},clearOnChatClear:(c=t.clearOnChatClear)!=null?c:!0}:null}function wl(t){try{let n=t==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var Dr=t=>!t||typeof t!="object"?{}:{...t},aa=t=>t.map(n=>({...n,streaming:!1})),la=(t,n,r)=>{let e=t!=null&&t.markdown?bs(t.markdown):null;return o=>{var a,u,c;let s=(a=o.text)!=null?a:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let v=n.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});v!==null&&(s=v.text,v.persist||(o.message.__skipPersist=!0),v.resubmit&&!o.streaming&&r&&r())}return t!=null&&t.postprocessMessage?t.postprocessMessage({...o,text:s,raw:(c=i!=null?i:o.text)!=null?c:""}):e?e(s):qs(s)}},cr=(t,n,r)=>{var os,is,as,ls,ds,cs,us,ps,gs,D,ke,_e,at,mt,Tt,st,m,Pe,H,y,L,ie,Ae,Ye,It,rt,St,ft,De,qe,ct,Ue;t.id&&t.id!=="persona-root"&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.id="persona-root";let e=nr(n),o=Es.getForInstance(e.plugins);e.components&&qn.registerAll(e.components);let s=sa(),i=(os=e.storageAdapter)!=null?os:sr(),a={},u=null,c=l=>{if(e.onStateLoaded)try{return e.onStateLoaded(l)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")u=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return c(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=c(p);h.metadata&&(a=Dr(h.metadata)),(is=h.messages)!=null&&is.length&&(e={...e,initialMessages:h.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(e.onStateLoaded)try{let l=c({messages:[],metadata:{}});(as=l.messages)!=null&&as.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,d=l=>{var h;a=(h=l({...a}))!=null?h:{},Gn()},f=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ts],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Mn.message,Mn.messageAndClick],S=Ms({parsers:f,handlers:w,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let x=(ds=(ls=e.launcher)==null?void 0:ls.enabled)!=null?ds:!0,E=(us=(cs=e.launcher)==null?void 0:cs.autoExpand)!=null?us:!1,C=E,W=x,V=(gs=(ps=e.layout)==null?void 0:ps.header)==null?void 0:gs.layout,b=x?E:!0,N=!1,M=null,R=()=>{N=!0,M&&clearTimeout(M),M=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},ne=la(e,S,R),Y=(ke=(D=e.features)==null?void 0:D.showReasoning)!=null?ke:!0,_=(at=(_e=e.features)==null?void 0:_e.showToolCalls)!=null?at:!0,q=(Tt=(mt=e.features)==null?void 0:mt.showEventStreamToggle)!=null?Tt:!1,ue=`${(m=typeof e.persistState=="object"?(st=e.persistState)==null?void 0:st.keyPrefix:void 0)!=null?m:"persona-"}event-stream`,B=q?new As(ue):null,Z=(y=(H=(Pe=e.features)==null?void 0:Pe.eventStream)==null?void 0:H.maxEvents)!=null?y:2e3,P=q?new Ss(Z,B):null,z=null,Ce=!1,fe=null,ze=0;B==null||B.open().then(()=>P==null?void 0:P.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let dt={onCopy:l=>{var p,h;s.emit("message:copy",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(T=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",T)}),(h=(p=e.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;s.emit("message:feedback",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(T=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",T)}),(h=(p=e.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},Mt=(L=e.statusIndicator)!=null?L:{},Nt=l=>{var p,h,T,A;return l==="idle"?(p=Mt.idleText)!=null?p:Bt.idle:l==="connecting"?(h=Mt.connectingText)!=null?h:Bt.connecting:l==="connected"?(T=Mt.connectedText)!=null?T:Bt.connected:l==="error"?(A=Mt.errorText)!=null?A:Bt.error:Bt[l]},{wrapper:$e,panel:Se}=Yi(e),se=Vi(e,x),{container:he,body:Fe,messagesWrapper:Xe,suggestions:Et,textarea:pe,sendButton:G,sendButtonWrapper:pt,composerForm:gt,statusText:vt,introTitle:Dt,introSubtitle:yt,closeButton:Q,iconHolder:We,headerTitle:bt,headerSubtitle:xt,header:te,footer:Oe,actionsRow:Ct,leftActions:Wt,rightActions:Lt}=se,j=se.micButton,et=se.micButtonWrapper,Ie=se.attachmentButton,K=se.attachmentButtonWrapper,O=se.attachmentInput,we=se.attachmentPreviewsContainer,de=null;(ie=e.attachments)!=null&&ie.enabled&&O&&we&&(de=An.fromConfig(e.attachments),de.setPreviewsContainer(we),O.addEventListener("change",l=>{let p=l.target;de==null||de.handleFileSelect(p.files),p.value=""}));let re=o.find(l=>l.renderHeader);if(re!=null&&re.renderHeader){let l=re.renderHeader({config:e,defaultRenderer:()=>{let p=an({config:e,showClose:x});return En(he,p,e),p.header},onClose:()=>nt(!1,"user")});if(l){let p=he.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(l),te=l)}}let Me=()=>{var p,h,T,A;if(!P)return;if(Ce=!0,!z&&P&&(z=ta({buffer:P,getFullHistory:()=>P.getAllFromStore(),onClose:()=>Ne(),config:e,plugins:o})),z&&(Fe.style.display="none",(p=Oe.parentNode)==null||p.insertBefore(z.element,Oe),z.update()),J){J.classList.remove("tvw-text-cw-muted"),J.classList.add("tvw-text-cw-accent"),J.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let F=(A=(T=(h=e.features)==null?void 0:h.eventStream)==null?void 0:T.classNames)==null?void 0:A.toggleButtonActive;F&&F.split(/\s+/).forEach(ve=>ve&&J.classList.add(ve))}let l=()=>{if(!Ce)return;let F=Date.now();F-ze>=200&&(z==null||z.update(),ze=F),fe=requestAnimationFrame(l)};ze=0,fe=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},Ne=()=>{var l,p,h;if(Ce){if(Ce=!1,z&&z.element.remove(),Fe.style.display="",J){J.classList.remove("tvw-text-cw-accent"),J.classList.add("tvw-text-cw-muted"),J.style.boxShadow="";let T=(h=(p=(l=e.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;T&&T.split(/\s+/).forEach(A=>A&&J.classList.remove(A))}fe!==null&&(cancelAnimationFrame(fe),fe=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},J=null;if(q){let l=(Ye=(Ae=e.features)==null?void 0:Ae.eventStream)==null?void 0:Ye.classNames,p="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");J=g("button",p),J.style.width="28px",J.style.height="28px",J.type="button",J.setAttribute("aria-label","Event Stream"),J.title="Event Stream";let h=oe("activity","18px","currentColor",1.5);h&&J.appendChild(h);let T=se.clearChatButtonWrapper,A=se.closeButtonWrapper,F=T||A;F&&F.parentNode===te?te.insertBefore(J,F):te.appendChild(J),J.addEventListener("click",()=>{Ce?Ne():Me()})}let le=o.find(l=>l.renderComposer);if(le!=null&&le.renderComposer){let l=le.renderComposer({config:e,defaultRenderer:()=>On({config:e}).footer,onSubmit:p=>{$&&!$.isStreaming()&&$.sendMessage(p)},disabled:!1});l&&(Oe.replaceWith(l),Oe=l)}(()=>{var T,A;let l=(A=(T=e.layout)==null?void 0:T.slots)!=null?A:{},p=F=>{switch(F){case"body-top":return he.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Xe;case"footer-top":return Et;case"composer":return gt;case"footer-bottom":return vt;default:return null}},h=(F,ve)=>{var ae;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")te.insertBefore(ve,te.firstChild);else if(F==="header-right")te.appendChild(ve);else{let ce=te.querySelector(".tvw-flex-col");ce?(ae=ce.parentNode)==null||ae.insertBefore(ve,ce.nextSibling):te.appendChild(ve)}break;case"body-top":{let ce=Fe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ce?ce.replaceWith(ve):Fe.insertBefore(ve,Fe.firstChild);break}case"body-bottom":Fe.appendChild(ve);break;case"footer-top":Et.replaceWith(ve);break;case"footer-bottom":vt.replaceWith(ve);break;default:break}};for(let[F,ve]of Object.entries(l))if(ve)try{let ae=ve({config:e,defaultContent:()=>p(F)});ae&&h(F,ae)}catch(ae){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,ae)}})();let Je=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let T=h.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!T)return;let A=T.getAttribute("data-message-id");if(!A)return;let F=h.getAttribute("data-bubble-type");F==="reasoning"?(Dn.has(A)?Dn.delete(A):Dn.add(A),Qi(A,T)):F==="tool"&&(_n.has(A)?_n.delete(A):_n.add(A),Zi(A,T,e))};Xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),Xe.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))});let ot=new Map;Xe.addEventListener("click",l=>{var ve;let h=l.target.closest(".tvw-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let T=h.closest("[data-actions-for]");if(!T)return;let A=T.getAttribute("data-actions-for");if(!A)return;let F=h.getAttribute("data-action");if(F==="copy"){let ce=$.getMessages().find(xe=>xe.id===A);if(ce&&dt.onCopy){let xe=ce.content||"";navigator.clipboard.writeText(xe).then(()=>{h.classList.add("tvw-message-action-success");let ge=oe("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("tvw-message-action-success");let Ee=oe("copy",14,"currentColor",2);Ee&&(h.innerHTML="",h.appendChild(Ee))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),dt.onCopy(ce)}}else if(F==="upvote"||F==="downvote")if(((ve=ot.get(A))!=null?ve:null)===F)ot.delete(A),h.classList.remove("tvw-message-action-active");else{let xe=F==="upvote"?"downvote":"upvote",ge=T.querySelector(`[data-action="${xe}"]`);ge&&ge.classList.remove("tvw-message-action-active"),ot.set(A,F),h.classList.add("tvw-message-action-active");let ee=$.getMessages().find(I=>I.id===A);ee&&dt.onFeedback&&dt.onFeedback({type:F,messageId:ee.id,message:ee})}}),Xe.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let T=h.closest(".vanilla-approval-bubble");if(!T)return;let A=T.getAttribute("data-message-id");if(!A)return;let F=h.getAttribute("data-approval-action");if(!F)return;let ve=F==="approve"?"approved":"denied",ce=$.getMessages().find(ge=>ge.id===A);if(!(ce!=null&&ce.approval))return;let xe=T.querySelector("[data-approval-buttons]");xe&&xe.querySelectorAll("button").forEach(Ee=>{Ee.disabled=!0,Ee.style.opacity="0.5",Ee.style.cursor="not-allowed"}),$.resolveApproval(ce.approval,ve)}),Se.appendChild(he),t.appendChild($e);let In=()=>{var me,ye,Ve,He,ht,Ht,X,je,Xt,zt,pn,Ns,yr,ut,Ds,ms;let l=(ye=(me=e.launcher)==null?void 0:me.sidebarMode)!=null?ye:!1,p=l||((He=(Ve=e.launcher)==null?void 0:Ve.fullHeight)!=null?He:!1),h=(ht=e.theme)!=null?ht:{},T=(X=(Ht=e.launcher)==null?void 0:Ht.position)!=null?X:"bottom-left",A=T==="bottom-left"||T==="top-left",F=l?"none":"1px solid var(--tvw-cw-border)",ve=l?A?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",ae=l?"0":"16px",ce=(je=h.panelBorder)!=null?je:F,xe=(Xt=h.panelShadow)!=null?Xt:ve,ge=(zt=h.panelBorderRadius)!=null?zt:ae;t.style.cssText="",$e.style.cssText="",Se.style.cssText="",he.style.cssText="",Fe.style.cssText="",Oe.style.cssText="";let Ee=(Ns=(pn=e==null?void 0:e.launcher)==null?void 0:pn.width)!=null?Ns:e==null?void 0:e.launcherWidth,ee=Ee!=null?Ee:"min(400px, calc(100vw - 24px))";l||(Se.style.width=ee,Se.style.maxWidth=ee),Se.style.boxShadow=xe,Se.style.borderRadius=ge,he.style.border=ce,he.style.borderRadius=ge;let I=((yr=e.launcher)==null?void 0:yr.enabled)===!1;if(p&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",$e.style.display="flex",$e.style.flexDirection="column",$e.style.flex="1 1 0%",$e.style.minHeight="0",$e.style.maxHeight="100%",$e.style.height="100%",I&&($e.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",Se.style.overflow="hidden",he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.overflow="hidden",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.overflowY="auto",Oe.style.flexShrink="0"),$e.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!I&&((ut=Jt[T])!=null?ut:Jt["bottom-right"]).split(" ").forEach(bn=>$e.classList.add(bn)),l){let yn=(ms=(Ds=e.launcher)==null?void 0:Ds.sidebarWidth)!=null?ms:"420px";$e.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
top: 0 !important;
|
|
23
23
|
bottom: 0 !important;
|
|
24
|
-
width: ${
|
|
24
|
+
width: ${yn} !important;
|
|
25
25
|
height: 100vh !important;
|
|
26
26
|
max-height: 100vh !important;
|
|
27
27
|
margin: 0 !important;
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
display: flex !important;
|
|
30
30
|
flex-direction: column !important;
|
|
31
31
|
${A?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
32
|
-
`,
|
|
32
|
+
`,Se.style.cssText=`
|
|
33
33
|
position: relative !important;
|
|
34
34
|
display: flex !important;
|
|
35
35
|
flex-direction: column !important;
|
|
@@ -40,9 +40,9 @@
|
|
|
40
40
|
min-height: 0 !important;
|
|
41
41
|
margin: 0 !important;
|
|
42
42
|
padding: 0 !important;
|
|
43
|
-
box-shadow: ${
|
|
44
|
-
border-radius: ${
|
|
45
|
-
`,
|
|
43
|
+
box-shadow: ${xe} !important;
|
|
44
|
+
border-radius: ${ge} !important;
|
|
45
|
+
`,Se.style.setProperty("width","100%","important"),Se.style.setProperty("max-width","100%","important"),he.style.cssText=`
|
|
46
46
|
display: flex !important;
|
|
47
47
|
flex-direction: column !important;
|
|
48
48
|
flex: 1 1 0% !important;
|
|
@@ -51,13 +51,13 @@
|
|
|
51
51
|
min-height: 0 !important;
|
|
52
52
|
max-height: 100% !important;
|
|
53
53
|
overflow: hidden !important;
|
|
54
|
-
border-radius: ${
|
|
55
|
-
border: ${
|
|
54
|
+
border-radius: ${ge} !important;
|
|
55
|
+
border: ${ce} !important;
|
|
56
56
|
`,Oe.style.cssText=`
|
|
57
57
|
flex-shrink: 0 !important;
|
|
58
58
|
border-top: none !important;
|
|
59
59
|
padding: 8px 16px 12px 16px !important;
|
|
60
|
-
`}if(!I){let fn="max-height: -moz-available !important; max-height: stretch !important;",wn=l?"":"padding-top: 1.25em !important;";Fe.style.cssText+=fn+wn}};Tn(),$s(e,t);let rt=[];X&&rt.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),Z==null||Z.destroy(),Z=null,D==null||D.destroy(),D=null,N=null});let Jt=null,qn=()=>{Jt&&(Jt(),Jt=null),t.colorScheme==="auto"&&(Jt=_i(()=>{$s(e,t)}))};qn(),rt.push(()=>{Jt&&(Jt(),Jt=null)});let an=Gi(At),Kt=null,F,ln=!1,Gt=!0,un=0,zn=0,Qt=null,Zt=!1,Mn=0,Ln=!1,ps=125,gs=2e3,ms=5,Un=50,kn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Jn=(Hr=(Pr=t.voiceRecognition)==null?void 0:Pr.autoResume)!=null?Hr:!1,Kn=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},en=()=>{c(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},hs=()=>{var L,A;if(((L=t.voiceRecognition)==null?void 0:L.enabled)===!1)return;let l=br(a.voiceState),u=!!l.active,b=Number((A=l.timestamp)!=null?A:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-b<il&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,hn("restore"))},1e3)},fs=()=>F?ra(F.getMessages()).filter(l=>!l.__skipPersist):[];function Yn(l){if(!(i!=null&&i.save))return;let b={messages:l?ra(l):F?fs():[],metadata:a};try{let L=i.save(b);L instanceof Promise&&L.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(L){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)}}let pn=(l=!1)=>{if(!Gt)return;let u=Date.now();Zt&&u<Mn&&!l||(Zt&&u>=Mn&&(Zt=!1),!(!l&&!ln)&&(u-zn<ps||(zn=u,Qt&&cancelAnimationFrame(Qt),Qt=requestAnimationFrame(()=>{Zt||!Gt||(Ln=!0,$e.scrollTop=$e.scrollHeight,un=$e.scrollTop,requestAnimationFrame(()=>{Ln=!1}),Qt=null)}))))},tn=null,ws=()=>Fe.querySelector("#persona-scroll-container")||$e,vs=(l,u=500)=>{let b=l.scrollTop,L=l.clientHeight,A=l.scrollHeight,$=A-b;if(b+L>=A-2||Math.abs($)<5)return;tn!==null&&(cancelAnimationFrame(tn),tn=null);let ce=performance.now(),be=Ce=>1-Math.pow(1-Ce,3),Te=Ce=>{let Pe=l.scrollHeight;Pe!==A&&(A=Pe,$=A-b);let G=Ce-ce,I=Math.min(G/u,1),we=be(I),xe=b+$*we;l.scrollTop=xe,I<1?tn=requestAnimationFrame(Te):(l.scrollTop=l.scrollHeight,tn=null)};tn=requestAnimationFrame(Te)},ys=l=>{let u=new Map;l.forEach(b=>{let L=kn.get(b.id);u.set(b.id,{streaming:b.streaming,role:b.role}),!L&&b.role==="assistant"&&s.emit("assistant:message",b),b.role==="assistant"&&(L!=null&&L.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b)}),kn.clear(),u.forEach((b,L)=>{kn.set(L,b)})},gn=(l,u,b)=>{var Te,Ce,Pe,G;let L=document.createElement("div"),$=(()=>{var we;let I=o.find(xe=>xe.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((we=t.loadingIndicator)!=null&&we.render)return t.loadingIndicator.render})();u.forEach(I=>{var mt,It;let we=null,xe=o.find(K=>!!(I.variant==="reasoning"&&K.renderReasoning||I.variant==="tool"&&K.renderToolCall||!I.variant&&K.renderMessage)),Ve=(mt=t.layout)==null?void 0:mt.messages;if(xe)if(I.variant==="reasoning"&&I.reasoning&&xe.renderReasoning){if(!_)return;we=xe.renderReasoning({message:I,defaultRenderer:()=>ur(I),config:t})}else if(I.variant==="tool"&&I.toolCall&&xe.renderToolCall){if(!le)return;we=xe.renderToolCall({message:I,defaultRenderer:()=>pr(I,t),config:t})}else xe.renderMessage&&(we=xe.renderMessage({message:I,defaultRenderer:()=>{let K=Fn(I,b,Ve,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t});return I.role!=="user"&&mr(K,I,t,F),K},config:t}));if(!we&&I.role==="assistant"&&!I.variant&&t.enableComponentStreaming!==!1&&qs(I)){let je=zs(I);if(je){let Vt=_s(je,{config:t,message:I,transform:b});if(Vt){let zt=document.createElement("div");if(zt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),zt.id=`bubble-${I.id}`,zt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let dn=document.createElement("div");dn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",dn.innerHTML=b({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),zt.appendChild(dn)}zt.appendChild(Vt),we=zt}}}if(!we)if(I.variant==="reasoning"&&I.reasoning){if(!_)return;we=ur(I)}else if(I.variant==="tool"&&I.toolCall){if(!le)return;we=pr(I,t)}else{let K=(It=t.layout)==null?void 0:It.messages;K!=null&&K.renderUserMessage&&I.role==="user"?we=K.renderUserMessage({message:I,config:t,streaming:!!I.streaming}):K!=null&&K.renderAssistantMessage&&I.role==="assistant"?we=K.renderAssistantMessage({message:I,config:t,streaming:!!I.streaming}):we=Fn(I,b,K,t.messageActions,it,{loadingIndicatorRenderer:$,widgetConfig:t}),I.role!=="user"&&we&&mr(we,I,t,F)}let He=document.createElement("div");He.className="tvw-flex",He.id=`wrapper-${I.id}`,He.setAttribute("data-wrapper-id",I.id),I.role==="user"&&He.classList.add("tvw-justify-end"),He.appendChild(we),L.appendChild(He)});let ye=u.some(I=>I.role==="assistant"&&I.streaming),ce=u[u.length-1],be=(ce==null?void 0:ce.role)==="assistant"&&!ce.streaming;if(ln&&u.some(I=>I.role==="user")&&!ye&&!be){let I={config:t,streaming:!0,location:"standalone",defaultRenderer:Sn},we=o.find(Ve=>Ve.renderLoadingIndicator),xe=null;if(we!=null&&we.renderLoadingIndicator&&(xe=we.renderLoadingIndicator(I)),xe===null&&((Te=t.loadingIndicator)!=null&&Te.render)&&(xe=t.loadingIndicator.render(I)),xe===null&&(xe=Sn()),xe){let Ve=document.createElement("div"),He=((Ce=t.loadingIndicator)==null?void 0:Ce.showBubble)!==!1;Ve.className=He?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(xe);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Ve),L.appendChild(mt)}}if(!ln&&u.length>0){let I=u[u.length-1],we={config:t,lastMessage:I,messageCount:u.length},xe=o.find(He=>He.renderIdleIndicator),Ve=null;if(xe!=null&&xe.renderIdleIndicator&&(Ve=xe.renderIdleIndicator(we)),Ve===null&&((Pe=t.loadingIndicator)!=null&&Pe.renderIdle)&&(Ve=t.loadingIndicator.renderIdle(we)),Ve){let He=document.createElement("div"),mt=((G=t.loadingIndicator)==null?void 0:G.showBubble)!==!1;He.className=mt?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(Ve);let It=document.createElement("div");It.className="tvw-flex",It.id="wrapper-idle-indicator",It.setAttribute("data-wrapper-id","idle-indicator"),It.appendChild(He),L.appendChild(It)}}zi(l,L),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=ws();vs(I)})})},mn=()=>{C&&(y?(Fe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-95","tvw-opacity-0"),Ae.classList.add("tvw-scale-100","tvw-opacity-100"),ne?ne.element.style.display="none":ae&&(ae.style.display="none")):(Fe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Ae.classList.remove("tvw-scale-100","tvw-opacity-100"),Ae.classList.add("tvw-scale-95","tvw-opacity-0"),ne?ne.element.style.display="":ae&&(ae.style.display="")))},tt=(l,u="user")=>{if(!C||y===l)return;let b=y;y=l,mn(),y&&(Xe(),pn(!0));let L={open:y,source:u,timestamp:Date.now()};y&&!b?s.emit("widget:opened",L):!y&&b&&s.emit("widget:closed",L),s.emit("widget:state",{open:y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()})},Wn=l=>{J.disabled=l,j&&(j.disabled=l),an.buttons.forEach(u=>{u.disabled=l})},Vn=()=>{var A,$,ye,ce,be,Te,Ce,Pe,G,I,we,xe,Ve,He;Ot.textContent=($=(A=t.copy)==null?void 0:A.welcomeTitle)!=null?$:"Hello \u{1F44B}",wt.textContent=(ce=(ye=t.copy)==null?void 0:ye.welcomeSubtitle)!=null?ce:"Ask anything about your account or products.",me.placeholder=(Te=(be=t.copy)==null?void 0:be.inputPlaceholder)!=null?Te:"How can I help...",((Pe=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?Pe:!1)||(J.textContent=(I=(G=t.copy)==null?void 0:G.sendButtonLabel)!=null?I:"Send");let u=(xe=(we=t.theme)==null?void 0:we.inputFontFamily)!=null?xe:"sans-serif",b=(He=(Ve=t.theme)==null?void 0:Ve.inputFontWeight)!=null?He:"400",L=mt=>{switch(mt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};me.style.fontFamily=L(u),me.style.fontWeight=b};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{c(u=>({...u,sessionId:l}))}}),F=new Hn(t,{onMessagesChanged(l){gn(Qe,l,oe),F&&(l.some(A=>A.role==="user")?an.render([],F,me,l):an.render(t.suggestionChips,F,me,l,t.suggestionChipsConfig)),pn(!ln),ys(l);let u=[...l].reverse().find(L=>L.role==="user"),b=Ke.lastUserMessageId;u&&u.id!==b&&(Ke.lastUserMessageId=u.id,s.emit("user:message",u)),Ke.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Yn(l)},onStatusChanged(l){var L;let u=(L=t.statusIndicator)!=null?L:{},b=A=>{var $,ye,ce,be;return A==="idle"?($=u.idleText)!=null?$:Pt.idle:A==="connecting"?(ye=u.connectingText)!=null?ye:Pt.connecting:A==="connected"?(ce=u.connectedText)!=null?ce:Pt.connected:A==="error"?(be=u.errorText)!=null?be:Pt.error:Pt[A]};ft.textContent=b(l)},onStreamingChanged(l){ln=l,Wn(l),F&&gn(Qe,F.getMessages(),oe),l||pn(!0)}}),t.clientToken&&F.initClientSession().catch(l=>{t.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&F.setSSEEventCallback((l,u)=>{D==null||D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(a=br(l.metadata),x.syncFromMetadata()),(u=l.messages)!=null&&u.length&&F.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Xn=l=>{var A;l.preventDefault();let u=me.value.trim(),b=(A=ue==null?void 0:ue.hasAttachments())!=null?A:!1;if(!u&&!b)return;let L;b&&(L=[],L.push(...ue.getContentParts()),u&&L.push(Bs(u))),me.value="",me.style.height="auto",F.sendMessage(u,{contentParts:L}),b&&ue.clearAttachments()},Gn=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},Ht=null,Nt=!1,nn=null,Yt=null,Qn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,hn=(l="user")=>{var $,ye,ce,be;if(Nt||F.isStreaming())return;let u=Qn();if(!u)return;Ht=new u;let L=(ye=(($=t.voiceRecognition)!=null?$:{}).pauseDuration)!=null?ye:2e3;Ht.continuous=!0,Ht.interimResults=!0,Ht.lang="en-US";let A=me.value;Ht.onresult=Te=>{let Ce="",Pe="";for(let I=0;I<Te.results.length;I++){let we=Te.results[I],xe=we[0].transcript;we.isFinal?Ce+=xe+" ":Pe=xe}let G=A+Ce+Pe;me.value=G,nn&&clearTimeout(nn),(Ce||Pe)&&(nn=window.setTimeout(()=>{let I=me.value.trim();I&&Ht&&Nt&&(qt(),me.value="",me.style.height="auto",F.sendMessage(I,{viaVoice:!0}))},L))},Ht.onerror=Te=>{Te.error!=="no-speech"&&qt()},Ht.onend=()=>{if(Nt){let Te=me.value.trim();Te&&Te!==A.trim()&&(me.value="",me.style.height="auto",F.sendMessage(Te,{viaVoice:!0})),qt()}};try{if(Ht.start(),Nt=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),Kn(l),en(),j){Yt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let Te=(ce=t.voiceRecognition)!=null?ce:{},Ce=(be=Te.recordingBackgroundColor)!=null?be:"#ef4444",Pe=Te.recordingIconColor,G=Te.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=Ce,Pe){j.style.color=Pe;let I=j.querySelector("svg");I&&I.setAttribute("stroke",Pe)}G&&(j.style.borderColor=G),j.setAttribute("aria-label","Stop voice recognition")}}catch{qt("system")}},qt=(l="user")=>{if(Nt){if(Nt=!1,nn&&(clearTimeout(nn),nn=null),Ht){try{Ht.stop()}catch{}Ht=null}if(Ke.active=!1,Kn(l),en(),j){if(j.classList.remove("tvw-voice-recording"),Yt){j.style.backgroundColor=Yt.backgroundColor,j.style.color=Yt.color,j.style.borderColor=Yt.borderColor;let u=j.querySelector("svg");u&&u.setAttribute("stroke",Yt.color||"currentColor"),Yt=null}j.setAttribute("aria-label","Start voice recognition")}}},bs=(l,u)=>{var xe,Ve,He,mt,It,K,je;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let L=p("div","tvw-send-button-wrapper"),A=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let $=(xe=l==null?void 0:l.iconName)!=null?xe:"mic",ye=(Ve=u==null?void 0:u.size)!=null?Ve:"40px",ce=(He=l==null?void 0:l.iconSize)!=null?He:ye,be=parseFloat(ce)||24,Te=(mt=l==null?void 0:l.backgroundColor)!=null?mt:u==null?void 0:u.backgroundColor,Ce=(It=l==null?void 0:l.iconColor)!=null?It:u==null?void 0:u.textColor;A.style.width=ce,A.style.height=ce,A.style.minWidth=ce,A.style.minHeight=ce,A.style.fontSize="18px",A.style.lineHeight="1";let Pe=Ce||"currentColor",G=ie($,be,Pe,1.5);G?(A.appendChild(G),A.style.color=Pe):(A.textContent="\u{1F3A4}",A.style.color=Pe),Te?A.style.backgroundColor=Te:A.classList.add("tvw-bg-cw-primary"),Ce?A.style.color=Ce:!Ce&&!(u!=null&&u.textColor)&&A.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(A.style.borderWidth=l.borderWidth,A.style.borderStyle="solid"),l!=null&&l.borderColor&&(A.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(A.style.paddingLeft=l.paddingX,A.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(A.style.paddingTop=l.paddingY,A.style.paddingBottom=l.paddingY),L.appendChild(A);let I=(K=l==null?void 0:l.tooltipText)!=null?K:"Start voice recognition";if(((je=l==null?void 0:l.showTooltip)!=null?je:!1)&&I){let Vt=p("div","tvw-send-button-tooltip");Vt.textContent=I,L.appendChild(Vt)}return{micButton:A,micButtonWrapper:L}},In=()=>{if(Nt){let l=me.value.trim();Ke.manuallyDeactivated=!0,en(),qt("user"),l&&(me.value="",me.style.height="auto",F.sendMessage(l))}else Ke.manuallyDeactivated=!1,en(),hn("user")};j&&(j.addEventListener("click",In),rt.push(()=>{qt("system"),j&&j.removeEventListener("click",In)}));let Cs=s.on("assistant:complete",()=>{Jn&&(Ke.active||Ke.manuallyDeactivated||Jn==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&hn("auto")},600))});rt.push(Cs);let xs=s.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});rt.push(xs);let B=()=>{tt(!y,"user")},ne=null,ae=null;if(C){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:t,defaultRenderer:()=>is(t,B).element,onToggle:B});u&&(ae=u)}ae||(ne=is(t,B))}ne?e.appendChild(ne.element):ae&&e.appendChild(ae),mn(),an.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),Vn(),Wn(F.isStreaming()),pn(!0),hs();let Xe=()=>{var b,L,A,$,ye,ce,be,Te;let l=(L=(b=t.launcher)==null?void 0:b.sidebarMode)!=null?L:!1,u=l||(($=(A=t.launcher)==null?void 0:A.fullHeight)!=null?$:!1);if(!C){Ae.style.height="",Ae.style.width="";return}if(!l){let Ce=(ce=(ye=t==null?void 0:t.launcher)==null?void 0:ye.width)!=null?ce:t==null?void 0:t.launcherWidth,Pe=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";Ae.style.width=Pe,Ae.style.maxWidth=Pe}if(!u){let Ce=window.innerHeight,Pe=64,G=(Te=(be=t.launcher)==null?void 0:be.heightOffset)!=null?Te:0,I=Math.max(200,Ce-Pe),we=Math.min(640,I),xe=Math.max(200,we-G);Ae.style.height=`${xe}px`}};Xe(),window.addEventListener("resize",Xe),rt.push(()=>window.removeEventListener("resize",Xe)),un=$e.scrollTop;let pt=()=>{let l=$e.scrollTop,u=$e.scrollHeight,b=$e.clientHeight,L=u-l-b,A=Math.abs(l-un);if(un=l,!Ln&&!(A<=ms)){if(!Gt&&L<Un){Zt=!1,Gt=!0;return}Gt&&L>Un&&(Zt=!0,Mn=Date.now()+gs,Gt=!1)}};$e.addEventListener("scroll",pt,{passive:!0}),rt.push(()=>$e.removeEventListener("scroll",pt)),rt.push(()=>{Qt&&cancelAnimationFrame(Qt)});let Et=()=>{Y&&(Kt&&(Y.removeEventListener("click",Kt),Kt=null),C?(Y.style.display="",Kt=()=>{y=!1,mn()},Y.addEventListener("click",Kt)):Y.style.display="none")};Et(),(()=>{let{clearChatButton:l}=ee;l&&l.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(_n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_n}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==_n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",L)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()})})(),ut.addEventListener("submit",Xn),me.addEventListener("keydown",Gn),rt.push(()=>{ut.removeEventListener("submit",Xn),me.removeEventListener("keydown",Gn)}),rt.push(()=>{F.cancel()}),ne?rt.push(()=>{ne==null||ne.destroy()}):ae&&rt.push(()=>{ae==null||ae.remove()});let m={update(l){var Dr,jr,_r,qr,zr,Ur,Jr,Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,Lo,ko,Wo,Io,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,jo,_o,qo,zo,Uo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,hi,fi,wi,vi;let u=t.toolCall,b=t.colorScheme;t={...t,...l},Tn(),$s(e,t),t.colorScheme!==b&&qn();let L=ds.getForInstance(t.plugins);o.length=0,o.push(...L),C=(jr=(Dr=t.launcher)==null?void 0:Dr.enabled)!=null?jr:!0,E=(qr=(_r=t.launcher)==null?void 0:_r.autoExpand)!=null?qr:!1,_=(Ur=(zr=t.features)==null?void 0:zr.showReasoning)!=null?Ur:!0,le=(Kr=(Jr=t.features)==null?void 0:Jr.showToolCalls)!=null?Kr:!0;let A=X;if(X=(Vr=(Yr=t.features)==null?void 0:Yr.showEventStreamToggle)!=null?Vr:!1,X&&!A){if(D||(N=new ls(Se),D=new as(re,N),N.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),F.setSSEEventCallback((M,Me)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:M,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!q&&Q){let M=(Gr=(Xr=t.features)==null?void 0:Xr.eventStream)==null?void 0:Gr.classNames,Me="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(M!=null&&M.toggleButton?" "+M.toggleButton:"");q=p("button",Me),q.style.width="28px",q.style.height="28px",q.type="button",q.setAttribute("aria-label","Event Stream"),q.title="Event Stream";let Ge=ie("activity","18px","currentColor",1.5);Ge&&q.appendChild(Ge);let fe=ee.clearChatButtonWrapper,Re=ee.closeButtonWrapper,ht=fe||Re;ht&&ht.parentNode===Q?Q.insertBefore(q,ht):Q.appendChild(q),q.addEventListener("click",()=>{ve?Ne():Le()})}}else!X&&A&&(Ne(),q&&(q.remove(),q=null),D==null||D.clear(),N==null||N.destroy(),D=null,N=null);if(((Qr=t.launcher)==null?void 0:Qr.enabled)===!1&&ne&&(ne.destroy(),ne=null),((Zr=t.launcher)==null?void 0:Zr.enabled)===!1&&ae&&(ae.remove(),ae=null),((eo=t.launcher)==null?void 0:eo.enabled)!==!1&&!ne&&!ae){let M=o.find(Me=>Me.renderLauncher);if(M!=null&&M.renderLauncher){let Me=M.renderLauncher({config:t,defaultRenderer:()=>is(t,B).element,onToggle:B});Me&&(ae=Me,e.appendChild(ae))}ae||(ne=is(t,B),e.appendChild(ne.element))}ne&&ne.update(t),vt&&((to=t.launcher)==null?void 0:to.title)!==void 0&&(vt.textContent=t.launcher.title),yt&&((no=t.launcher)==null?void 0:no.subtitle)!==void 0&&(yt.textContent=t.launcher.subtitle);let $=(so=t.layout)==null?void 0:so.header;if(($==null?void 0:$.layout)!==V&&Q){let M=$?Bn(t,$,{showClose:C,onClose:()=>tt(!1,"user")}):rn({config:t,showClose:C,onClose:()=>tt(!1,"user")});Q.replaceWith(M.header),Q=M.header,Ie=M.iconHolder,vt=M.headerTitle,yt=M.headerSubtitle,Y=M.closeButton,V=$==null?void 0:$.layout}else if($&&(Ie&&(Ie.style.display=$.showIcon===!1?"none":""),vt&&(vt.style.display=$.showTitle===!1?"none":""),yt&&(yt.style.display=$.showSubtitle===!1?"none":""),Y&&(Y.style.display=$.showCloseButton===!1?"none":""),ee.clearChatButtonWrapper)){let M=$.showClearChat;if(M!==void 0){ee.clearChatButtonWrapper.style.display=M?"":"none";let{closeButtonWrapper:Me}=ee;Me&&!Me.classList.contains("tvw-absolute")&&(M?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let ce=((ro=t.layout)==null?void 0:ro.showHeader)!==!1;Q&&(Q.style.display=ce?"":"none");let be=((oo=t.layout)==null?void 0:oo.showFooter)!==!1;Oe&&(Oe.style.display=be?"":"none"),C!==k?C?tt(E,"auto"):(y=!0,mn()):E!==S&&tt(E,"auto"),S=E,k=C,Xe(),Et(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&F&&gn(Qe,F.getMessages(),oe);let G=(io=t.launcher)!=null?io:{},I=(ao=G.headerIconHidden)!=null?ao:!1,we=(co=(lo=t.layout)==null?void 0:lo.header)==null?void 0:co.showIcon,xe=I||we===!1,Ve=G.headerIconName,He=(uo=G.headerIconSize)!=null?uo:"48px";if(Ie){let M=ge.querySelector(".tvw-border-b-cw-divider"),Me=M==null?void 0:M.querySelector(".tvw-flex-col");if(xe)Ie.style.display="none",M&&Me&&!M.contains(Me)&&M.insertBefore(Me,M.firstChild);else{if(Ie.style.display="",Ie.style.height=He,Ie.style.width=He,M&&Me&&(M.contains(Ie)?Ie.nextSibling!==Me&&(Ie.remove(),M.insertBefore(Ie,Me)):M.insertBefore(Ie,Me)),Ve){let fe=parseFloat(He)||24,Re=ie(Ve,fe*.6,"#ffffff",2);Re?Ie.replaceChildren(Re):Ie.textContent=(po=G.agentIconText)!=null?po:"\u{1F4AC}"}else if(G.iconUrl){let fe=Ie.querySelector("img");if(fe)fe.src=G.iconUrl,fe.style.height=He,fe.style.width=He;else{let Re=document.createElement("img");Re.src=G.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=He,Re.style.width=He,Ie.replaceChildren(Re)}}else{let fe=Ie.querySelector("svg"),Re=Ie.querySelector("img");(fe||Re)&&Ie.replaceChildren(),Ie.textContent=(go=G.agentIconText)!=null?go:"\u{1F4AC}"}let Ge=Ie.querySelector("img");Ge&&(Ge.style.height=He,Ge.style.width=He)}}let mt=(ho=(mo=t.layout)==null?void 0:mo.header)==null?void 0:ho.showTitle,It=(wo=(fo=t.layout)==null?void 0:fo.header)==null?void 0:wo.showSubtitle;if(vt&&(vt.style.display=mt===!1?"none":""),yt&&(yt.style.display=It===!1?"none":""),Y){((yo=(vo=t.layout)==null?void 0:vo.header)==null?void 0:yo.showCloseButton)===!1?Y.style.display="none":Y.style.display="";let Me=(bo=G.closeButtonSize)!=null?bo:"32px",Ge=(Co=G.closeButtonPlacement)!=null?Co:"inline";Y.style.height=Me,Y.style.width=Me;let{closeButtonWrapper:fe}=ee,Re=Ge==="top-right",ht=fe==null?void 0:fe.classList.contains("tvw-absolute");if(fe&&Re!==ht)if(fe.remove(),Re)fe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",ge.style.position="relative",ge.appendChild(fe);else{let ke=(So=(xo=G.clearChat)==null?void 0:xo.placement)!=null?So:"inline",St=(Eo=(Ao=G.clearChat)==null?void 0:Ao.enabled)!=null?Eo:!0;fe.className=St&&ke==="inline"?"":"tvw-ml-auto";let Ft=ge.querySelector(".tvw-border-b-cw-divider");Ft&&Ft.appendChild(fe)}if(G.closeButtonColor?(Y.style.color=G.closeButtonColor,Y.classList.remove("tvw-text-cw-muted")):(Y.style.color="",Y.classList.add("tvw-text-cw-muted")),G.closeButtonBackgroundColor?(Y.style.backgroundColor=G.closeButtonBackgroundColor,Y.classList.remove("hover:tvw-bg-gray-100")):(Y.style.backgroundColor="",Y.classList.add("hover:tvw-bg-gray-100")),G.closeButtonBorderWidth||G.closeButtonBorderColor){let ke=G.closeButtonBorderWidth||"0px",St=G.closeButtonBorderColor||"transparent";Y.style.border=`${ke} solid ${St}`,Y.classList.remove("tvw-border-none")}else Y.style.border="",Y.classList.add("tvw-border-none");G.closeButtonBorderRadius?(Y.style.borderRadius=G.closeButtonBorderRadius,Y.classList.remove("tvw-rounded-full")):(Y.style.borderRadius="",Y.classList.add("tvw-rounded-full")),G.closeButtonPaddingX?(Y.style.paddingLeft=G.closeButtonPaddingX,Y.style.paddingRight=G.closeButtonPaddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),G.closeButtonPaddingY?(Y.style.paddingTop=G.closeButtonPaddingY,Y.style.paddingBottom=G.closeButtonPaddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let kt=(To=G.closeButtonIconName)!=null?To:"x",Dt=(Mo=G.closeButtonIconText)!=null?Mo:"\xD7";Y.innerHTML="";let Bt=ie(kt,"20px",G.closeButtonColor||"",2);Bt?Y.appendChild(Bt):Y.textContent=Dt;let ot=(Lo=G.closeButtonTooltipText)!=null?Lo:"Close chat",jt=(ko=G.closeButtonShowTooltip)!=null?ko:!0;if(Y.setAttribute("aria-label",ot),fe&&(fe._cleanupTooltip&&(fe._cleanupTooltip(),delete fe._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!Y)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let ss=p("div");ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(ss);let vn=Y.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${vn.left+vn.width/2}px`,ke.style.top=`${vn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};fe.addEventListener("mouseenter",St),fe.addEventListener("mouseleave",Ft),Y.addEventListener("focus",St),Y.addEventListener("blur",Ft),fe._cleanupTooltip=()=>{Ft(),fe&&(fe.removeEventListener("mouseenter",St),fe.removeEventListener("mouseleave",Ft)),Y&&(Y.removeEventListener("focus",St),Y.removeEventListener("blur",Ft))}}}let{clearChatButton:K,clearChatButtonWrapper:je}=ee;if(K){let M=(Wo=G.clearChat)!=null?Wo:{},Me=(Io=M.enabled)!=null?Io:!0,Ge=(Ho=(Po=t.layout)==null?void 0:Po.header)==null?void 0:Ho.showClearChat,fe=Ge!==void 0?Ge:Me,Re=(Bo=M.placement)!=null?Bo:"inline";if(je){je.style.display=fe?"":"none";let{closeButtonWrapper:ht}=ee;ht&&!ht.classList.contains("tvw-absolute")&&(fe?ht.classList.remove("tvw-ml-auto"):ht.classList.add("tvw-ml-auto"));let kt=Re==="top-right",Dt=je.classList.contains("tvw-absolute");if(kt!==Dt&&fe){if(je.remove(),kt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",ge.style.position="relative",ge.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ot=ge.querySelector(".tvw-border-b-cw-divider"),jt=ee.closeButtonWrapper;ot&&jt&&jt.parentElement===ot?ot.insertBefore(je,jt):ot&&ot.appendChild(je)}let Bt=ee.closeButtonWrapper;Bt&&!Bt.classList.contains("tvw-absolute")&&(kt?Bt.classList.add("tvw-ml-auto"):Bt.classList.remove("tvw-ml-auto"))}}if(fe){let ht=(Ro=M.size)!=null?Ro:"32px";K.style.height=ht,K.style.width=ht;let kt=(Fo=M.iconName)!=null?Fo:"refresh-cw",Dt=($o=M.iconColor)!=null?$o:"";K.innerHTML="";let Bt=ie(kt,"20px",Dt||"",2);if(Bt&&K.appendChild(Bt),Dt?(K.style.color=Dt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),M.backgroundColor?(K.style.backgroundColor=M.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),M.borderWidth||M.borderColor){let ke=M.borderWidth||"0px",St=M.borderColor||"transparent";K.style.border=`${ke} solid ${St}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");M.borderRadius?(K.style.borderRadius=M.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),M.paddingX?(K.style.paddingLeft=M.paddingX,K.style.paddingRight=M.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),M.paddingY?(K.style.paddingTop=M.paddingY,K.style.paddingBottom=M.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let ot=(Oo=M.tooltipText)!=null?Oo:"Clear chat",jt=(No=M.showTooltip)!=null?No:!0;if(K.setAttribute("aria-label",ot),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),jt&&ot)){let ke=null,St=()=>{if(ke||!K)return;ke=p("div","tvw-clear-chat-tooltip"),ke.textContent=ot;let ss=p("div");ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(ss);let vn=K.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${vn.left+vn.width/2}px`,ke.style.top=`${vn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},Ft=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};je.addEventListener("mouseenter",St),je.addEventListener("mouseleave",Ft),K.addEventListener("focus",St),K.addEventListener("blur",Ft),je._cleanupTooltip=()=>{Ft(),je&&(je.removeEventListener("mouseenter",St),je.removeEventListener("mouseleave",Ft)),K&&(K.removeEventListener("focus",St),K.removeEventListener("blur",Ft))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[cs],zt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[An.message,An.messageAndClick];x=us({parsers:Vt,handlers:zt,getSessionMetadata:w,updateSessionMetadata:c,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),oe=oa(t,x,H),F.updateConfig(t),gn(Qe,F.getMessages(),oe),an.render(t.suggestionChips,F,me,void 0,t.suggestionChipsConfig),Vn(),Wn(F.isStreaming());let dn=((Do=t.voiceRecognition)==null?void 0:Do.enabled)===!0,Ss=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(dn&&Ss)if(!j||!Ze){let M=bs(t.voiceRecognition,t.sendButton);M&&(j=M.micButton,Ze=M.micButtonWrapper,Mt.insertBefore(Ze,ct),j.addEventListener("click",In),j.disabled=F.isStreaming())}else{let M=(jo=t.voiceRecognition)!=null?jo:{},Me=(_o=t.sendButton)!=null?_o:{},Ge=(qo=M.iconName)!=null?qo:"mic",fe=(zo=Me.size)!=null?zo:"40px",Re=(Uo=M.iconSize)!=null?Uo:fe,ht=parseFloat(Re)||24;j.style.width=Re,j.style.height=Re,j.style.minWidth=Re,j.style.minHeight=Re;let kt=(Ko=(Jo=M.iconColor)!=null?Jo:Me.textColor)!=null?Ko:"currentColor";j.innerHTML="";let Dt=ie(Ge,ht,kt,2);Dt?j.appendChild(Dt):j.textContent="\u{1F3A4}";let Bt=(Yo=M.backgroundColor)!=null?Yo:Me.backgroundColor;Bt?(j.style.backgroundColor=Bt,j.classList.remove("tvw-bg-cw-primary")):(j.style.backgroundColor="",j.classList.add("tvw-bg-cw-primary")),kt?(j.style.color=kt,j.classList.remove("tvw-text-white")):!kt&&!Me.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),M.borderWidth?(j.style.borderWidth=M.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),M.borderColor?j.style.borderColor=M.borderColor:j.style.borderColor="",M.paddingX?(j.style.paddingLeft=M.paddingX,j.style.paddingRight=M.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),M.paddingY?(j.style.paddingTop=M.paddingY,j.style.paddingBottom=M.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let ot=Ze==null?void 0:Ze.querySelector(".tvw-send-button-tooltip"),jt=(Vo=M.tooltipText)!=null?Vo:"Start voice recognition";if(((Xo=M.showTooltip)!=null?Xo:!1)&&jt)if(ot)ot.textContent=jt,ot.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=jt,Ze==null||Ze.insertBefore(St,j)}else ot&&(ot.style.display="none");Ze.style.display="",j.disabled=F.isStreaming()}else j&&Ze&&(Ze.style.display="none",Nt&&qt());if(((Go=t.attachments)==null?void 0:Go.enabled)===!0)if(!z||!We){let M=(Qo=t.attachments)!=null?Qo:{},Ge=(ei=((Zo=t.sendButton)!=null?Zo:{}).size)!=null?ei:"40px";he||(he=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),he.style.display="none",ut.insertBefore(he,me)),R||(R=document.createElement("input"),R.type="file",R.accept=((ti=M.allowedTypes)!=null?ti:cn).join(","),R.multiple=((ni=M.maxFiles)!=null?ni:4)>1,R.style.display="none",R.setAttribute("aria-label","Attach files"),ut.insertBefore(R,me)),z=p("div","tvw-send-button-wrapper"),We=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),We.type="button",We.setAttribute("aria-label",(si=M.buttonTooltipText)!=null?si:"Attach file");let fe=(ri=M.buttonIconName)!=null?ri:"paperclip",Re=Ge,ht=parseFloat(Re)||40,kt=Math.round(ht*.6);We.style.width=Re,We.style.height=Re,We.style.minWidth=Re,We.style.minHeight=Re,We.style.fontSize="18px",We.style.lineHeight="1",We.style.backgroundColor="transparent",We.style.color="var(--cw-primary, #111827)",We.style.border="none",We.style.borderRadius="6px",We.style.transition="background-color 0.15s ease",We.addEventListener("mouseenter",()=>{We.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),We.addEventListener("mouseleave",()=>{We.style.backgroundColor="transparent"});let Dt=ie(fe,kt,"currentColor",1.5);Dt?We.appendChild(Dt):We.textContent="\u{1F4CE}",We.addEventListener("click",jt=>{jt.preventDefault(),R==null||R.click()}),z.appendChild(We);let Bt=(oi=M.buttonTooltipText)!=null?oi:"Attach file",ot=p("div","tvw-send-button-tooltip");ot.textContent=Bt,z.appendChild(ot),Wt.append(z),!ue&&R&&he&&(ue=Cn.fromConfig(M),ue.setPreviewsContainer(he),R.addEventListener("change",async()=>{ue&&(R!=null&&R.files)&&(await ue.handleFileSelect(R.files),R.value="")}))}else{z.style.display="";let M=(ii=t.attachments)!=null?ii:{};R&&(R.accept=((ai=M.allowedTypes)!=null?ai:cn).join(","),R.multiple=((li=M.maxFiles)!=null?li:4)>1),ue&&ue.updateConfig({allowedTypes:M.allowedTypes,maxFileSize:M.maxFileSize,maxFiles:M.maxFiles})}else z&&(z.style.display="none"),ue&&ue.clearAttachments();let dt=(di=t.sendButton)!=null?di:{},As=(ci=dt.useIcon)!=null?ci:!1,Zn=(ui=dt.iconText)!=null?ui:"\u2191",fn=dt.iconName,wn=(pi=dt.tooltipText)!=null?pi:"Send message",ma=(gi=dt.showTooltip)!=null?gi:!1,es=(mi=dt.size)!=null?mi:"40px",Es=dt.backgroundColor,Xt=dt.textColor;if(As){if(J.style.width=es,J.style.height=es,J.style.minWidth=es,J.style.minHeight=es,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",fn){let M=parseFloat(es)||24,Me=Xt&&typeof Xt=="string"&&Xt.trim()?Xt.trim():"currentColor",Ge=ie(fn,M,Me,2);Ge?(J.appendChild(Ge),J.style.color=Me):(J.textContent=Zn,Xt?J.style.color=Xt:J.classList.add("tvw-text-white"))}else J.textContent=Zn,Xt?J.style.color=Xt:J.classList.add("tvw-text-white");J.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Es?(J.style.backgroundColor=Es,J.classList.remove("tvw-bg-cw-primary")):J.classList.add("tvw-bg-cw-primary")}else J.textContent=(fi=(hi=t.copy)==null?void 0:hi.sendButtonLabel)!=null?fi:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Es?(J.style.backgroundColor=Es,J.classList.remove("tvw-bg-cw-accent")):J.classList.add("tvw-bg-cw-accent"),Xt?J.style.color=Xt:J.classList.add("tvw-text-white");dt.borderWidth?(J.style.borderWidth=dt.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),dt.borderColor?J.style.borderColor=dt.borderColor:J.style.borderColor="",dt.paddingX?(J.style.paddingLeft=dt.paddingX,J.style.paddingRight=dt.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),dt.paddingY?(J.style.paddingTop=dt.paddingY,J.style.paddingBottom=dt.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let ts=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(ma&&wn)if(ts)ts.textContent=wn,ts.style.display="";else{let M=document.createElement("div");M.className="tvw-send-button-tooltip",M.textContent=wn,ct==null||ct.insertBefore(M,J)}else ts&&(ts.style.display="none");let ns=(wi=t.statusIndicator)!=null?wi:{},ha=(vi=ns.visible)!=null?vi:!0;if(ft.style.display=ha?"":"none",F){let M=F.getStatus(),Me=Ge=>{var fe,Re,ht,kt;return Ge==="idle"?(fe=ns.idleText)!=null?fe:Pt.idle:Ge==="connecting"?(Re=ns.connectingText)!=null?Re:Pt.connecting:Ge==="connected"?(ht=ns.connectedText)!=null?ht:Pt.connected:Ge==="error"?(kt=ns.errorText)!=null?kt:Pt.error:Pt[Ge]};ft.textContent=Me(M)}},open(){C&&tt(!0,"api")},close(){C&&tt(!1,"api")},toggle(){C&&tt(!y,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(_n),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_n}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==_n)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},x.syncFromMetadata(),D==null||D.clear(),Z==null||Z.update()},setMessage(l){return!me||F.isStreaming()?!1:(!y&&C&&tt(!0,"system"),me.value=l,me.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let u=(l==null?void 0:l.trim())||me.value.trim();return u?(!y&&C&&tt(!0,"system"),me.value="",me.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){return Nt||F.isStreaming()||!Qn()?!1:(!y&&C&&tt(!0,"system"),Ke.manuallyDeactivated=!1,en(),hn("user"),!0)},stopVoiceRecognition(){return Nt?(Ke.manuallyDeactivated=!0,en(),qt("user"),!0):!1},injectMessage(l){return!y&&C&&tt(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!y&&C&&tt(!0,"system");let u=F.injectAssistantMessage(l);return O&&(O=!1,W&&(clearTimeout(W),W=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),u},injectUserMessage(l){return!y&&C&&tt(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!y&&C&&tt(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!y&&C&&tt(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!y&&C&&tt(!0,"system"),F.injectTestEvent(l)},__pushEventStreamEvent(l){D&&D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!X||!D||Le()},hideEventStream(){ve&&Ne()},isEventStreamVisible(){return ve},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){c(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return C&&y},isVoiceActive(){return Ke.active},getState(){return{open:C&&y,launcherEnabled:C,voiceActive:Ke.active,streaming:F.isStreaming()}},showCSATFeedback(l){!y&&C&&tt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Us({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitCSATFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!y&&C&&tt(!0,"system");let u=Qe.querySelector(".tvw-feedback-container");u&&u.remove();let b=Js({onSubmit:async(L,A)=>{var $;F.isClientTokenMode()&&await F.submitNPSFeedback(L,A),($=l==null?void 0:l.onSubmit)==null||$.call(l,L,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return F.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return F.submitNPSFeedback(l,u)},destroy(){rt.forEach(l=>l()),Fe.remove(),ne==null||ne.destroy(),ae==null||ae.remove(),Kt&&Y.removeEventListener("click",Kt)}};if((((Br=r==null?void 0:r.debugTools)!=null?Br:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:m,getMessages:m.getMessages,getStatus:m.getStatus,getMetadata:m.getPersistentMetadata,updateMetadata:m.updatePersistentMetadata,clearHistory:()=>m.clearChat(),setVoiceActive:b=>b?m.startVoiceRecognition():m.stopVoiceRecognition()};window.AgentWidgetBrowser=u,rt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(X&&typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.showEventStream()},b=L=>{let A=L.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&m.hideEventStream()};window.addEventListener("persona:showEventStream",u),window.addEventListener("persona:hideEventStream",b),rt.push(()=>{window.removeEventListener("persona:showEventStream",u),window.removeEventListener("persona:hideEventStream",b)})}let P=al(t.persistState);if(P&&C){let l=ll(P.storage),u=`${P.keyPrefix}widget-open`,b=`${P.keyPrefix}widget-voice`,L=`${P.keyPrefix}widget-voice-mode`;if(l){let A=((Rr=P.persist)==null?void 0:Rr.openState)&&l.getItem(u)==="true",$=((Fr=P.persist)==null?void 0:Fr.voiceState)&&l.getItem(b)==="true",ye=(($r=P.persist)==null?void 0:$r.voiceState)&&l.getItem(L)==="true";if(A&&setTimeout(()=>{m.open(),setTimeout(()=>{var ce;if($||ye)m.startVoiceRecognition();else if((ce=P.persist)!=null&&ce.focusInput){let be=e.querySelector("textarea");be&&be.focus()}},100)},0),(Or=P.persist)!=null&&Or.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Nr=P.persist)!=null&&Nr.voiceState&&(s.on("voice:state",ce=>{l.setItem(b,ce.active?"true":"false")}),s.on("user:message",ce=>{l.setItem(L,ce.viaVoice?"true":"false")})),P.clearOnChatClear){let ce=()=>{l.removeItem(u),l.removeItem(b),l.removeItem(L)},be=()=>ce();window.addEventListener("persona:clear-chat",be),rt.push(()=>{window.removeEventListener("persona:clear-chat",be)})}}}return m};var Cr={},dl=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},cl=()=>{try{if(typeof Cr!="undefined"&&Cr.url)return new URL("../widget.css",Cr.url).href}catch{}return null},ia=e=>{let n=cl(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},xr=e=>{var g,w,c,h;let n=dl(e.target),r=document.createElement("div");r.className="persona-host";let t=(c=(w=(g=e.config)==null?void 0:g.launcher)==null?void 0:w.enabled)!=null?c:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let f=r.attachShadow({mode:"open"});i=f,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),f.appendChild(s),ia(f)}else i=r,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),ia(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=Ks(s,e.config,{debugTools:e.debugTools});(h=e.onReady)==null||h.call(e);let d={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var aa={name:"@runtypelabs/persona",version:"1.44.1",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var En=aa.version;function on(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function pl(e){if(e)return{getHeaders:on(e.getHeaders),onFeedback:on(e.onFeedback),onCopy:on(e.onCopy),requestMiddleware:on(e.requestMiddleware),actionHandlers:on(e.actionHandlers),actionParsers:on(e.actionParsers),postprocessMessage:on(e.postprocessMessage),contextProviders:on(e.contextProviders),streamParser:on(e.streamParser)}}var la=`({ text, message }: any) => {
|
|
60
|
+
`}if(!I){let yn="max-height: -moz-available !important; max-height: stretch !important;",bn=l?"":"padding-top: 1.25em !important;";$e.style.cssText+=yn+bn}};In(),er(t,e);let it=[];q&&it.push(()=>{fe!==null&&(cancelAnimationFrame(fe),fe=null),z==null||z.destroy(),z=null,P==null||P.destroy(),P=null,B=null});let Kt=null,Jn=()=>{Kt&&(Kt(),Kt=null),e.colorScheme==="auto"&&(Kt=zi(()=>{er(t,e)}))};Jn(),it.push(()=>{Kt&&(Kt(),Kt=null)});let dn=ea(Et),Yt=null,$,cn=!1,Qt=!0,mn=0,Kn=0,Zt=null,en=!1,kn=0,Wn=!1,Ls=125,Is=2e3,ks=5,Yn=50,Pn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Vn=(rt=(It=e.voiceRecognition)==null?void 0:It.autoResume)!=null?rt:!1,Xn=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},tn=()=>{d(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Ws=()=>{var T,A;if(((T=e.voiceRecognition)==null?void 0:T.enabled)===!1)return;let l=Dr(a.voiceState),p=!!l.active,h=Number((A=l.timestamp)!=null?A:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<gl&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,vn("restore"))},1e3)},Ps=()=>$?aa($.getMessages()).filter(l=>!l.__skipPersist):[];function Gn(l){if(!(i!=null&&i.save))return;let h={messages:l?aa(l):$?Ps():[],metadata:a};try{let T=i.save(h);T instanceof Promise&&T.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)}}let fn=(l=!1)=>{if(!Qt)return;let p=Date.now();en&&p<kn&&!l||(en&&p>=kn&&(en=!1),!(!l&&!cn)&&(p-Kn<Ls||(Kn=p,Zt&&cancelAnimationFrame(Zt),Zt=requestAnimationFrame(()=>{en||!Qt||(Wn=!0,Fe.scrollTop=Fe.scrollHeight,mn=Fe.scrollTop,requestAnimationFrame(()=>{Wn=!1}),Zt=null)}))))},nn=null,Hs=()=>$e.querySelector("#persona-scroll-container")||Fe,Bs=(l,p=500)=>{let h=l.scrollTop,T=l.clientHeight,A=l.scrollHeight,F=A-h;if(h+T>=A-2||Math.abs(F)<5)return;nn!==null&&(cancelAnimationFrame(nn),nn=null);let ae=performance.now(),ce=ge=>1-Math.pow(1-ge,3),xe=ge=>{let Ee=l.scrollHeight;Ee!==A&&(A=Ee,F=A-h);let ee=ge-ae,I=Math.min(ee/p,1),me=ce(I),ye=h+F*me;l.scrollTop=ye,I<1?nn=requestAnimationFrame(xe):(l.scrollTop=l.scrollHeight,nn=null)};nn=requestAnimationFrame(xe)},Rs=l=>{let p=new Map;l.forEach(h=>{let T=Pn.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!T&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(T!=null&&T.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(T?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Pn.clear(),p.forEach((h,T)=>{Pn.set(T,h)})},hn=(l,p,h)=>{var xe,ge,Ee,ee;let T=document.createElement("div"),F=(()=>{var me;let I=o.find(ye=>ye.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((me=e.loadingIndicator)!=null&&me.render)return e.loadingIndicator.render})();p.forEach(I=>{var ht,Ht;let me=null,ye=o.find(X=>!!(I.variant==="reasoning"&&X.renderReasoning||I.variant==="tool"&&X.renderToolCall||I.variant==="approval"&&X.renderApproval||!I.variant&&X.renderMessage)),Ve=(ht=e.layout)==null?void 0:ht.messages;if(ye)if(I.variant==="reasoning"&&I.reasoning&&ye.renderReasoning){if(!Y)return;me=ye.renderReasoning({message:I,defaultRenderer:()=>kr(I),config:e})}else if(I.variant==="tool"&&I.toolCall&&ye.renderToolCall){if(!_)return;me=ye.renderToolCall({message:I,defaultRenderer:()=>Wr(I,e),config:e})}else if(I.variant==="approval"&&I.approval&&ye.renderApproval){if(e.approval===!1)return;me=ye.renderApproval({message:I,defaultRenderer:()=>Pr(I,e),config:e})}else ye.renderMessage&&(me=ye.renderMessage({message:I,defaultRenderer:()=>{let X=Nn(I,h,Ve,e.messageActions,dt,{loadingIndicatorRenderer:F,widgetConfig:e});return I.role!=="user"&&Br(X,I,e,$),X},config:e}));if(!me&&I.role==="assistant"&&!I.variant&&e.enableComponentStreaming!==!1&&ir(I)){let je=ar(I);if(je){let Xt=or(je,{config:e,message:I,transform:h});if(Xt){let zt=document.createElement("div");if(zt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),zt.id=`bubble-${I.id}`,zt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let pn=document.createElement("div");pn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",pn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),zt.appendChild(pn)}zt.appendChild(Xt),me=zt}}}if(!me)if(I.variant==="reasoning"&&I.reasoning){if(!Y)return;me=kr(I)}else if(I.variant==="tool"&&I.toolCall){if(!_)return;me=Wr(I,e)}else if(I.variant==="approval"&&I.approval){if(e.approval===!1)return;me=Pr(I,e)}else{let X=(Ht=e.layout)==null?void 0:Ht.messages;X!=null&&X.renderUserMessage&&I.role==="user"?me=X.renderUserMessage({message:I,config:e,streaming:!!I.streaming}):X!=null&&X.renderAssistantMessage&&I.role==="assistant"?me=X.renderAssistantMessage({message:I,config:e,streaming:!!I.streaming}):me=Nn(I,h,X,e.messageActions,dt,{loadingIndicatorRenderer:F,widgetConfig:e}),I.role!=="user"&&me&&Br(me,I,e,$)}let He=document.createElement("div");He.className="tvw-flex",He.id=`wrapper-${I.id}`,He.setAttribute("data-wrapper-id",I.id),I.role==="user"&&He.classList.add("tvw-justify-end"),He.appendChild(me),T.appendChild(He)});let ve=p.some(I=>I.role==="assistant"&&I.streaming),ae=p[p.length-1],ce=(ae==null?void 0:ae.role)==="assistant"&&!ae.streaming;if(cn&&p.some(I=>I.role==="user")&&!ve&&!ce){let I={config:e,streaming:!0,location:"standalone",defaultRenderer:Tn},me=o.find(Ve=>Ve.renderLoadingIndicator),ye=null;if(me!=null&&me.renderLoadingIndicator&&(ye=me.renderLoadingIndicator(I)),ye===null&&((xe=e.loadingIndicator)!=null&&xe.render)&&(ye=e.loadingIndicator.render(I)),ye===null&&(ye=Tn()),ye){let Ve=document.createElement("div"),He=((ge=e.loadingIndicator)==null?void 0:ge.showBubble)!==!1;Ve.className=He?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(ye);let ht=document.createElement("div");ht.className="tvw-flex",ht.id="wrapper-typing-indicator",ht.setAttribute("data-wrapper-id","typing-indicator"),ht.appendChild(Ve),T.appendChild(ht)}}if(!cn&&p.length>0){let I=p[p.length-1],me={config:e,lastMessage:I,messageCount:p.length},ye=o.find(He=>He.renderIdleIndicator),Ve=null;if(ye!=null&&ye.renderIdleIndicator&&(Ve=ye.renderIdleIndicator(me)),Ve===null&&((Ee=e.loadingIndicator)!=null&&Ee.renderIdle)&&(Ve=e.loadingIndicator.renderIdle(me)),Ve){let He=document.createElement("div"),ht=((ee=e.loadingIndicator)==null?void 0:ee.showBubble)!==!1;He.className=ht?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(Ve);let Ht=document.createElement("div");Ht.className="tvw-flex",Ht.id="wrapper-idle-indicator",Ht.setAttribute("data-wrapper-id","idle-indicator"),Ht.appendChild(He),T.appendChild(Ht)}}Ki(l,T),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=Hs();Bs(I)})})},wn=()=>{x&&(b?($e.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Se.classList.remove("tvw-scale-95","tvw-opacity-0"),Se.classList.add("tvw-scale-100","tvw-opacity-100"),Ge?Ge.element.style.display="none":Qe&&(Qe.style.display="none")):($e.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Se.classList.remove("tvw-scale-100","tvw-opacity-100"),Se.classList.add("tvw-scale-95","tvw-opacity-0"),Ge?Ge.element.style.display="":Qe&&(Qe.style.display="")))},nt=(l,p="user")=>{if(!x||b===l)return;let h=b;b=l,wn(),b&&(un(),fn(!0));let T={open:b,source:p,timestamp:Date.now()};b&&!h?s.emit("widget:opened",T):!b&&h&&s.emit("widget:closed",T),s.emit("widget:state",{open:b,launcherEnabled:x,voiceActive:Ke.active,streaming:$.isStreaming()})},Hn=l=>{G.disabled=l,j&&(j.disabled=l),dn.buttons.forEach(p=>{p.disabled=l})},Qn=()=>{var A,F,ve,ae,ce,xe,ge,Ee,ee,I,me,ye,Ve,He;Dt.textContent=(F=(A=e.copy)==null?void 0:A.welcomeTitle)!=null?F:"Hello \u{1F44B}",yt.textContent=(ae=(ve=e.copy)==null?void 0:ve.welcomeSubtitle)!=null?ae:"Ask anything about your account or products.",pe.placeholder=(xe=(ce=e.copy)==null?void 0:ce.inputPlaceholder)!=null?xe:"How can I help...",((Ee=(ge=e.sendButton)==null?void 0:ge.useIcon)!=null?Ee:!1)||(G.textContent=(I=(ee=e.copy)==null?void 0:ee.sendButtonLabel)!=null?I:"Send");let p=(ye=(me=e.theme)==null?void 0:me.inputFontFamily)!=null?ye:"sans-serif",h=(He=(Ve=e.theme)==null?void 0:Ve.inputFontWeight)!=null?He:"400",T=ht=>{switch(ht){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=T(p),pe.style.fontWeight=h};e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{d(p=>({...p,sessionId:l}))}}),$=new $n(e,{onMessagesChanged(l){hn(Xe,l,ne),$&&(l.some(A=>A.role==="user")?dn.render([],$,pe,l):dn.render(e.suggestionChips,$,pe,l,e.suggestionChipsConfig)),fn(!cn),Rs(l);let p=[...l].reverse().find(T=>T.role==="user"),h=Ke.lastUserMessageId;p&&p.id!==h&&(Ke.lastUserMessageId=p.id,s.emit("user:message",p)),Ke.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Gn(l)},onStatusChanged(l){var T;let p=(T=e.statusIndicator)!=null?T:{},h=A=>{var F,ve,ae,ce;return A==="idle"?(F=p.idleText)!=null?F:Bt.idle:A==="connecting"?(ve=p.connectingText)!=null?ve:Bt.connecting:A==="connected"?(ae=p.connectedText)!=null?ae:Bt.connected:A==="error"?(ce=p.errorText)!=null?ce:Bt.error:Bt[A]};vt.textContent=h(l)},onStreamingChanged(l){cn=l,Hn(l),$&&hn(Xe,$.getMessages(),ne),l||fn(!0)}}),e.clientToken&&$.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),P&&$.setSSEEventCallback((l,p)=>{P==null||P.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),u&&u.then(l=>{var p;l&&(l.metadata&&(a=Dr(l.metadata),S.syncFromMetadata()),(p=l.messages)!=null&&p.length&&$.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Zn=l=>{var A;l.preventDefault();let p=pe.value.trim(),h=(A=de==null?void 0:de.hasAttachments())!=null?A:!1;if(!p&&!h)return;let T;h&&(T=[],T.push(...de.getContentParts()),p&&T.push(Gs(p))),pe.value="",pe.style.height="auto",$.sendMessage(p,{contentParts:T}),h&&de.clearAttachments()},es=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),G.click())},ts=async l=>{var h;if(((h=e.attachments)==null?void 0:h.enabled)!==!0||!de)return;let p=fl(l.clipboardData);p.length!==0&&(l.preventDefault(),await de.handleFiles(p))},Rt=null,_t=!1,sn=null,Vt=null,ns=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,vn=(l="user")=>{var F,ve,ae,ce;if(_t||$.isStreaming())return;let p=ns();if(!p)return;Rt=new p;let T=(ve=((F=e.voiceRecognition)!=null?F:{}).pauseDuration)!=null?ve:2e3;Rt.continuous=!0,Rt.interimResults=!0,Rt.lang="en-US";let A=pe.value;Rt.onresult=xe=>{let ge="",Ee="";for(let I=0;I<xe.results.length;I++){let me=xe.results[I],ye=me[0].transcript;me.isFinal?ge+=ye+" ":Ee=ye}let ee=A+ge+Ee;pe.value=ee,sn&&clearTimeout(sn),(ge||Ee)&&(sn=window.setTimeout(()=>{let I=pe.value.trim();I&&Rt&&_t&&(Ut(),pe.value="",pe.style.height="auto",$.sendMessage(I,{viaVoice:!0}))},T))},Rt.onerror=xe=>{xe.error!=="no-speech"&&Ut()},Rt.onend=()=>{if(_t){let xe=pe.value.trim();xe&&xe!==A.trim()&&(pe.value="",pe.style.height="auto",$.sendMessage(xe,{viaVoice:!0})),Ut()}};try{if(Rt.start(),_t=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),Xn(l),tn(),j){Vt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let xe=(ae=e.voiceRecognition)!=null?ae:{},ge=(ce=xe.recordingBackgroundColor)!=null?ce:"#ef4444",Ee=xe.recordingIconColor,ee=xe.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=ge,Ee){j.style.color=Ee;let I=j.querySelector("svg");I&&I.setAttribute("stroke",Ee)}ee&&(j.style.borderColor=ee),j.setAttribute("aria-label","Stop voice recognition")}}catch{Ut("system")}},Ut=(l="user")=>{if(_t){if(_t=!1,sn&&(clearTimeout(sn),sn=null),Rt){try{Rt.stop()}catch{}Rt=null}if(Ke.active=!1,Xn(l),tn(),j){if(j.classList.remove("tvw-voice-recording"),Vt){j.style.backgroundColor=Vt.backgroundColor,j.style.color=Vt.color,j.style.borderColor=Vt.borderColor;let p=j.querySelector("svg");p&&p.setAttribute("stroke",Vt.color||"currentColor"),Vt=null}j.setAttribute("aria-label","Start voice recognition")}}},$s=(l,p)=>{var ye,Ve,He,ht,Ht,X,je;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let T=g("div","tvw-send-button-wrapper"),A=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let F=(ye=l==null?void 0:l.iconName)!=null?ye:"mic",ve=(Ve=p==null?void 0:p.size)!=null?Ve:"40px",ae=(He=l==null?void 0:l.iconSize)!=null?He:ve,ce=parseFloat(ae)||24,xe=(ht=l==null?void 0:l.backgroundColor)!=null?ht:p==null?void 0:p.backgroundColor,ge=(Ht=l==null?void 0:l.iconColor)!=null?Ht:p==null?void 0:p.textColor;A.style.width=ae,A.style.height=ae,A.style.minWidth=ae,A.style.minHeight=ae,A.style.fontSize="18px",A.style.lineHeight="1";let Ee=ge||"currentColor",ee=oe(F,ce,Ee,1.5);ee?(A.appendChild(ee),A.style.color=Ee):(A.textContent="\u{1F3A4}",A.style.color=Ee),xe?A.style.backgroundColor=xe:A.classList.add("tvw-bg-cw-primary"),ge?A.style.color=ge:!ge&&!(p!=null&&p.textColor)&&A.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(A.style.borderWidth=l.borderWidth,A.style.borderStyle="solid"),l!=null&&l.borderColor&&(A.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(A.style.paddingLeft=l.paddingX,A.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(A.style.paddingTop=l.paddingY,A.style.paddingBottom=l.paddingY),T.appendChild(A);let I=(X=l==null?void 0:l.tooltipText)!=null?X:"Start voice recognition";if(((je=l==null?void 0:l.showTooltip)!=null?je:!1)&&I){let Xt=g("div","tvw-send-button-tooltip");Xt.textContent=I,T.appendChild(Xt)}return{micButton:A,micButtonWrapper:T}},Bn=()=>{if(_t){let l=pe.value.trim();Ke.manuallyDeactivated=!0,tn(),Ut("user"),l&&(pe.value="",pe.style.height="auto",$.sendMessage(l))}else Ke.manuallyDeactivated=!1,tn(),vn("user")};j&&(j.addEventListener("click",Bn),it.push(()=>{Ut("system"),j&&j.removeEventListener("click",Bn)}));let Fs=s.on("assistant:complete",()=>{Vn&&(Ke.active||Ke.manuallyDeactivated||Vn==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&vn("auto")},600))});it.push(Fs);let Os=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});it.push(Os);let rn=()=>{nt(!b,"user")},Ge=null,Qe=null;if(x){let l=o.find(p=>p.renderLauncher);if(l!=null&&l.renderLauncher){let p=l.renderLauncher({config:e,defaultRenderer:()=>Cs(e,rn).element,onToggle:rn});p&&(Qe=p)}Qe||(Ge=Cs(e,rn))}Ge?t.appendChild(Ge.element):Qe&&t.appendChild(Qe),wn(),dn.render(e.suggestionChips,$,pe,void 0,e.suggestionChipsConfig),Qn(),Hn($.isStreaming()),fn(!0),Ws();let un=()=>{var h,T,A,F,ve,ae,ce,xe;let l=(T=(h=e.launcher)==null?void 0:h.sidebarMode)!=null?T:!1,p=l||((F=(A=e.launcher)==null?void 0:A.fullHeight)!=null?F:!1);if(!x){Se.style.height="",Se.style.width="";return}if(!l){let ge=(ae=(ve=e==null?void 0:e.launcher)==null?void 0:ve.width)!=null?ae:e==null?void 0:e.launcherWidth,Ee=ge!=null?ge:"min(400px, calc(100vw - 24px))";Se.style.width=Ee,Se.style.maxWidth=Ee}if(!p){let ge=window.innerHeight,Ee=64,ee=(xe=(ce=e.launcher)==null?void 0:ce.heightOffset)!=null?xe:0,I=Math.max(200,ge-Ee),me=Math.min(640,I),ye=Math.max(200,me-ee);Se.style.height=`${ye}px`}};un(),window.addEventListener("resize",un),it.push(()=>window.removeEventListener("resize",un)),mn=Fe.scrollTop;let ss=()=>{let l=Fe.scrollTop,p=Fe.scrollHeight,h=Fe.clientHeight,T=p-l-h,A=Math.abs(l-mn);if(mn=l,!Wn&&!(A<=ks)){if(!Qt&&T<Yn){en=!1,Qt=!0;return}Qt&&T>Yn&&(en=!0,kn=Date.now()+Is,Qt=!1)}};Fe.addEventListener("scroll",ss,{passive:!0}),it.push(()=>Fe.removeEventListener("scroll",ss)),it.push(()=>{Zt&&cancelAnimationFrame(Zt)});let rs=()=>{Q&&(Yt&&(Q.removeEventListener("click",Yt),Yt=null),x?(Q.style.display="",Yt=()=>{b=!1,wn()},Q.addEventListener("click",Yt)):Q.style.display="none")};rs(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{$.clearMessages();try{localStorage.removeItem(zn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zn}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==zn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}a={},S.syncFromMetadata(),P==null||P.clear(),z==null||z.update()})})(),gt.addEventListener("submit",Zn),pe.addEventListener("keydown",es),pe.addEventListener("paste",ts),it.push(()=>{gt.removeEventListener("submit",Zn),pe.removeEventListener("keydown",es),pe.removeEventListener("paste",ts)}),it.push(()=>{$.cancel()}),Ge?it.push(()=>{Ge==null||Ge.destroy()}):Qe&&it.push(()=>{Qe==null||Qe.remove()});let Pt={update(l){var Ur,zr,Jr,Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,fo,ho,wo,vo,yo,bo,xo,Co,So,Ao,Eo,To,Mo,Lo,Io,ko,Wo,Po,Ho,Bo,Ro,$o,Fo,Oo,No,Do,_o,jo,qo,Uo,zo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,fi,hi,wi,vi,yi,bi,xi,Ci;let p=e.toolCall,h=e.colorScheme;e={...e,...l},In(),er(t,e),e.colorScheme!==h&&Jn();let T=Es.getForInstance(e.plugins);o.length=0,o.push(...T),x=(zr=(Ur=e.launcher)==null?void 0:Ur.enabled)!=null?zr:!0,E=(Kr=(Jr=e.launcher)==null?void 0:Jr.autoExpand)!=null?Kr:!1,Y=(Vr=(Yr=e.features)==null?void 0:Yr.showReasoning)!=null?Vr:!0,_=(Gr=(Xr=e.features)==null?void 0:Xr.showToolCalls)!=null?Gr:!0;let A=q;if(q=(Zr=(Qr=e.features)==null?void 0:Qr.showEventStreamToggle)!=null?Zr:!1,q&&!A){if(P||(B=new As(ue),P=new Ss(Z,B),B.open().then(()=>P==null?void 0:P.restore()).catch(()=>{}),$.setSSEEventCallback((k,Te)=>{P.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:k,timestamp:Date.now(),payload:JSON.stringify(Te)})})),!J&&te){let k=(to=(eo=e.features)==null?void 0:eo.eventStream)==null?void 0:to.classNames,Te="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"+(k!=null&&k.toggleButton?" "+k.toggleButton:"");J=g("button",Te),J.style.width="28px",J.style.height="28px",J.type="button",J.setAttribute("aria-label","Event Stream"),J.title="Event Stream";let Ze=oe("activity","18px","currentColor",1.5);Ze&&J.appendChild(Ze);let be=se.clearChatButtonWrapper,Re=se.closeButtonWrapper,wt=be||Re;wt&&wt.parentNode===te?te.insertBefore(J,wt):te.appendChild(J),J.addEventListener("click",()=>{Ce?Ne():Me()})}}else!q&&A&&(Ne(),J&&(J.remove(),J=null),P==null||P.clear(),B==null||B.destroy(),P=null,B=null);if(((no=e.launcher)==null?void 0:no.enabled)===!1&&Ge&&(Ge.destroy(),Ge=null),((so=e.launcher)==null?void 0:so.enabled)===!1&&Qe&&(Qe.remove(),Qe=null),((ro=e.launcher)==null?void 0:ro.enabled)!==!1&&!Ge&&!Qe){let k=o.find(Te=>Te.renderLauncher);if(k!=null&&k.renderLauncher){let Te=k.renderLauncher({config:e,defaultRenderer:()=>Cs(e,rn).element,onToggle:rn});Te&&(Qe=Te,t.appendChild(Qe))}Qe||(Ge=Cs(e,rn),t.appendChild(Ge.element))}Ge&&Ge.update(e),bt&&((oo=e.launcher)==null?void 0:oo.title)!==void 0&&(bt.textContent=e.launcher.title),xt&&((io=e.launcher)==null?void 0:io.subtitle)!==void 0&&(xt.textContent=e.launcher.subtitle);let F=(ao=e.layout)==null?void 0:ao.header;if((F==null?void 0:F.layout)!==V&&te){let k=F?Fn(e,F,{showClose:x,onClose:()=>nt(!1,"user")}):an({config:e,showClose:x,onClose:()=>nt(!1,"user")});te.replaceWith(k.header),te=k.header,We=k.iconHolder,bt=k.headerTitle,xt=k.headerSubtitle,Q=k.closeButton,V=F==null?void 0:F.layout}else if(F&&(We&&(We.style.display=F.showIcon===!1?"none":""),bt&&(bt.style.display=F.showTitle===!1?"none":""),xt&&(xt.style.display=F.showSubtitle===!1?"none":""),Q&&(Q.style.display=F.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let k=F.showClearChat;if(k!==void 0){se.clearChatButtonWrapper.style.display=k?"":"none";let{closeButtonWrapper:Te}=se;Te&&!Te.classList.contains("tvw-absolute")&&(k?Te.classList.remove("tvw-ml-auto"):Te.classList.add("tvw-ml-auto"))}}let ae=((lo=e.layout)==null?void 0:lo.showHeader)!==!1;te&&(te.style.display=ae?"":"none");let ce=((co=e.layout)==null?void 0:co.showFooter)!==!1;Oe&&(Oe.style.display=ce?"":"none"),x!==W?x?nt(E,"auto"):(b=!0,wn()):E!==C&&nt(E,"auto"),C=E,W=x,un(),rs(),JSON.stringify(l.toolCall)!==JSON.stringify(p)&&$&&hn(Xe,$.getMessages(),ne);let ee=(uo=e.launcher)!=null?uo:{},I=(po=ee.headerIconHidden)!=null?po:!1,me=(mo=(go=e.layout)==null?void 0:go.header)==null?void 0:mo.showIcon,ye=I||me===!1,Ve=ee.headerIconName,He=(fo=ee.headerIconSize)!=null?fo:"48px";if(We){let k=he.querySelector(".tvw-border-b-cw-divider"),Te=k==null?void 0:k.querySelector(".tvw-flex-col");if(ye)We.style.display="none",k&&Te&&!k.contains(Te)&&k.insertBefore(Te,k.firstChild);else{if(We.style.display="",We.style.height=He,We.style.width=He,k&&Te&&(k.contains(We)?We.nextSibling!==Te&&(We.remove(),k.insertBefore(We,Te)):k.insertBefore(We,Te)),Ve){let be=parseFloat(He)||24,Re=oe(Ve,be*.6,"#ffffff",2);Re?We.replaceChildren(Re):We.textContent=(ho=ee.agentIconText)!=null?ho:"\u{1F4AC}"}else if(ee.iconUrl){let be=We.querySelector("img");if(be)be.src=ee.iconUrl,be.style.height=He,be.style.width=He;else{let Re=document.createElement("img");Re.src=ee.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=He,Re.style.width=He,We.replaceChildren(Re)}}else{let be=We.querySelector("svg"),Re=We.querySelector("img");(be||Re)&&We.replaceChildren(),We.textContent=(wo=ee.agentIconText)!=null?wo:"\u{1F4AC}"}let Ze=We.querySelector("img");Ze&&(Ze.style.height=He,Ze.style.width=He)}}let ht=(yo=(vo=e.layout)==null?void 0:vo.header)==null?void 0:yo.showTitle,Ht=(xo=(bo=e.layout)==null?void 0:bo.header)==null?void 0:xo.showSubtitle;if(bt&&(bt.style.display=ht===!1?"none":""),xt&&(xt.style.display=Ht===!1?"none":""),Q){((So=(Co=e.layout)==null?void 0:Co.header)==null?void 0:So.showCloseButton)===!1?Q.style.display="none":Q.style.display="";let Te=(Ao=ee.closeButtonSize)!=null?Ao:"32px",Ze=(Eo=ee.closeButtonPlacement)!=null?Eo:"inline";Q.style.height=Te,Q.style.width=Te;let{closeButtonWrapper:be}=se,Re=Ze==="top-right",wt=be==null?void 0:be.classList.contains("tvw-absolute");if(be&&Re!==wt)if(be.remove(),Re)be.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",he.style.position="relative",he.appendChild(be);else{let Le=(Mo=(To=ee.clearChat)==null?void 0:To.placement)!=null?Mo:"inline",At=(Io=(Lo=ee.clearChat)==null?void 0:Lo.enabled)!=null?Io:!0;be.className=At&&Le==="inline"?"":"tvw-ml-auto";let Ot=he.querySelector(".tvw-border-b-cw-divider");Ot&&Ot.appendChild(be)}if(ee.closeButtonColor?(Q.style.color=ee.closeButtonColor,Q.classList.remove("tvw-text-cw-muted")):(Q.style.color="",Q.classList.add("tvw-text-cw-muted")),ee.closeButtonBackgroundColor?(Q.style.backgroundColor=ee.closeButtonBackgroundColor,Q.classList.remove("hover:tvw-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:tvw-bg-gray-100")),ee.closeButtonBorderWidth||ee.closeButtonBorderColor){let Le=ee.closeButtonBorderWidth||"0px",At=ee.closeButtonBorderColor||"transparent";Q.style.border=`${Le} solid ${At}`,Q.classList.remove("tvw-border-none")}else Q.style.border="",Q.classList.add("tvw-border-none");ee.closeButtonBorderRadius?(Q.style.borderRadius=ee.closeButtonBorderRadius,Q.classList.remove("tvw-rounded-full")):(Q.style.borderRadius="",Q.classList.add("tvw-rounded-full")),ee.closeButtonPaddingX?(Q.style.paddingLeft=ee.closeButtonPaddingX,Q.style.paddingRight=ee.closeButtonPaddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),ee.closeButtonPaddingY?(Q.style.paddingTop=ee.closeButtonPaddingY,Q.style.paddingBottom=ee.closeButtonPaddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let kt=(ko=ee.closeButtonIconName)!=null?ko:"x",jt=(Wo=ee.closeButtonIconText)!=null?Wo:"\xD7";Q.innerHTML="";let Ft=oe(kt,"20px",ee.closeButtonColor||"",2);Ft?Q.appendChild(Ft):Q.textContent=jt;let lt=(Po=ee.closeButtonTooltipText)!=null?Po:"Close chat",qt=(Ho=ee.closeButtonShowTooltip)!=null?Ho:!0;if(Q.setAttribute("aria-label",lt),be&&(be._cleanupTooltip&&(be._cleanupTooltip(),delete be._cleanupTooltip),qt&<)){let Le=null,At=()=>{if(Le||!Q)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=lt;let vs=g("div");vs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(vs);let xn=Q.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${xn.left+xn.width/2}px`,Le.style.top=`${xn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ot=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};be.addEventListener("mouseenter",At),be.addEventListener("mouseleave",Ot),Q.addEventListener("focus",At),Q.addEventListener("blur",Ot),be._cleanupTooltip=()=>{Ot(),be&&(be.removeEventListener("mouseenter",At),be.removeEventListener("mouseleave",Ot)),Q&&(Q.removeEventListener("focus",At),Q.removeEventListener("blur",Ot))}}}let{clearChatButton:X,clearChatButtonWrapper:je}=se;if(X){let k=(Bo=ee.clearChat)!=null?Bo:{},Te=(Ro=k.enabled)!=null?Ro:!0,Ze=(Fo=($o=e.layout)==null?void 0:$o.header)==null?void 0:Fo.showClearChat,be=Ze!==void 0?Ze:Te,Re=(Oo=k.placement)!=null?Oo:"inline";if(je){je.style.display=be?"":"none";let{closeButtonWrapper:wt}=se;wt&&!wt.classList.contains("tvw-absolute")&&(be?wt.classList.remove("tvw-ml-auto"):wt.classList.add("tvw-ml-auto"));let kt=Re==="top-right",jt=je.classList.contains("tvw-absolute");if(kt!==jt&&be){if(je.remove(),kt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",he.style.position="relative",he.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let lt=he.querySelector(".tvw-border-b-cw-divider"),qt=se.closeButtonWrapper;lt&&qt&&qt.parentElement===lt?lt.insertBefore(je,qt):lt&<.appendChild(je)}let Ft=se.closeButtonWrapper;Ft&&!Ft.classList.contains("tvw-absolute")&&(kt?Ft.classList.add("tvw-ml-auto"):Ft.classList.remove("tvw-ml-auto"))}}if(be){let wt=(No=k.size)!=null?No:"32px";X.style.height=wt,X.style.width=wt;let kt=(Do=k.iconName)!=null?Do:"refresh-cw",jt=(_o=k.iconColor)!=null?_o:"";X.innerHTML="";let Ft=oe(kt,"20px",jt||"",2);if(Ft&&X.appendChild(Ft),jt?(X.style.color=jt,X.classList.remove("tvw-text-cw-muted")):(X.style.color="",X.classList.add("tvw-text-cw-muted")),k.backgroundColor?(X.style.backgroundColor=k.backgroundColor,X.classList.remove("hover:tvw-bg-gray-100")):(X.style.backgroundColor="",X.classList.add("hover:tvw-bg-gray-100")),k.borderWidth||k.borderColor){let Le=k.borderWidth||"0px",At=k.borderColor||"transparent";X.style.border=`${Le} solid ${At}`,X.classList.remove("tvw-border-none")}else X.style.border="",X.classList.add("tvw-border-none");k.borderRadius?(X.style.borderRadius=k.borderRadius,X.classList.remove("tvw-rounded-full")):(X.style.borderRadius="",X.classList.add("tvw-rounded-full")),k.paddingX?(X.style.paddingLeft=k.paddingX,X.style.paddingRight=k.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),k.paddingY?(X.style.paddingTop=k.paddingY,X.style.paddingBottom=k.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let lt=(jo=k.tooltipText)!=null?jo:"Clear chat",qt=(qo=k.showTooltip)!=null?qo:!0;if(X.setAttribute("aria-label",lt),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),qt&<)){let Le=null,At=()=>{if(Le||!X)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=lt;let vs=g("div");vs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(vs);let xn=X.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${xn.left+xn.width/2}px`,Le.style.top=`${xn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ot=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};je.addEventListener("mouseenter",At),je.addEventListener("mouseleave",Ot),X.addEventListener("focus",At),X.addEventListener("blur",Ot),je._cleanupTooltip=()=>{Ot(),je&&(je.removeEventListener("mouseenter",At),je.removeEventListener("mouseleave",Ot)),X&&(X.removeEventListener("focus",At),X.removeEventListener("blur",Ot))}}}}let Xt=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ts],zt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Mn.message,Mn.messageAndClick];S=Ms({parsers:Xt,handlers:zt,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ne=la(e,S,R),$.updateConfig(e),hn(Xe,$.getMessages(),ne),dn.render(e.suggestionChips,$,pe,void 0,e.suggestionChipsConfig),Qn(),Hn($.isStreaming());let pn=((Uo=e.voiceRecognition)==null?void 0:Uo.enabled)===!0,Ns=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(pn&&Ns)if(!j||!et){let k=$s(e.voiceRecognition,e.sendButton);k&&(j=k.micButton,et=k.micButtonWrapper,Lt.insertBefore(et,pt),j.addEventListener("click",Bn),j.disabled=$.isStreaming())}else{let k=(zo=e.voiceRecognition)!=null?zo:{},Te=(Jo=e.sendButton)!=null?Jo:{},Ze=(Ko=k.iconName)!=null?Ko:"mic",be=(Yo=Te.size)!=null?Yo:"40px",Re=(Vo=k.iconSize)!=null?Vo:be,wt=parseFloat(Re)||24;j.style.width=Re,j.style.height=Re,j.style.minWidth=Re,j.style.minHeight=Re;let kt=(Go=(Xo=k.iconColor)!=null?Xo:Te.textColor)!=null?Go:"currentColor";j.innerHTML="";let jt=oe(Ze,wt,kt,2);jt?j.appendChild(jt):j.textContent="\u{1F3A4}";let Ft=(Qo=k.backgroundColor)!=null?Qo:Te.backgroundColor;Ft?(j.style.backgroundColor=Ft,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&&!Te.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),k.borderWidth?(j.style.borderWidth=k.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),k.borderColor?j.style.borderColor=k.borderColor:j.style.borderColor="",k.paddingX?(j.style.paddingLeft=k.paddingX,j.style.paddingRight=k.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),k.paddingY?(j.style.paddingTop=k.paddingY,j.style.paddingBottom=k.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let lt=et==null?void 0:et.querySelector(".tvw-send-button-tooltip"),qt=(Zo=k.tooltipText)!=null?Zo:"Start voice recognition";if(((ei=k.showTooltip)!=null?ei:!1)&&qt)if(lt)lt.textContent=qt,lt.style.display="";else{let At=document.createElement("div");At.className="tvw-send-button-tooltip",At.textContent=qt,et==null||et.insertBefore(At,j)}else lt&&(lt.style.display="none");et.style.display="",j.disabled=$.isStreaming()}else j&&et&&(et.style.display="none",_t&&Ut());if(((ti=e.attachments)==null?void 0:ti.enabled)===!0)if(!K||!Ie){let k=(ni=e.attachments)!=null?ni:{},Ze=(ri=((si=e.sendButton)!=null?si:{}).size)!=null?ri:"40px";we||(we=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),we.style.display="none",gt.insertBefore(we,pe)),O||(O=document.createElement("input"),O.type="file",O.accept=((oi=k.allowedTypes)!=null?oi:gn).join(","),O.multiple=((ii=k.maxFiles)!=null?ii:4)>1,O.style.display="none",O.setAttribute("aria-label","Attach files"),gt.insertBefore(O,pe)),K=g("div","tvw-send-button-wrapper"),Ie=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),Ie.type="button",Ie.setAttribute("aria-label",(ai=k.buttonTooltipText)!=null?ai:"Attach file");let be=(li=k.buttonIconName)!=null?li:"paperclip",Re=Ze,wt=parseFloat(Re)||40,kt=Math.round(wt*.6);Ie.style.width=Re,Ie.style.height=Re,Ie.style.minWidth=Re,Ie.style.minHeight=Re,Ie.style.fontSize="18px",Ie.style.lineHeight="1",Ie.style.backgroundColor="transparent",Ie.style.color="var(--cw-primary, #111827)",Ie.style.border="none",Ie.style.borderRadius="6px",Ie.style.transition="background-color 0.15s ease",Ie.addEventListener("mouseenter",()=>{Ie.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),Ie.addEventListener("mouseleave",()=>{Ie.style.backgroundColor="transparent"});let jt=oe(be,kt,"currentColor",1.5);jt?Ie.appendChild(jt):Ie.textContent="\u{1F4CE}",Ie.addEventListener("click",qt=>{qt.preventDefault(),O==null||O.click()}),K.appendChild(Ie);let Ft=(di=k.buttonTooltipText)!=null?di:"Attach file",lt=g("div","tvw-send-button-tooltip");lt.textContent=Ft,K.appendChild(lt),Wt.append(K),!de&&O&&we&&(de=An.fromConfig(k),de.setPreviewsContainer(we),O.addEventListener("change",async()=>{de&&(O!=null&&O.files)&&(await de.handleFileSelect(O.files),O.value="")}))}else{K.style.display="";let k=(ci=e.attachments)!=null?ci:{};O&&(O.accept=((ui=k.allowedTypes)!=null?ui:gn).join(","),O.multiple=((pi=k.maxFiles)!=null?pi:4)>1),de&&de.updateConfig({allowedTypes:k.allowedTypes,maxFileSize:k.maxFileSize,maxFiles:k.maxFiles})}else K&&(K.style.display="none"),de&&de.clearAttachments();let ut=(gi=e.sendButton)!=null?gi:{},Ds=(mi=ut.useIcon)!=null?mi:!1,ms=(fi=ut.iconText)!=null?fi:"\u2191",yn=ut.iconName,bn=(hi=ut.tooltipText)!=null?hi:"Send message",wa=(wi=ut.showTooltip)!=null?wi:!1,fs=(vi=ut.size)!=null?vi:"40px",_s=ut.backgroundColor,Gt=ut.textColor;if(Ds){if(G.style.width=fs,G.style.height=fs,G.style.minWidth=fs,G.style.minHeight=fs,G.style.fontSize="18px",G.style.lineHeight="1",G.innerHTML="",yn){let k=parseFloat(fs)||24,Te=Gt&&typeof Gt=="string"&&Gt.trim()?Gt.trim():"currentColor",Ze=oe(yn,k,Te,2);Ze?(G.appendChild(Ze),G.style.color=Te):(G.textContent=ms,Gt?G.style.color=Gt:G.classList.add("tvw-text-white"))}else G.textContent=ms,Gt?G.style.color=Gt:G.classList.add("tvw-text-white");G.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",_s?(G.style.backgroundColor=_s,G.classList.remove("tvw-bg-cw-primary")):G.classList.add("tvw-bg-cw-primary")}else G.textContent=(bi=(yi=e.copy)==null?void 0:yi.sendButtonLabel)!=null?bi:"Send",G.style.width="",G.style.height="",G.style.minWidth="",G.style.minHeight="",G.style.fontSize="",G.style.lineHeight="",G.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",_s?(G.style.backgroundColor=_s,G.classList.remove("tvw-bg-cw-accent")):G.classList.add("tvw-bg-cw-accent"),Gt?G.style.color=Gt:G.classList.add("tvw-text-white");ut.borderWidth?(G.style.borderWidth=ut.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ut.borderColor?G.style.borderColor=ut.borderColor:G.style.borderColor="",ut.paddingX?(G.style.paddingLeft=ut.paddingX,G.style.paddingRight=ut.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ut.paddingY?(G.style.paddingTop=ut.paddingY,G.style.paddingBottom=ut.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let hs=pt==null?void 0:pt.querySelector(".tvw-send-button-tooltip");if(wa&&bn)if(hs)hs.textContent=bn,hs.style.display="";else{let k=document.createElement("div");k.className="tvw-send-button-tooltip",k.textContent=bn,pt==null||pt.insertBefore(k,G)}else hs&&(hs.style.display="none");let ws=(xi=e.statusIndicator)!=null?xi:{},va=(Ci=ws.visible)!=null?Ci:!0;if(vt.style.display=va?"":"none",$){let k=$.getStatus(),Te=Ze=>{var be,Re,wt,kt;return Ze==="idle"?(be=ws.idleText)!=null?be:Bt.idle:Ze==="connecting"?(Re=ws.connectingText)!=null?Re:Bt.connecting:Ze==="connected"?(wt=ws.connectedText)!=null?wt:Bt.connected:Ze==="error"?(kt=ws.errorText)!=null?kt:Bt.error:Bt[Ze]};vt.textContent=Te(k)}},open(){x&&nt(!0,"api")},close(){x&&nt(!1,"api")},toggle(){x&&nt(!b,"api")},clearChat(){$.clearMessages();try{localStorage.removeItem(zn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zn}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==zn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}a={},S.syncFromMetadata(),P==null||P.clear(),z==null||z.update()},setMessage(l){return!pe||$.isStreaming()?!1:(!b&&x&&nt(!0,"system"),pe.value=l,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let p=(l==null?void 0:l.trim())||pe.value.trim();return p?(!b&&x&&nt(!0,"system"),pe.value="",pe.style.height="auto",$.sendMessage(p),!0):!1},startVoiceRecognition(){return _t||$.isStreaming()||!ns()?!1:(!b&&x&&nt(!0,"system"),Ke.manuallyDeactivated=!1,tn(),vn("user"),!0)},stopVoiceRecognition(){return _t?(Ke.manuallyDeactivated=!0,tn(),Ut("user"),!0):!1},injectMessage(l){return!b&&x&&nt(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!b&&x&&nt(!0,"system");let p=$.injectAssistantMessage(l);return N&&(N=!1,M&&(clearTimeout(M),M=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),p},injectUserMessage(l){return!b&&x&&nt(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!b&&x&&nt(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!b&&x&&nt(!0,"system"),$.injectMessageBatch(l)},injectTestMessage(l){!b&&x&&nt(!0,"system"),$.injectTestEvent(l)},async connectStream(l,p){return $.connectStream(l,p)},__pushEventStreamEvent(l){P&&P.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!q||!P||Me()},hideEventStream(){Ce&&Ne()},isEventStreamVisible(){return Ce},async resolveApproval(l,p){let T=$.getMessages().find(A=>{var F;return A.variant==="approval"&&((F=A.approval)==null?void 0:F.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);return $.resolveApproval(T.approval,p)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){d(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return x&&b},isVoiceActive(){return Ke.active},getState(){return{open:x&&b,launcherEnabled:x,voiceActive:Ke.active,streaming:$.isStreaming()}},showCSATFeedback(l){!b&&x&&nt(!0,"system");let p=Xe.querySelector(".tvw-feedback-container");p&&p.remove();let h=lr({onSubmit:async(T,A)=>{var F;$.isClientTokenMode()&&await $.submitCSATFeedback(T,A),(F=l==null?void 0:l.onSubmit)==null||F.call(l,T,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!b&&x&&nt(!0,"system");let p=Xe.querySelector(".tvw-feedback-container");p&&p.remove();let h=dr({onSubmit:async(T,A)=>{var F;$.isClientTokenMode()&&await $.submitNPSFeedback(T,A),(F=l==null?void 0:l.onSubmit)==null||F.call(l,T,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return $.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return $.submitNPSFeedback(l,p)},destroy(){it.forEach(l=>l()),$e.remove(),Ge==null||Ge.destroy(),Qe==null||Qe.remove(),Yt&&Q.removeEventListener("click",Yt)}};if((((St=r==null?void 0:r.debugTools)!=null?St:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:Pt,getMessages:Pt.getMessages,getStatus:Pt.getStatus,getMetadata:Pt.getPersistentMetadata,updateMetadata:Pt.updatePersistentMetadata,clearHistory:()=>Pt.clearChat(),setVoiceActive:h=>h?Pt.startVoiceRecognition():Pt.stopVoiceRecognition()};window.AgentWidgetBrowser=p,it.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(q&&typeof window!="undefined"){let l=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),p=T=>{let A=T.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&Pt.showEventStream()},h=T=>{let A=T.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&Pt.hideEventStream()};window.addEventListener("persona:showEventStream",p),window.addEventListener("persona:hideEventStream",h),it.push(()=>{window.removeEventListener("persona:showEventStream",p),window.removeEventListener("persona:hideEventStream",h)})}let $t=hl(e.persistState);if($t&&x){let l=wl($t.storage),p=`${$t.keyPrefix}widget-open`,h=`${$t.keyPrefix}widget-voice`,T=`${$t.keyPrefix}widget-voice-mode`;if(l){let A=((ft=$t.persist)==null?void 0:ft.openState)&&l.getItem(p)==="true",F=((De=$t.persist)==null?void 0:De.voiceState)&&l.getItem(h)==="true",ve=((qe=$t.persist)==null?void 0:qe.voiceState)&&l.getItem(T)==="true";if(A&&setTimeout(()=>{Pt.open(),setTimeout(()=>{var ae;if(F||ve)Pt.startVoiceRecognition();else if((ae=$t.persist)!=null&&ae.focusInput){let ce=t.querySelector("textarea");ce&&ce.focus()}},100)},0),(ct=$t.persist)!=null&&ct.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Ue=$t.persist)!=null&&Ue.voiceState&&(s.on("voice:state",ae=>{l.setItem(h,ae.active?"true":"false")}),s.on("user:message",ae=>{l.setItem(T,ae.viaVoice?"true":"false")})),$t.clearOnChatClear){let ae=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(T)},ce=()=>ae();window.addEventListener("persona:clear-chat",ce),it.push(()=>{window.removeEventListener("persona:clear-chat",ce)})}}}return Pt};var _r={},vl=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let n=document.querySelector(t);if(!n)throw new Error(`Chat widget target "${t}" was not found`);return n}return t},yl=()=>{try{if(typeof _r!="undefined"&&_r.url)return new URL("../widget.css",_r.url).href}catch{}return null},da=t=>{let n=yl(),r=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);t.insertBefore(o,t.firstChild)};if(t instanceof ShadowRoot)if(n){let e=document.createElement("link");e.rel="stylesheet",e.href=n,e.setAttribute("data-persona","true"),t.insertBefore(e,t.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},jr=t=>{var c,v,d,f;let n=vl(t.target),r=document.createElement("div");r.className="persona-host";let e=(d=(v=(c=t.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?d:!0;e||(r.style.height="100%"),n.appendChild(r);let o=t.useShadowDom===!0,s,i;if(o){let w=r.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),da(w)}else i=r,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),da(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=cr(s,t.config,{debugTools:t.debugTools});(f=t.onReady)==null||f.call(t);let u={...a,host:r,destroy(){a.destroy(),r.remove(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}};return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=u),u};var ca={name:"@runtypelabs/persona",version:"1.45.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var Ln=ca.version;function ln(t){if(t!==void 0)return typeof t=="string"?t:Array.isArray(t)?`[${t.map(n=>n.toString()).join(", ")}]`:t.toString()}function xl(t){if(t)return{getHeaders:ln(t.getHeaders),onFeedback:ln(t.onFeedback),onCopy:ln(t.onCopy),requestMiddleware:ln(t.requestMiddleware),actionHandlers:ln(t.actionHandlers),actionParsers:ln(t.actionParsers),postprocessMessage:ln(t.postprocessMessage),contextProviders:ln(t.contextProviders),streamParser:ln(t.streamParser)}}var ua=`({ text, message }: any) => {
|
|
61
61
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
62
62
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
63
63
|
let cleanJson = jsonSource
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
71
71
|
} catch (e) { return null; }
|
|
72
72
|
return null;
|
|
73
|
-
}`,
|
|
73
|
+
}`,pa=`function(ctx) {
|
|
74
74
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
75
75
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
76
76
|
var cleanJson = jsonSource
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
84
84
|
} catch (e) { return null; }
|
|
85
85
|
return null;
|
|
86
|
-
}`,
|
|
86
|
+
}`,ga=`(action: any, context: any) => {
|
|
87
87
|
if (action.type !== 'nav_then_click') return;
|
|
88
88
|
const payload = action.payload || action.raw || {};
|
|
89
89
|
const url = payload?.page;
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
101
101
|
window.location.href = targetUrl;
|
|
102
102
|
return { handled: true, displayText: text };
|
|
103
|
-
}`,
|
|
103
|
+
}`,ma=`function(action, context) {
|
|
104
104
|
if (action.type !== 'nav_then_click') return;
|
|
105
105
|
var payload = action.payload || action.raw || {};
|
|
106
106
|
var url = payload.page;
|
|
@@ -117,24 +117,24 @@
|
|
|
117
117
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
118
118
|
window.location.href = targetUrl;
|
|
119
119
|
return { handled: true, displayText: text };
|
|
120
|
-
}`,
|
|
120
|
+
}`,Cl=`(parsed: any) => {
|
|
121
121
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
122
122
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
123
123
|
if (parsed.action === 'message') return parsed.text || '';
|
|
124
124
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
125
125
|
return parsed.text || null;
|
|
126
|
-
}`,
|
|
126
|
+
}`,Sl=`function(parsed) {
|
|
127
127
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
128
128
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
129
129
|
if (parsed.action === 'message') return parsed.text || '';
|
|
130
130
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
131
131
|
return parsed.text || null;
|
|
132
|
-
}`;function
|
|
133
|
-
`)}function
|
|
134
|
-
`)}function vl(e,n){let r=n==null?void 0:n.hooks,t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),e.theme&&(t.push(" theme: {"),Object.entries(e.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...Vs(e," ")),t.push(...Xs(e," ",r)),t.push(...Gs(e," ")),t.push(...Qs(e," ")),r!=null&&r.getHeaders&&t.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&t.push(` contextProviders: ${r.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?t.push(` streamParser: ${r.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${gl}),`)),r!=null&&r.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${la}`),t.push(" ],")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Parser for markdown-wrapped JSON"),t.push(` ${la}`),t.push(" ],")),r!=null&&r.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${r.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${ca}`),t.push(" ],")):(t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(` ${ca}`),t.push(" ],")),r!=null&&r.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),t.push(" const merged = customResult || payload;"),t.push(" return {"),t.push(" ...merged,"),t.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),t.push(" };"),t.push(" }")):(t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }")),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('persona:message', handleMessage);"),t.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('persona:message', handleMessage);"),t.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
|
|
135
|
-
`)}function
|
|
136
|
-
`)}function
|
|
132
|
+
}`;function Al(t){if(!t)return null;let n=t.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function ur(t){var n,r;return(r=(n=t.parserType)!=null?n:Al(t.streamParser))!=null?r:"plain"}function pr(t,n){let r=[];return t.toolCall&&(r.push(`${n}toolCall: {`),Object.entries(t.toolCall).forEach(([e,o])=>{typeof o=="string"&&r.push(`${n} ${e}: "${o}",`)}),r.push(`${n}},`)),r}function gr(t,n,r){let e=[],o=t.messageActions&&Object.entries(t.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||s)&&(e.push(`${n}messageActions: {`),t.messageActions&&Object.entries(t.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?e.push(`${n} ${i}: "${a}",`):typeof a=="boolean"&&e.push(`${n} ${i}: ${a},`))}),r!=null&&r.onFeedback&&e.push(`${n} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&e.push(`${n} onCopy: ${r.onCopy},`),e.push(`${n}},`)),e}function mr(t,n){let r=[];if(t.markdown){let e=t.markdown.options&&Object.keys(t.markdown.options).length>0,o=t.markdown.disableDefaultStyles!==void 0;(e||o)&&(r.push(`${n}markdown: {`),e&&(r.push(`${n} options: {`),Object.entries(t.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`)}),r.push(`${n} },`)),o&&r.push(`${n} disableDefaultStyles: ${t.markdown.disableDefaultStyles},`),r.push(`${n}},`))}return r}function fr(t,n){let r=[];if(t.layout){let e=t.layout.header&&Object.keys(t.layout.header).some(s=>s!=="render"),o=t.layout.messages&&Object.keys(t.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||o)&&(r.push(`${n}layout: {`),e&&(r.push(`${n} header: {`),Object.entries(t.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),o&&(r.push(`${n} messages: {`),Object.entries(t.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${n} avatar: {`),Object.entries(i).forEach(([a,u])=>{typeof u=="string"?r.push(`${n} ${a}: "${u}",`):typeof u=="boolean"&&r.push(`${n} ${a}: ${u},`)}),r.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([u])=>u!=="format")&&(r.push(`${n} timestamp: {`),Object.entries(i).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?r.push(`${n} ${u}: "${c}",`):typeof c=="boolean"&&r.push(`${n} ${u}: ${c},`))}),r.push(`${n} },`)):typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),r.push(`${n}},`))}return r}function qr(t,n){let r=[];return t&&(t.getHeaders&&r.push(`${n}getHeaders: ${t.getHeaders},`),t.requestMiddleware&&r.push(`${n}requestMiddleware: ${t.requestMiddleware},`),t.actionParsers&&r.push(`${n}actionParsers: ${t.actionParsers},`),t.actionHandlers&&r.push(`${n}actionHandlers: ${t.actionHandlers},`),t.contextProviders&&r.push(`${n}contextProviders: ${t.contextProviders},`),t.streamParser&&r.push(`${n}streamParser: ${t.streamParser},`)),r}function fa(t,n="esm",r){let e={...t};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:xl(r.hooks)}:void 0;return n==="esm"?El(e,o):n==="script-installer"?Ll(e):n==="script-advanced"?kl(e,o):n==="react-component"?Tl(e,o):n==="react-advanced"?Ml(e,o):Il(e,o)}function El(t,n){let r=n==null?void 0:n.hooks,e=ur(t),o=e!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return t.apiUrl&&s.push(` apiUrl: "${t.apiUrl}",`),t.clientToken&&s.push(` clientToken: "${t.clientToken}",`),t.flowId&&s.push(` flowId: "${t.flowId}",`),o&&s.push(` parserType: "${e}",`),t.theme&&(s.push(" theme: {"),Object.entries(t.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.launcher&&(s.push(" launcher: {"),Object.entries(t.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.copy&&(s.push(" copy: {"),Object.entries(t.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.sendButton&&(s.push(" sendButton: {"),Object.entries(t.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(t.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(t.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.features&&(s.push(" features: {"),Object.entries(t.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),t.suggestionChips&&t.suggestionChips.length>0&&(s.push(" suggestionChips: ["),t.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),t.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),t.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${t.suggestionChipsConfig.fontFamily}",`),t.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${t.suggestionChipsConfig.fontWeight}",`),t.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${t.suggestionChipsConfig.paddingX}",`),t.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${t.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...pr(t," ")),s.push(...gr(t," ",r)),s.push(...mr(t," ")),s.push(...fr(t," ")),s.push(...qr(r," ")),t.debug&&s.push(` debug: ${t.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
133
|
+
`)}function Tl(t,n){let r=n==null?void 0:n.hooks,e=ur(t),o=e!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return t.apiUrl&&s.push(` apiUrl: "${t.apiUrl}",`),t.clientToken&&s.push(` clientToken: "${t.clientToken}",`),t.flowId&&s.push(` flowId: "${t.flowId}",`),o&&s.push(` parserType: "${e}",`),t.theme&&(s.push(" theme: {"),Object.entries(t.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.launcher&&(s.push(" launcher: {"),Object.entries(t.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.copy&&(s.push(" copy: {"),Object.entries(t.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.sendButton&&(s.push(" sendButton: {"),Object.entries(t.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(t.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(t.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.features&&(s.push(" features: {"),Object.entries(t.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),t.suggestionChips&&t.suggestionChips.length>0&&(s.push(" suggestionChips: ["),t.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),t.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),t.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${t.suggestionChipsConfig.fontFamily}",`),t.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${t.suggestionChipsConfig.fontWeight}",`),t.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${t.suggestionChipsConfig.paddingX}",`),t.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${t.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...pr(t," ")),s.push(...gr(t," ",r)),s.push(...mr(t," ")),s.push(...fr(t," ")),s.push(...qr(r," ")),t.debug&&s.push(` debug: ${t.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
|
|
134
|
+
`)}function Ml(t,n){let r=n==null?void 0:n.hooks,e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return t.apiUrl&&e.push(` apiUrl: "${t.apiUrl}",`),t.clientToken&&e.push(` clientToken: "${t.clientToken}",`),t.flowId&&e.push(` flowId: "${t.flowId}",`),t.theme&&(e.push(" theme: {"),Object.entries(t.theme).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),t.launcher&&(e.push(" launcher: {"),Object.entries(t.launcher).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),t.copy&&(e.push(" copy: {"),Object.entries(t.copy).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),t.sendButton&&(e.push(" sendButton: {"),Object.entries(t.sendButton).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),t.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(t.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"?e.push(` ${o}: ${s},`):typeof s=="number"&&e.push(` ${o}: ${s},`)}),e.push(" },")),t.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(t.statusIndicator).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),t.features&&(e.push(" features: {"),Object.entries(t.features).forEach(([o,s])=>{e.push(` ${o}: ${s},`)}),e.push(" },")),t.suggestionChips&&t.suggestionChips.length>0&&(e.push(" suggestionChips: ["),t.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),t.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),t.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${t.suggestionChipsConfig.fontFamily}",`),t.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${t.suggestionChipsConfig.fontWeight}",`),t.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${t.suggestionChipsConfig.paddingX}",`),t.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${t.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...pr(t," ")),e.push(...gr(t," ",r)),e.push(...mr(t," ")),e.push(...fr(t," ")),r!=null&&r.getHeaders&&e.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&e.push(` contextProviders: ${r.contextProviders},`),t.debug&&e.push(` debug: ${t.debug},`),e.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?e.push(` streamParser: ${r.streamParser},`):(e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(` streamParser: () => createFlexibleJsonStreamParser(${Cl}),`)),r!=null&&r.actionParsers?(e.push(" // Action parsers (custom merged with defaults)"),e.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),e.push(" // Built-in parser for markdown-wrapped JSON"),e.push(` ${ua}`),e.push(" ],")):(e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Parser for markdown-wrapped JSON"),e.push(` ${ua}`),e.push(" ],")),r!=null&&r.actionHandlers?(e.push(" // Action handlers (custom merged with defaults)"),e.push(` actionHandlers: [...(${r.actionHandlers}),`),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Built-in handler for nav_then_click action"),e.push(` ${ga}`),e.push(" ],")):(e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(` ${ga}`),e.push(" ],")),r!=null&&r.postprocessMessage?e.push(` postprocessMessage: ${r.postprocessMessage},`):e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(e.push(" // Request middleware (custom merged with DOM context)"),e.push(" requestMiddleware: ({ payload, config }) => {"),e.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),e.push(" const merged = customResult || payload;"),e.push(" return {"),e.push(" ...merged,"),e.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),e.push(" };"),e.push(" }")):(e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }")),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('persona:message', handleMessage);"),e.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('persona:message', handleMessage);"),e.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
|
|
135
|
+
`)}function ha(t){var o;let n=ur(t),r=n!=="plain",e={};if(t.apiUrl&&(e.apiUrl=t.apiUrl),t.clientToken&&(e.clientToken=t.clientToken),t.flowId&&(e.flowId=t.flowId),r&&(e.parserType=n),t.theme&&(e.theme=t.theme),t.launcher&&(e.launcher=t.launcher),t.copy&&(e.copy=t.copy),t.sendButton&&(e.sendButton=t.sendButton),t.voiceRecognition&&(e.voiceRecognition=t.voiceRecognition),t.statusIndicator&&(e.statusIndicator=t.statusIndicator),t.features&&(e.features=t.features),((o=t.suggestionChips)==null?void 0:o.length)>0&&(e.suggestionChips=t.suggestionChips),t.suggestionChipsConfig&&(e.suggestionChipsConfig=t.suggestionChipsConfig),t.debug&&(e.debug=t.debug),t.toolCall){let s={};Object.entries(t.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(e.toolCall=s)}if(t.messageActions){let s={};Object.entries(t.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(e.messageActions=s)}if(t.markdown){let s={};t.markdown.options&&(s.options=t.markdown.options),t.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=t.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(t.layout){let s={};if(t.layout.header){let i={};Object.entries(t.layout.header).forEach(([a,u])=>{a!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(i[a]=u)}),Object.keys(i).length>0&&(s.header=i)}if(t.layout.messages){let i={};Object.entries(t.layout.messages).forEach(([a,u])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof u=="object"&&u!==null)i.avatar=u;else if(a==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([v,d])=>{v!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[v]=d)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(i[a]=u)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function Ll(t){let n=ha(t),r=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ln}/dist/install.global.js" data-config='${r}'></script>`}function Il(t,n){let r=n==null?void 0:n.hooks,e=ur(t),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ln}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ln}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return t.apiUrl&&s.push(` apiUrl: "${t.apiUrl}",`),t.clientToken&&s.push(` clientToken: "${t.clientToken}",`),t.flowId&&s.push(` flowId: "${t.flowId}",`),o&&s.push(` parserType: "${e}",`),t.theme&&(s.push(" theme: {"),Object.entries(t.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.launcher&&(s.push(" launcher: {"),Object.entries(t.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.copy&&(s.push(" copy: {"),Object.entries(t.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.sendButton&&(s.push(" sendButton: {"),Object.entries(t.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(t.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(t.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.features&&(s.push(" features: {"),Object.entries(t.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),t.suggestionChips&&t.suggestionChips.length>0&&(s.push(" suggestionChips: ["),t.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),t.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),t.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${t.suggestionChipsConfig.fontFamily}",`),t.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${t.suggestionChipsConfig.fontWeight}",`),t.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${t.suggestionChipsConfig.paddingX}",`),t.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${t.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...pr(t," ")),s.push(...gr(t," ",r)),s.push(...mr(t," ")),s.push(...fr(t," ")),s.push(...qr(r," ")),t.debug&&s.push(` debug: ${t.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
|
|
136
|
+
`)}function kl(t,n){let r=n==null?void 0:n.hooks,e=ha(t),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(e,null,2).split(`
|
|
137
137
|
`).map((i,a)=>a===0?i:" "+i).join(`
|
|
138
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
139
|
-
`)}var
|
|
138
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ln}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r!=null&&r.getHeaders&&(s.push(` widgetConfig.getHeaders = ${r.getHeaders};`),s.push("")),r!=null&&r.contextProviders&&(s.push(` widgetConfig.contextProviders = ${r.contextProviders};`),s.push("")),r!=null&&r.streamParser?s.push(` widgetConfig.streamParser = ${r.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${Sl});`),s.push(" };")),s.push(""),r!=null&&r.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${r.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${pa}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${pa}`),s.push(" ];")),s.push(""),r!=null&&r.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${r.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${ma}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${ma}`),s.push(" ];")),s.push(""),r!=null&&r.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${r.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),r!=null&&r.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(r!=null&&r.onFeedback||r!=null&&r.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r!=null&&r.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r!=null&&r.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
|
|
139
|
+
`)}var Wl=jr;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,renderLoadingIndicatorWithFallback,validateImageFile});
|
|
140
140
|
//# sourceMappingURL=index.cjs.map
|