@runtypelabs/persona 1.38.3 → 1.39.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 +8 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -11
- package/dist/index.d.ts +11 -11
- package/dist/index.global.js +2 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +8 -8
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +30 -30
- package/src/types.ts +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var Mi=Object.create;var _n=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var Wi=Object.getOwnPropertyNames;var ki=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var Pi=(e,n)=>{for(var o in n)_n(e,o,{get:n[o],enumerable:!0})},Lr=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Wi(n))!Li.call(e,r)&&r!==o&&_n(e,r,{get:()=>n[r],enumerable:!(t=Ei(n,r))||t.enumerable});return e};var Hi=(e,n,o)=>(o=e!=null?Mi(ki(e)):{},Lr(n||!e||!e.__esModule?_n(o,"default",{value:e,enumerable:!0}):o,e)),
|
|
1
|
+
"use strict";var Mi=Object.create;var _n=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var Wi=Object.getOwnPropertyNames;var ki=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var Pi=(e,n)=>{for(var o in n)_n(e,o,{get:n[o],enumerable:!0})},Lr=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Wi(n))!Li.call(e,r)&&r!==o&&_n(e,r,{get:()=>n[r],enumerable:!(t=Ei(n,r))||t.enumerable});return e};var Hi=(e,n,o)=>(o=e!=null?Mi(ki(e)):{},Lr(n||!e||!e.__esModule?_n(o,"default",{value:e,enumerable:!0}):o,e)),Ii=e=>Lr(_n({},"__esModule",{value:!0}),e);var ba={};Pi(ba,{AgentWidgetClient:()=>Qt,AgentWidgetSession:()=>an,AttachmentManager:()=>Zt,DEFAULT_DARK_THEME:()=>ks,DEFAULT_LIGHT_THEME:()=>Ws,DEFAULT_WIDGET_CONFIG:()=>Ie,VERSION:()=>nn,attachHeaderToContainer:()=>en,buildComposer:()=>dn,buildDefaultHeader:()=>vs,buildExpandedHeader:()=>Cs,buildHeader:()=>Ut,buildHeaderWithLayout:()=>ln,buildMinimalHeader:()=>bs,componentRegistry:()=>gn,createActionManager:()=>Rn,createAgentExperience:()=>ds,createBubbleWithLayout:()=>ii,createCSATFeedback:()=>as,createComponentMiddleware:()=>mi,createComponentStreamParser:()=>ss,createDirectivePostprocessor:()=>Rr,createFlexibleJsonStreamParser:()=>Nr,createImagePart:()=>Yr,createJsonStreamParser:()=>Kn,createLocalStorageAdapter:()=>ns,createMarkdownProcessor:()=>Wn,createMarkdownProcessorFromConfig:()=>kn,createMessageActions:()=>Ss,createNPSFeedback:()=>ls,createPlainTextParser:()=>Jn,createRegexJsonParser:()=>Yn,createStandardBubble:()=>cn,createTextPart:()=>Xn,createTypingIndicator:()=>Hn,createXmlParser:()=>Vn,default:()=>va,defaultActionHandlers:()=>tn,defaultJsonActionParser:()=>Bn,directivePostprocessor:()=>Fr,escapeHtml:()=>qn,extractComponentDirectiveFromMessage:()=>is,fileToImagePart:()=>Kr,generateAssistantMessageId:()=>rn,generateCodeSnippet:()=>Si,generateMessageId:()=>_r,generateUserMessageId:()=>Ln,getDisplayText:()=>Ur,getHeaderLayout:()=>xs,getImageParts:()=>Jr,hasComponentDirective:()=>rs,hasImages:()=>zr,headerLayouts:()=>es,initAgentWidget:()=>Bs,isComponentDirectiveType:()=>gi,markdownPostprocessor:()=>fs,mergeWithDefaults:()=>ts,normalizeContent:()=>qr,pluginRegistry:()=>In,renderComponentDirective:()=>os,validateImageFile:()=>Vr});module.exports=Ii(ba);var Hr=require("marked"),Bi=e=>{if(e)return e},Wn=e=>{var r,s;let n=e==null?void 0:e.markedOptions,o=new Hr.Marked({gfm:(r=n==null?void 0:n.gfm)!=null?r:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),t=Bi(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},kn=e=>e?Wn({markedOptions:e.options,renderer:e.renderer}):Wn(),Ri=Wn(),fs=e=>Ri(e),qn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Ir=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Pr=e=>`%%FORM_PLACEHOLDER_${e}%%`,Br=(e,n)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Pr(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let s=Pr(n.length);return n.push({token:s,type:r}),s}),o},Rr=e=>{let n=kn(e);return o=>{let t=[],r=Br(o,t),s=n(r);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${Ir(a)}"></div>`;s=s.replace(d,f)}),s}},Fr=e=>{let n=[],o=Br(e,n),t=fs(o);return n.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Ir(s)}"></div>`;t=t.replace(i,d)}),t};var qt=require("partial-json"),Un=e=>e.replace(/\\n/g,`
|
|
2
2
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ws=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Fi=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),o=(a=e.startedAt)!=null?a:n,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},$r=e=>e.status==="complete"?Fi(e):e.status==="pending"?"Waiting":"",$i=e=>{var r,s,i;let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((i=(s=e.startedAt)!=null?s:e.completedAt)!=null?i:Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Or=e=>e.status==="complete"?$i(e):"Using tool...",Oi=()=>{let e=null,n=0,o=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=t.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},zn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Jn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Yn=()=>{var n;let e=Oi();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(o)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Kn=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,qt.parse)(o,qt.STR|qt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Un(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Un(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Nr=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Un(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Un(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<=o)return n!==null?{text:n,raw:s}:null;try{let a=(0,qt.parse)(s,qt.STR|qt.OBJ),d=r(a);d!==null&&(n=d)}catch{}return o=s.length,{text:n||"",raw:s}},close:()=>{}}},Vn=()=>{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 Ni="https://api.runtype.com/v1/dispatch",jr="https://api.runtype.com",Dr=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 ji(e){switch(e){case"json":return Kn;case"regex-json":return Yn;case"xml":return Vn;case"plain":default:return Jn}}var Qt=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=n.apiUrl)!=null?o:Ni,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:ji(n.parserType),this.contextProviders=(r=n.contextProviders)!=null?r:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(n){var t;let o=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||jr;return n==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,o;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,(o=(n=this.config).onSessionInit)==null||o.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,o={token:this.config.clientToken,...this.config.flowId&&{flow_id:this.config.flowId},...n&&{session_id:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});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 r=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.session_id),{sessionId:r.session_id,expiresAt:new Date(r.expires_at),flow:r.flow,config:{welcomeMessage:r.config.welcome_message,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||jr}/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.message_id)throw new Error(`message_id 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 r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.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,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:n,type:o})}async submitCSATFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:n,comment:o})}async submitNPSFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:n,comment:o})}async dispatch(n,o){return this.isClientTokenMode()?this.dispatchClientToken(n,o):this.dispatchProxy(n,o)}async dispatchClientToken(n,o){var r,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let w=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:w}),w}let u=await this.buildPayload(n.messages),f=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([w])=>w!=="session_id")):void 0,p={session_id:d.sessionId,messages:n.messages.filter(Dr).map(w=>{var h,R,M;return{id:w.id,role:w.role,content:(M=(R=(h=w.contentParts)!=null?h:w.llmContent)!=null?R:w.rawContent)!=null?M:w.content}}),...n.assistantMessageId&&{assistant_message_id:n.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...u.context&&{context:u.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:t.signal});if(!m.ok){let w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let R=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:R}),R}if(m.status===429){let R=new Error(w.hint||"Message limit reached for this session.");throw o({type:"error",error:R}),R}let h=new Error(w.error||"Failed to send message");throw o({type:"error",error:h}),h}if(!m.body){let w=new Error("No response body received");throw o({type:"error",error:w}),w}o({type:"status",status:"connected"});try{await this.streamResponse(m.body,o,n.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&o({type:"error",error:u}),u}}async dispatchProxy(n,o){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);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(r),signal:t.signal},r)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:a}),a}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(n){let t={messages:n.slice().filter(Dr).sort((r,s)=>{let i=new Date(r.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(r=>{var s,i,a;return{role:r.role,content:(a=(i=(s=r.contentParts)!=null?s:r.llmContent)!=null?i:r.rawContent)!=null?a:r.content,createdAt:r.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(n,o,t,r,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,r(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,o,t){var Z,de,qe,Ct,ee,j,at,xt,vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt,U,Re,Xe,Wt,gt,Pt,Fe,st,kt,mt,ht,P,te,we,Ge,St,ze,ft,Lt,Ht,fn,Kt,Fn,wn,sn,We,yn,vn,Dt,$n;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=B=>{let le=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,he=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Ee=B.tools?B.tools.map(Ze=>({...Ze,chunks:Ze.chunks?[...Ze.chunks]:void 0})):void 0;return{...B,reasoning:le,toolCall:he,tools:Ee}},p=B=>{o({type:"message",message:f(B)})},m=null,w={current:null},h=new Map,R=new Map,M={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},A=B=>{if(B==null)return null;try{return String(B)}catch{return null}},I=B=>{var le,he,Ee,Ze,ot;return A((ot=(Ze=(Ee=(he=(le=B.stepId)!=null?le:B.step_id)!=null?he:B.step)!=null?Ee:B.parentId)!=null?Ze:B.flowStepId)!=null?ot:B.flow_step_id)},v=B=>{var le,he,Ee,Ze,ot,$e,O;return A((O=($e=(ot=(Ze=(Ee=(he=(le=B.callId)!=null?le:B.call_id)!=null?he:B.requestId)!=null?Ee:B.request_id)!=null?Ze:B.toolCallId)!=null?ot:B.tool_call_id)!=null?$e:B.stepId)!=null?O:B.step_id)},N=()=>m||(m={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},p(m),m),C=(B,le)=>{M.lastId=le,B&&M.byStep.set(B,le)},k=(B,le)=>{var ot;let he=(ot=B.reasoningId)!=null?ot:B.id,Ee=I(B);if(he){let $e=String(he);return C(Ee,$e),$e}if(Ee){let $e=M.byStep.get(Ee);if($e)return M.lastId=$e,$e}if(M.lastId&&!le)return M.lastId;if(!le)return null;let Ze=`reason-${u()}`;return C(Ee,Ze),Ze},z=B=>{let le=h.get(B);if(le)return le;let he={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:B,status:"streaming",chunks:[]}};return h.set(B,he),p(he),he},_=(B,le)=>{y.lastId=le,B&&y.byCall.set(B,le)},ne=(B,le)=>{var ot;let he=(ot=B.toolId)!=null?ot:B.id,Ee=v(B);if(he){let $e=String(he);return _(Ee,$e),$e}if(Ee){let $e=y.byCall.get(Ee);if($e)return y.lastId=$e,$e}if(y.lastId&&!le)return y.lastId;if(!le)return null;let Ze=`tool-${u()}`;return _(Ee,Ze),Ze},re=B=>{let le=R.get(B);if(le)return le;let he={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:B,status:"pending"}};return R.set(B,he),p(he),he},V=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let le=Number(B);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let he=Date.parse(B);if(!Number.isNaN(he))return he}return Date.now()},J=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},L=new Map,q=new Map;for(;;){let{done:B,value:le}=await r.read();if(B)break;i+=s.decode(le,{stream:!0});let he=i.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},zn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Jn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Yn=()=>{var n;let e=Oi();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(o)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Kn=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,qt.parse)(o,qt.STR|qt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Un(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Un(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Nr=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Un(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Un(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<=o)return n!==null?{text:n,raw:s}:null;try{let a=(0,qt.parse)(s,qt.STR|qt.OBJ),d=r(a);d!==null&&(n=d)}catch{}return o=s.length,{text:n||"",raw:s}},close:()=>{}}},Vn=()=>{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 Ni="https://api.runtype.com/v1/dispatch",jr="https://api.runtype.com",Dr=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 ji(e){switch(e){case"json":return Kn;case"regex-json":return Yn;case"xml":return Vn;case"plain":default:return Jn}}var Qt=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=n.apiUrl)!=null?o:Ni,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:ji(n.parserType),this.contextProviders=(r=n.contextProviders)!=null?r:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(n){var t;let o=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||jr;return n==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,o;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,(o=(n=this.config).onSessionInit)==null||o.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,o={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(o)});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 r=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||jr}/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 r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.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,o){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:o})}async submitCSATFeedback(n,o){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:o})}async submitNPSFeedback(n,o){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:o})}async dispatch(n,o){return this.isClientTokenMode()?this.dispatchClientToken(n,o):this.dispatchProxy(n,o)}async dispatchClientToken(n,o){var r,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let w=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:w}),w}let u=await this.buildPayload(n.messages),f=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(Dr).map(w=>{var h,R,M;return{id:w.id,role:w.role,content:(M=(R=(h=w.contentParts)!=null?h:w.llmContent)!=null?R:w.rawContent)!=null?M:w.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...u.context&&{context:u.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:t.signal});if(!m.ok){let w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let R=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:R}),R}if(m.status===429){let R=new Error(w.hint||"Message limit reached for this session.");throw o({type:"error",error:R}),R}let h=new Error(w.error||"Failed to send message");throw o({type:"error",error:h}),h}if(!m.body){let w=new Error("No response body received");throw o({type:"error",error:w}),w}o({type:"status",status:"connected"});try{await this.streamResponse(m.body,o,n.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&o({type:"error",error:u}),u}}async dispatchProxy(n,o){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);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(r),signal:t.signal},r)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:a}),a}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(n){let t={messages:n.slice().filter(Dr).sort((r,s)=>{let i=new Date(r.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(r=>{var s,i,a;return{role:r.role,content:(a=(i=(s=r.contentParts)!=null?s:r.llmContent)!=null?i:r.rawContent)!=null?a:r.content,createdAt:r.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(n,o,t,r,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,r(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,o,t){var Z,de,qe,Ct,ee,j,at,xt,vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt,U,Re,Xe,Wt,gt,Pt,Fe,st,kt,mt,ht,P,te,we,Ge,St,ze,ft,Lt,Ht,fn,Kt,Fn,wn,sn,We,yn,vn,Dt,$n;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=I=>{let le=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,he=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,Ee=I.tools?I.tools.map(Ze=>({...Ze,chunks:Ze.chunks?[...Ze.chunks]:void 0})):void 0;return{...I,reasoning:le,toolCall:he,tools:Ee}},p=I=>{o({type:"message",message:f(I)})},m=null,w={current:null},h=new Map,R=new Map,M={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},A=I=>{if(I==null)return null;try{return String(I)}catch{return null}},B=I=>{var le,he,Ee,Ze,ot;return A((ot=(Ze=(Ee=(he=(le=I.stepId)!=null?le:I.step_id)!=null?he:I.step)!=null?Ee:I.parentId)!=null?Ze:I.flowStepId)!=null?ot:I.flow_step_id)},v=I=>{var le,he,Ee,Ze,ot,$e,O;return A((O=($e=(ot=(Ze=(Ee=(he=(le=I.callId)!=null?le:I.call_id)!=null?he:I.requestId)!=null?Ee:I.request_id)!=null?Ze:I.toolCallId)!=null?ot:I.tool_call_id)!=null?$e:I.stepId)!=null?O:I.step_id)},N=()=>m||(m={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},p(m),m),C=(I,le)=>{M.lastId=le,I&&M.byStep.set(I,le)},k=(I,le)=>{var ot;let he=(ot=I.reasoningId)!=null?ot:I.id,Ee=B(I);if(he){let $e=String(he);return C(Ee,$e),$e}if(Ee){let $e=M.byStep.get(Ee);if($e)return M.lastId=$e,$e}if(M.lastId&&!le)return M.lastId;if(!le)return null;let Ze=`reason-${u()}`;return C(Ee,Ze),Ze},z=I=>{let le=h.get(I);if(le)return le;let he={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:I,status:"streaming",chunks:[]}};return h.set(I,he),p(he),he},_=(I,le)=>{y.lastId=le,I&&y.byCall.set(I,le)},ne=(I,le)=>{var ot;let he=(ot=I.toolId)!=null?ot:I.id,Ee=v(I);if(he){let $e=String(he);return _(Ee,$e),$e}if(Ee){let $e=y.byCall.get(Ee);if($e)return y.lastId=$e,$e}if(y.lastId&&!le)return y.lastId;if(!le)return null;let Ze=`tool-${u()}`;return _(Ee,Ze),Ze},re=I=>{let le=R.get(I);if(le)return le;let he={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:I,status:"pending"}};return R.set(I,he),p(he),he},V=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let le=Number(I);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let he=Date.parse(I);if(!Number.isNaN(he))return he}return Date.now()},J=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},L=new Map,q=new Map;for(;;){let{done:I,value:le}=await r.read();if(I)break;i+=s.decode(le,{stream:!0});let he=i.split(`
|
|
5
5
|
|
|
6
6
|
`);i=(Z=he.pop())!=null?Z:"";for(let Ee of he){let Ze=Ee.split(`
|
|
7
|
-
`),ot="message",$e="";for(let se of Ze)se.startsWith("event:")?ot=se.replace("event:","").trim():se.startsWith("data:")&&($e+=se.replace("data:","").trim());if(!$e)continue;let O;try{O=JSON.parse($e)}catch(se){o({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let wt=ot!=="message"?ot:(de=O.type)!=null?de:"message";if(this.parseSSEEvent){w.current=m;let se=await this.handleCustomSSEEvent(O,o,w,p,u);if(w.current&&!m&&(m=w.current),se)continue}if(wt==="reason_start"){let se=(qe=k(O,!0))!=null?qe:`reason-${u()}`,S=z(se);S.reasoning=(Ct=S.reasoning)!=null?Ct:{id:se,status:"streaming",chunks:[]},S.reasoning.startedAt=(j=S.reasoning.startedAt)!=null?j:V((ee=O.startedAt)!=null?ee:O.timestamp),S.reasoning.completedAt=void 0,S.reasoning.durationMs=void 0,S.streaming=!0,S.reasoning.status="streaming",p(S)}else if(wt==="reason_chunk"){let se=(xt=(at=k(O,!1))!=null?at:k(O,!0))!=null?xt:`reason-${u()}`,S=z(se);S.reasoning=(vt=S.reasoning)!=null?vt:{id:se,status:"streaming",chunks:[]},S.reasoning.startedAt=(Ft=S.reasoning.startedAt)!=null?Ft:V((Rt=O.startedAt)!=null?Rt:O.timestamp);let E=(lt=(fe=(D=O.reasoningText)!=null?D:O.text)!=null?fe:O.delta)!=null?lt:"";if(E&&O.hidden!==!0&&S.reasoning.chunks.push(String(E)),S.reasoning.status=O.done?"complete":"streaming",O.done){S.reasoning.completedAt=V((dt=O.completedAt)!=null?dt:O.timestamp);let Y=(Ve=S.reasoning.startedAt)!=null?Ve:Date.now();S.reasoning.durationMs=Math.max(0,((ct=S.reasoning.completedAt)!=null?ct:Date.now())-Y)}S.streaming=S.reasoning.status!=="complete",p(S)}else if(wt==="reason_complete"){let se=($t=(jt=k(O,!1))!=null?jt:k(O,!0))!=null?$t:`reason-${u()}`,S=h.get(se);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=V((Ot=O.completedAt)!=null?Ot:O.timestamp);let Y=(F=S.reasoning.startedAt)!=null?F:Date.now();S.reasoning.durationMs=Math.max(0,((Ue=S.reasoning.completedAt)!=null?Ue:Date.now())-Y),S.streaming=!1,p(S)}let E=I(O);E&&M.byStep.delete(E)}else if(wt==="tool_start"){let se=(ge=ne(O,!0))!=null?ge:`tool-${u()}`,S=re(se),E=(tt=S.toolCall)!=null?tt:{id:se,status:"pending"};E.name=(me=O.toolName)!=null?me:E.name,E.status="running",O.args!==void 0&&(E.args=O.args),E.startedAt=(U=E.startedAt)!=null?U:V((nt=O.startedAt)!=null?nt:O.timestamp),E.completedAt=void 0,E.durationMs=void 0,S.toolCall=E,S.streaming=!0,p(S)}else if(wt==="tool_chunk"){let se=(Xe=(Re=ne(O,!1))!=null?Re:ne(O,!0))!=null?Xe:`tool-${u()}`,S=re(se),E=(Wt=S.toolCall)!=null?Wt:{id:se,status:"running"};E.startedAt=(Pt=E.startedAt)!=null?Pt:V((gt=O.startedAt)!=null?gt:O.timestamp);let Y=(kt=(st=(Fe=O.text)!=null?Fe:O.delta)!=null?st:O.message)!=null?kt:"";Y&&(E.chunks=(mt=E.chunks)!=null?mt:[],E.chunks.push(String(Y))),E.status="running",S.toolCall=E,S.streaming=!0,p(S)}else if(wt==="tool_complete"){let se=(P=(ht=ne(O,!1))!=null?ht:ne(O,!0))!=null?P:`tool-${u()}`,S=re(se),E=(te=S.toolCall)!=null?te:{id:se,status:"running"};if(E.status="complete",O.result!==void 0&&(E.result=O.result),typeof O.duration=="number"&&(E.duration=O.duration),E.completedAt=V((we=O.completedAt)!=null?we:O.timestamp),typeof O.duration=="number")E.durationMs=O.duration;else{let Pe=(Ge=E.startedAt)!=null?Ge:Date.now();E.durationMs=Math.max(0,((St=E.completedAt)!=null?St:Date.now())-Pe)}S.toolCall=E,S.streaming=!1,p(S);let Y=v(O);Y&&y.byCall.delete(Y)}else if(wt==="step_chunk"){let se=O.stepType,S=O.executionType;if(se==="tool"||S==="context")continue;let E=N(),Y=(Ht=(Lt=(ft=(ze=O.text)!=null?ze:O.delta)!=null?ft:O.content)!=null?Lt:O.chunk)!=null?Ht:"";if(Y){let He=((fn=q.get(E.id))!=null?fn:"")+Y;E.rawContent=He,L.has(E.id)||L.set(E.id,this.createStreamParser());let ke=L.get(E.id),ye=He.trim().startsWith("{")||He.trim().startsWith("[");if(ye&&q.set(E.id,He),ke.__isPlainTextParser===!0){E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E);continue}let Le=ke.processChunk(He);if(Le instanceof Promise)Le.then(ve=>{var Te;let be=typeof ve=="string"?ve:(Te=ve==null?void 0:ve.text)!=null?Te:null;if(be!==null&&be.trim()!==""){let Ae=m;Ae&&Ae.id===E.id&&(Ae.content=be,p(Ae))}else if(!ye&&!He.trim().startsWith("<")){let Ae=m;Ae&&Ae.id===E.id&&(Ae.content+=Y,q.delete(Ae.id),L.delete(Ae.id),Ae.rawContent=void 0,p(Ae))}}).catch(()=>{E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E)});else{let ve=typeof Le=="string"?Le:(Kt=Le==null?void 0:Le.text)!=null?Kt:null;ve!==null&&ve.trim()!==""?(E.content=ve,p(E)):!ye&&!He.trim().startsWith("<")&&(E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E))}}if(O.isComplete){let Pe=(wn=(Fn=O.result)==null?void 0:Fn.response)!=null?wn:E.content;if(Pe){let He=q.get(E.id),ke=He!=null?He:J(Pe);E.rawContent=ke;let ye=L.get(E.id),Ie=null,Le=!1;if(ye&&(Ie=ye.getExtractedText(),Ie===null&&(Ie=zn(ke)),Ie===null)){let ve=ye.processChunk(ke);ve instanceof Promise?(Le=!0,ve.then(be=>{var Ae;let Te=typeof be=="string"?be:(Ae=be==null?void 0:be.text)!=null?Ae:null;if(Te!==null){let Qe=m;Qe&&Qe.id===E.id&&(Qe.content=Te,Qe.streaming=!1,L.delete(Qe.id),q.delete(Qe.id),p(Qe))}})):Ie=typeof ve=="string"?ve:(sn=ve==null?void 0:ve.text)!=null?sn:null}if(!Le){Ie!==null&&Ie.trim()!==""?E.content=Ie:q.has(E.id)||(E.content=J(Pe));let ve=L.get(E.id);if(ve){let be=(We=ve.close)==null?void 0:We.call(ve);be instanceof Promise&&be.catch(()=>{}),L.delete(E.id)}q.delete(E.id),E.streaming=!1,p(E)}}}}else if(wt==="step_complete"){let se=O.stepType,S=O.executionType;if(se==="tool"||S==="context")continue;let E=(yn=O.result)==null?void 0:yn.response,Y=N();if(E!=null){let Pe=L.get(Y.id),He=!1,ke=!1;if(Pe){let ye=Pe.getExtractedText(),Ie=q.get(Y.id),Le=Ie!=null?Ie:J(E);if(Y.rawContent=Le,ye!==null&&ye.trim()!=="")Y.content=ye,He=!0;else{let ve=zn(Le);if(ve!==null)Y.content=ve,He=!0;else{let be=Pe.processChunk(Le);if(be instanceof Promise)ke=!0,be.then(Te=>{var Qe;let Ae=typeof Te=="string"?Te:(Qe=Te==null?void 0:Te.text)!=null?Qe:null;if(Ae!==null&&Ae.trim()!==""){let At=m;At&&At.id===Y.id&&(At.content=Ae,At.streaming=!1,L.delete(At.id),q.delete(At.id),p(At))}else{let At=Pe.getExtractedText(),Bt=m;Bt&&Bt.id===Y.id&&(At!==null&&At.trim()!==""?Bt.content=At:q.has(Bt.id)||(Bt.content=J(E)),Bt.streaming=!1,L.delete(Bt.id),q.delete(Bt.id),p(Bt))}});else{let Te=typeof be=="string"?be:(vn=be==null?void 0:be.text)!=null?vn:null;if(Te!==null&&Te.trim()!=="")Y.content=Te,He=!0;else{let Ae=Pe.getExtractedText();Ae!==null&&Ae.trim()!==""&&(Y.content=Ae,He=!0)}}}}}if(!ke){if(!Y.rawContent){let ye=q.get(Y.id);Y.rawContent=ye!=null?ye:J(E)}if(!He&&!q.has(Y.id)&&(Y.content=J(E)),Pe){let ye=(Dt=Pe.close)==null?void 0:Dt.call(Pe);ye instanceof Promise&&ye.catch(()=>{})}L.delete(Y.id),q.delete(Y.id),Y.streaming=!1,p(Y)}}else L.delete(Y.id),q.delete(Y.id),Y.streaming=!1,p(Y)}else if(wt==="flow_complete"){let se=($n=O.result)==null?void 0:$n.response;if(se!=null){let S=N(),E=q.get(S.id),Y=E!=null?E:J(se);S.rawContent=Y;let Pe=J(se),He=L.get(S.id);if(He){let Ie=zn(Y);if(Ie!==null)Pe=Ie;else{let Le=He.processChunk(Y);Le instanceof Promise&&Le.then(be=>{var Ae;let Te=typeof be=="string"?be:(Ae=be==null?void 0:be.text)!=null?Ae:null;if(Te!==null){let Qe=m;Qe&&Qe.id===S.id&&(Qe.content=Te,Qe.streaming=!1,p(Qe))}});let ve=He.getExtractedText();ve!==null&&(Pe=ve)}}L.delete(S.id),q.delete(S.id);let ke=Pe!==S.content,ye=S.streaming!==!1;ke&&(S.content=Pe),S.streaming=!1,(ke||ye)&&p(S)}else if(m!==null){let S=m;L.delete(S.id),q.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}o({type:"status",status:"idle"})}else wt==="error"&&O.error&&o({type:"error",error:O.error instanceof Error?O.error:new Error(String(O.error))})}}}};function _r(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ln(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function rn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var an=class{constructor(n={},o){this.config=n;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=n=>{var o,t;n.type==="message"?this.upsertMessage(n.message):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)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var n,o;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(o=(n=this.callbacks).onError)==null||o.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 o={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}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,o){return this.client.submitMessageFeedback(n,o)}async submitCSATFeedback(n,o){return this.client.submitCSATFeedback(n,o)}async submitNPSFeedback(n,o){return this.client.submitNPSFeedback(n,o)}updateConfig(n){this.config={...this.config,...n},this.client=new Qt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:o,content:t,llmContent:r,contentParts:s,id:i,createdAt:a,sequence:d,streaming:u=!1}=n,p={id:i!=null?i:o==="user"?Ln():o==="assistant"?rn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s}};return this.upsertMessage(p),p}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}async sendMessage(n,o){var u,f,p,m,w;let t=n.trim();if(!t&&(!(o!=null&&o.contentParts)||o.contentParts.length===0))return;(u=this.abortController)==null||u.abort();let r=Ln(),s=rn(),i={id:r,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1,...(o==null?void 0:o.contentParts)&&o.contentParts.length>0&&{contentParts:o.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(h){let R={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(R),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h instanceof Error?(p=(f=this.callbacks).onError)==null||p.call(f,h):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(h)))}}async continueConversation(){var r,s,i,a,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let n=rn();this.setStreaming(!0);let o=new AbortController;this.abortController=o;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n},this.handleEvent)}catch(u){let f={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(f),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,u):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(u)))}}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.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r: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 o=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let o=this.ensureSequence(n),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),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((o,t)=>{var d,u;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,a=(u=t.sequence)!=null?u:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var g=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var Di=Hi(require("lucide"),1),ie=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Di[r];return s?_i(s,n,o,t):(console.warn(`Lucide icon "${e}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${e}":`,r),null}};function _i(e,n,o,t){if(!e||!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(n)),r.setAttribute("height",String(n)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.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(([u,f])=>{u!=="stroke"&&d.setAttribute(u,String(f))}),r.appendChild(d)}}}),r}function qr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ur(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function zr(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Jr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Xn(e){return{type:"text",text:e}}function Yr(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 Kr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;n({type:"image",image:r,mimeType:e.type,alt:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Vr(e,n=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Xr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qi=["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"],Yt=[...Xr,...qi];function Ui(e){return Xr.includes(e)||e.startsWith("image/")}function Gn(e){return Ui(e.type)}async function Gr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Gn(e)?n({type:"image",image:r,mimeType:e.type,alt:e.name}):n({type:"file",data:r,mimeType:e.type,filename:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Qr(e,n=Yt,o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function zi(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Zr(e,n){let o=zi(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]||o||"FILE"}var Qn={allowedTypes:Yt,maxFileSize:10*1024*1024,maxFiles:4};function Ji(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Yi(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 Zt=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var o,t,r;this.config={allowedTypes:(o=n.allowedTypes)!=null?o:Qn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Qn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Qn.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:Qn.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,r,s,i,a,d,u;if(!n||n.length===0)return;let o=Array.from(n);for(let f of o){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,f,"count");continue}let p=Qr(f,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,m);continue}try{let m=await Gr(f),w=Gn(f)?URL.createObjectURL(f):null,h={id:Ji(),file:f,previewUrl:w,contentPart:m};this.attachments.push(h),this.renderPreview(h)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(u=(d=this.config).onAttachmentsChange)==null||u.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let o=this.attachments.findIndex(d=>d.id===n);if(o===-1)return;let t=this.attachments[o];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(o,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,o;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(o=(n=this.config).onAttachmentsChange)==null||o.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let o=Gn(n.file),t=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",o&&n.previewUrl){let i=g("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Yi(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=g("span");u.textContent=Zr(n.file.type,n.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--cw-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",i.appendChild(u),t.appendChild(i)}let r=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="rgba(0, 0, 0, 0.6)",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ie("x",10,"#ffffff",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="#ffffff",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(r),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,o){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:o})}};var ys=()=>{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"},Ki=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",o=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:o;return n==="light"?o:n==="dark"||ys()==="dark"?t:o},ei=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(ys())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(ys());o.addEventListener?(o.addEventListener("change",t),n.push(()=>o.removeEventListener("change",t))):o.addListener&&(o.addListener(t),n.push(()=>o.removeListener(t)))}return()=>{n.forEach(o=>o())}},Zn=(e,n)=>{let o=Ki(n);Object.entries(o).forEach(([t,r])=>{if(r==null||r==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(r))})};var ti=require("idiomorph"),ni=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;ti.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&t&&r.classList.contains("tvw-animate-typing"))return!1}}})};var pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var It={"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 Pn=(e,n)=>{let o=g("button");o.type="button",o.innerHTML=`
|
|
7
|
+
`),ot="message",$e="";for(let se of Ze)se.startsWith("event:")?ot=se.replace("event:","").trim():se.startsWith("data:")&&($e+=se.replace("data:","").trim());if(!$e)continue;let O;try{O=JSON.parse($e)}catch(se){o({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let wt=ot!=="message"?ot:(de=O.type)!=null?de:"message";if(this.parseSSEEvent){w.current=m;let se=await this.handleCustomSSEEvent(O,o,w,p,u);if(w.current&&!m&&(m=w.current),se)continue}if(wt==="reason_start"){let se=(qe=k(O,!0))!=null?qe:`reason-${u()}`,S=z(se);S.reasoning=(Ct=S.reasoning)!=null?Ct:{id:se,status:"streaming",chunks:[]},S.reasoning.startedAt=(j=S.reasoning.startedAt)!=null?j:V((ee=O.startedAt)!=null?ee:O.timestamp),S.reasoning.completedAt=void 0,S.reasoning.durationMs=void 0,S.streaming=!0,S.reasoning.status="streaming",p(S)}else if(wt==="reason_chunk"){let se=(xt=(at=k(O,!1))!=null?at:k(O,!0))!=null?xt:`reason-${u()}`,S=z(se);S.reasoning=(vt=S.reasoning)!=null?vt:{id:se,status:"streaming",chunks:[]},S.reasoning.startedAt=(Ft=S.reasoning.startedAt)!=null?Ft:V((Rt=O.startedAt)!=null?Rt:O.timestamp);let E=(lt=(fe=(D=O.reasoningText)!=null?D:O.text)!=null?fe:O.delta)!=null?lt:"";if(E&&O.hidden!==!0&&S.reasoning.chunks.push(String(E)),S.reasoning.status=O.done?"complete":"streaming",O.done){S.reasoning.completedAt=V((dt=O.completedAt)!=null?dt:O.timestamp);let Y=(Ve=S.reasoning.startedAt)!=null?Ve:Date.now();S.reasoning.durationMs=Math.max(0,((ct=S.reasoning.completedAt)!=null?ct:Date.now())-Y)}S.streaming=S.reasoning.status!=="complete",p(S)}else if(wt==="reason_complete"){let se=($t=(jt=k(O,!1))!=null?jt:k(O,!0))!=null?$t:`reason-${u()}`,S=h.get(se);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=V((Ot=O.completedAt)!=null?Ot:O.timestamp);let Y=(F=S.reasoning.startedAt)!=null?F:Date.now();S.reasoning.durationMs=Math.max(0,((Ue=S.reasoning.completedAt)!=null?Ue:Date.now())-Y),S.streaming=!1,p(S)}let E=B(O);E&&M.byStep.delete(E)}else if(wt==="tool_start"){let se=(ge=ne(O,!0))!=null?ge:`tool-${u()}`,S=re(se),E=(tt=S.toolCall)!=null?tt:{id:se,status:"pending"};E.name=(me=O.toolName)!=null?me:E.name,E.status="running",O.args!==void 0&&(E.args=O.args),E.startedAt=(U=E.startedAt)!=null?U:V((nt=O.startedAt)!=null?nt:O.timestamp),E.completedAt=void 0,E.durationMs=void 0,S.toolCall=E,S.streaming=!0,p(S)}else if(wt==="tool_chunk"){let se=(Xe=(Re=ne(O,!1))!=null?Re:ne(O,!0))!=null?Xe:`tool-${u()}`,S=re(se),E=(Wt=S.toolCall)!=null?Wt:{id:se,status:"running"};E.startedAt=(Pt=E.startedAt)!=null?Pt:V((gt=O.startedAt)!=null?gt:O.timestamp);let Y=(kt=(st=(Fe=O.text)!=null?Fe:O.delta)!=null?st:O.message)!=null?kt:"";Y&&(E.chunks=(mt=E.chunks)!=null?mt:[],E.chunks.push(String(Y))),E.status="running",S.toolCall=E,S.streaming=!0,p(S)}else if(wt==="tool_complete"){let se=(P=(ht=ne(O,!1))!=null?ht:ne(O,!0))!=null?P:`tool-${u()}`,S=re(se),E=(te=S.toolCall)!=null?te:{id:se,status:"running"};if(E.status="complete",O.result!==void 0&&(E.result=O.result),typeof O.duration=="number"&&(E.duration=O.duration),E.completedAt=V((we=O.completedAt)!=null?we:O.timestamp),typeof O.duration=="number")E.durationMs=O.duration;else{let Pe=(Ge=E.startedAt)!=null?Ge:Date.now();E.durationMs=Math.max(0,((St=E.completedAt)!=null?St:Date.now())-Pe)}S.toolCall=E,S.streaming=!1,p(S);let Y=v(O);Y&&y.byCall.delete(Y)}else if(wt==="step_chunk"){let se=O.stepType,S=O.executionType;if(se==="tool"||S==="context")continue;let E=N(),Y=(Ht=(Lt=(ft=(ze=O.text)!=null?ze:O.delta)!=null?ft:O.content)!=null?Lt:O.chunk)!=null?Ht:"";if(Y){let He=((fn=q.get(E.id))!=null?fn:"")+Y;E.rawContent=He,L.has(E.id)||L.set(E.id,this.createStreamParser());let ke=L.get(E.id),ye=He.trim().startsWith("{")||He.trim().startsWith("[");if(ye&&q.set(E.id,He),ke.__isPlainTextParser===!0){E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E);continue}let Le=ke.processChunk(He);if(Le instanceof Promise)Le.then(ve=>{var Te;let be=typeof ve=="string"?ve:(Te=ve==null?void 0:ve.text)!=null?Te:null;if(be!==null&&be.trim()!==""){let Ae=m;Ae&&Ae.id===E.id&&(Ae.content=be,p(Ae))}else if(!ye&&!He.trim().startsWith("<")){let Ae=m;Ae&&Ae.id===E.id&&(Ae.content+=Y,q.delete(Ae.id),L.delete(Ae.id),Ae.rawContent=void 0,p(Ae))}}).catch(()=>{E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E)});else{let ve=typeof Le=="string"?Le:(Kt=Le==null?void 0:Le.text)!=null?Kt:null;ve!==null&&ve.trim()!==""?(E.content=ve,p(E)):!ye&&!He.trim().startsWith("<")&&(E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E))}}if(O.isComplete){let Pe=(wn=(Fn=O.result)==null?void 0:Fn.response)!=null?wn:E.content;if(Pe){let He=q.get(E.id),ke=He!=null?He:J(Pe);E.rawContent=ke;let ye=L.get(E.id),Be=null,Le=!1;if(ye&&(Be=ye.getExtractedText(),Be===null&&(Be=zn(ke)),Be===null)){let ve=ye.processChunk(ke);ve instanceof Promise?(Le=!0,ve.then(be=>{var Ae;let Te=typeof be=="string"?be:(Ae=be==null?void 0:be.text)!=null?Ae:null;if(Te!==null){let Qe=m;Qe&&Qe.id===E.id&&(Qe.content=Te,Qe.streaming=!1,L.delete(Qe.id),q.delete(Qe.id),p(Qe))}})):Be=typeof ve=="string"?ve:(sn=ve==null?void 0:ve.text)!=null?sn:null}if(!Le){Be!==null&&Be.trim()!==""?E.content=Be:q.has(E.id)||(E.content=J(Pe));let ve=L.get(E.id);if(ve){let be=(We=ve.close)==null?void 0:We.call(ve);be instanceof Promise&&be.catch(()=>{}),L.delete(E.id)}q.delete(E.id),E.streaming=!1,p(E)}}}}else if(wt==="step_complete"){let se=O.stepType,S=O.executionType;if(se==="tool"||S==="context")continue;let E=(yn=O.result)==null?void 0:yn.response,Y=N();if(E!=null){let Pe=L.get(Y.id),He=!1,ke=!1;if(Pe){let ye=Pe.getExtractedText(),Be=q.get(Y.id),Le=Be!=null?Be:J(E);if(Y.rawContent=Le,ye!==null&&ye.trim()!=="")Y.content=ye,He=!0;else{let ve=zn(Le);if(ve!==null)Y.content=ve,He=!0;else{let be=Pe.processChunk(Le);if(be instanceof Promise)ke=!0,be.then(Te=>{var Qe;let Ae=typeof Te=="string"?Te:(Qe=Te==null?void 0:Te.text)!=null?Qe:null;if(Ae!==null&&Ae.trim()!==""){let At=m;At&&At.id===Y.id&&(At.content=Ae,At.streaming=!1,L.delete(At.id),q.delete(At.id),p(At))}else{let At=Pe.getExtractedText(),It=m;It&&It.id===Y.id&&(At!==null&&At.trim()!==""?It.content=At:q.has(It.id)||(It.content=J(E)),It.streaming=!1,L.delete(It.id),q.delete(It.id),p(It))}});else{let Te=typeof be=="string"?be:(vn=be==null?void 0:be.text)!=null?vn:null;if(Te!==null&&Te.trim()!=="")Y.content=Te,He=!0;else{let Ae=Pe.getExtractedText();Ae!==null&&Ae.trim()!==""&&(Y.content=Ae,He=!0)}}}}}if(!ke){if(!Y.rawContent){let ye=q.get(Y.id);Y.rawContent=ye!=null?ye:J(E)}if(!He&&!q.has(Y.id)&&(Y.content=J(E)),Pe){let ye=(Dt=Pe.close)==null?void 0:Dt.call(Pe);ye instanceof Promise&&ye.catch(()=>{})}L.delete(Y.id),q.delete(Y.id),Y.streaming=!1,p(Y)}}else L.delete(Y.id),q.delete(Y.id),Y.streaming=!1,p(Y)}else if(wt==="flow_complete"){let se=($n=O.result)==null?void 0:$n.response;if(se!=null){let S=N(),E=q.get(S.id),Y=E!=null?E:J(se);S.rawContent=Y;let Pe=J(se),He=L.get(S.id);if(He){let Be=zn(Y);if(Be!==null)Pe=Be;else{let Le=He.processChunk(Y);Le instanceof Promise&&Le.then(be=>{var Ae;let Te=typeof be=="string"?be:(Ae=be==null?void 0:be.text)!=null?Ae:null;if(Te!==null){let Qe=m;Qe&&Qe.id===S.id&&(Qe.content=Te,Qe.streaming=!1,p(Qe))}});let ve=He.getExtractedText();ve!==null&&(Pe=ve)}}L.delete(S.id),q.delete(S.id);let ke=Pe!==S.content,ye=S.streaming!==!1;ke&&(S.content=Pe),S.streaming=!1,(ke||ye)&&p(S)}else if(m!==null){let S=m;L.delete(S.id),q.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}o({type:"status",status:"idle"})}else wt==="error"&&O.error&&o({type:"error",error:O.error instanceof Error?O.error:new Error(String(O.error))})}}}};function _r(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ln(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function rn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var an=class{constructor(n={},o){this.config=n;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=n=>{var o,t;n.type==="message"?this.upsertMessage(n.message):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)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var n,o;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(o=(n=this.callbacks).onError)==null||o.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 o={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}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,o){return this.client.submitMessageFeedback(n,o)}async submitCSATFeedback(n,o){return this.client.submitCSATFeedback(n,o)}async submitNPSFeedback(n,o){return this.client.submitNPSFeedback(n,o)}updateConfig(n){this.config={...this.config,...n},this.client=new Qt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:o,content:t,llmContent:r,contentParts:s,id:i,createdAt:a,sequence:d,streaming:u=!1}=n,p={id:i!=null?i:o==="user"?Ln():o==="assistant"?rn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s}};return this.upsertMessage(p),p}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}async sendMessage(n,o){var u,f,p,m,w;let t=n.trim();if(!t&&(!(o!=null&&o.contentParts)||o.contentParts.length===0))return;(u=this.abortController)==null||u.abort();let r=Ln(),s=rn(),i={id:r,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1,...(o==null?void 0:o.contentParts)&&o.contentParts.length>0&&{contentParts:o.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(h){let R={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(R),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h instanceof Error?(p=(f=this.callbacks).onError)==null||p.call(f,h):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(h)))}}async continueConversation(){var r,s,i,a,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let n=rn();this.setStreaming(!0);let o=new AbortController;this.abortController=o;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n},this.handleEvent)}catch(u){let f={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(f),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,u):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(u)))}}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.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r: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 o=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let o=this.ensureSequence(n),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),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((o,t)=>{var d,u;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,a=(u=t.sequence)!=null?u:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var g=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var Di=Hi(require("lucide"),1),ie=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Di[r];return s?_i(s,n,o,t):(console.warn(`Lucide icon "${e}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${e}":`,r),null}};function _i(e,n,o,t){if(!e||!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(n)),r.setAttribute("height",String(n)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.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(([u,f])=>{u!=="stroke"&&d.setAttribute(u,String(f))}),r.appendChild(d)}}}),r}function qr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ur(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function zr(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Jr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Xn(e){return{type:"text",text:e}}function Yr(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 Kr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;n({type:"image",image:r,mimeType:e.type,alt:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Vr(e,n=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Xr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qi=["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"],Yt=[...Xr,...qi];function Ui(e){return Xr.includes(e)||e.startsWith("image/")}function Gn(e){return Ui(e.type)}async function Gr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Gn(e)?n({type:"image",image:r,mimeType:e.type,alt:e.name}):n({type:"file",data:r,mimeType:e.type,filename:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Qr(e,n=Yt,o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function zi(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Zr(e,n){let o=zi(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]||o||"FILE"}var Qn={allowedTypes:Yt,maxFileSize:10*1024*1024,maxFiles:4};function Ji(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Yi(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 Zt=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var o,t,r;this.config={allowedTypes:(o=n.allowedTypes)!=null?o:Qn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Qn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Qn.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:Qn.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,r,s,i,a,d,u;if(!n||n.length===0)return;let o=Array.from(n);for(let f of o){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,f,"count");continue}let p=Qr(f,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,m);continue}try{let m=await Gr(f),w=Gn(f)?URL.createObjectURL(f):null,h={id:Ji(),file:f,previewUrl:w,contentPart:m};this.attachments.push(h),this.renderPreview(h)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(u=(d=this.config).onAttachmentsChange)==null||u.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let o=this.attachments.findIndex(d=>d.id===n);if(o===-1)return;let t=this.attachments[o];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(o,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,o;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(o=(n=this.config).onAttachmentsChange)==null||o.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let o=Gn(n.file),t=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",o&&n.previewUrl){let i=g("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Yi(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=g("span");u.textContent=Zr(n.file.type,n.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--cw-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",i.appendChild(u),t.appendChild(i)}let r=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="rgba(0, 0, 0, 0.6)",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ie("x",10,"#ffffff",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="#ffffff",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(r),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,o){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:o})}};var ys=()=>{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"},Ki=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",o=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:o;return n==="light"?o:n==="dark"||ys()==="dark"?t:o},ei=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(ys())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(ys());o.addEventListener?(o.addEventListener("change",t),n.push(()=>o.removeEventListener("change",t))):o.addListener&&(o.addListener(t),n.push(()=>o.removeListener(t)))}return()=>{n.forEach(o=>o())}},Zn=(e,n)=>{let o=Ki(n);Object.entries(o).forEach(([t,r])=>{if(r==null||r==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(r))})};var ti=require("idiomorph"),ni=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;ti.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&t&&r.classList.contains("tvw-animate-typing"))return!1}}})};var pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Bt={"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 Pn=(e,n)=>{let o=g("button");o.type="button",o.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,12 +12,12 @@
|
|
|
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
|
-
`,o.addEventListener("click",n);let t=s=>{var y,A,I,v,N,C,k,z,_,ne,re,V;let i=(y=s.launcher)!=null?y:{},a=o.querySelector("[data-role='launcher-title']");a&&(a.textContent=(A=i.title)!=null?A:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(I=i.subtitle)!=null?I:"Get answers fast");let u=o.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let f=o.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let J=(v=i.agentIconSize)!=null?v:"40px";if(f.style.height=J,f.style.width=J,f.innerHTML="",i.agentIconName){let L=parseFloat(J)||24,q=ie(i.agentIconName,L*.6,"#ffffff",2);q?(f.appendChild(q),f.style.display=""):(f.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(C=i.agentIconText)!=null?C:"\u{1F4AC}",f.style.display="")}let p=o.querySelector("[data-role='launcher-image']");if(p){let J=(k=i.agentIconSize)!=null?k:"40px";p.style.height=J,p.style.width=J,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(p.src=i.iconUrl,p.style.display="block"):p.style.display="none"}let m=o.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let J=(z=i.callToActionIconSize)!=null?z:"32px";m.style.height=J,m.style.width=J,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("tvw-bg-cw-primary")):(m.style.backgroundColor="",m.classList.add("tvw-bg-cw-primary"));let L=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,L=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display="",m.innerHTML="",i.callToActionIconName){let q=parseFloat(J)||24,Z=Math.max(q-L,8),de=ie(i.callToActionIconName,Z,"currentColor",2);de?m.appendChild(de):m.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(ne=i.callToActionIconText)!=null?ne:"\u2197"}let w=i.position&&It[i.position]?It[i.position]:It["bottom-right"],h="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";o.className=`${h} ${w}`;let R="1px solid #e5e7eb",M="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(re=i.border)!=null?re:R,o.style.boxShadow=(V=i.shadow)!=null?V:M},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var Ut=e=>{var ne,re,V,J,L,q,Z,de,qe,Ct,ee,j,at,xt,vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt;let{config:n,showClose:o=!0}=e,t=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(ne=n==null?void 0:n.launcher)!=null?ne:{},s=(re=r.headerIconSize)!=null?re:"48px",i=(V=r.closeButtonSize)!=null?V:"32px",a=(J=r.closeButtonPlacement)!=null?J:"inline",d=(L=r.headerIconHidden)!=null?L:!1,u=r.headerIconName,f=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=s,f.style.width=s,!d)if(u){let U=parseFloat(s)||24,Re=ie(u,U*.6,"#ffffff",2);Re?f.replaceChildren(Re):f.textContent=(Z=(q=n==null?void 0:n.launcher)==null?void 0:q.agentIconText)!=null?Z:"\u{1F4AC}"}else if((de=n==null?void 0:n.launcher)!=null&&de.iconUrl){let U=g("img");U.src=n.launcher.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=s,U.style.width=s,f.replaceChildren(U)}else f.textContent=(Ct=(qe=n==null?void 0:n.launcher)==null?void 0:qe.agentIconText)!=null?Ct:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(j=(ee=n==null?void 0:n.launcher)==null?void 0:ee.title)!=null?j:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(xt=(at=n==null?void 0:n.launcher)==null?void 0:at.subtitle)!=null?xt:"Here to help you get answers fast",p.append(m,w),d?t.append(p):t.append(f,p);let h=(vt=r.clearChat)!=null?vt:{},R=(Rt=h.enabled)!=null?Rt:!0,M=(Ft=h.placement)!=null?Ft:"inline",y=null,A=null;if(R){let U=(D=h.size)!=null?D:"32px",Re=(fe=h.iconName)!=null?fe:"refresh-cw",Xe=(lt=h.iconColor)!=null?lt:"",Wt=(dt=h.backgroundColor)!=null?dt:"",gt=(Ve=h.borderWidth)!=null?Ve:"",Pt=(ct=h.borderColor)!=null?ct:"",Fe=(jt=h.borderRadius)!=null?jt:"",st=($t=h.paddingX)!=null?$t:"",kt=(Ot=h.paddingY)!=null?Ot:"",mt=(F=h.tooltipText)!=null?F:"Clear chat",ht=(Ue=h.showTooltip)!=null?Ue:!0;A=g("div",M==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),M==="top-right"&&(A.style.right="48px"),y=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),y.style.height=U,y.style.width=U,y.type="button",y.setAttribute("aria-label",mt);let P=ie(Re,"20px",Xe||"",2);if(P&&y.appendChild(P),Xe&&(y.style.color=Xe,y.classList.remove("tvw-text-cw-muted")),Wt&&(y.style.backgroundColor=Wt,y.classList.remove("hover:tvw-bg-gray-100")),gt||Pt){let te=gt||"0px",we=Pt||"transparent";y.style.border=`${te} solid ${we}`,y.classList.remove("tvw-border-none")}if(Fe&&(y.style.borderRadius=Fe,y.classList.remove("tvw-rounded-full")),st?(y.style.paddingLeft=st,y.style.paddingRight=st):(y.style.paddingLeft="",y.style.paddingRight=""),kt?(y.style.paddingTop=kt,y.style.paddingBottom=kt):(y.style.paddingTop="",y.style.paddingBottom=""),A.appendChild(y),ht&&mt&&y&&A){let te=null,we=()=>{if(te||!y)return;te=g("div","tvw-clear-chat-tooltip"),te.textContent=mt;let St=g("div");St.className="tvw-clear-chat-tooltip-arrow",te.appendChild(St);let ze=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${ze.left+ze.width/2}px`,te.style.top=`${ze.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Ge=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};A.addEventListener("mouseenter",we),A.addEventListener("mouseleave",Ge),y.addEventListener("focus",we),y.addEventListener("blur",Ge),A._cleanupTooltip=()=>{Ge(),A&&(A.removeEventListener("mouseenter",we),A.removeEventListener("mouseleave",Ge)),y&&(y.removeEventListener("focus",we),y.removeEventListener("blur",Ge))}}M==="inline"&&t.appendChild(A)}let I=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":R&&M==="inline"?"":"tvw-ml-auto"),v=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");v.style.height=i,v.style.width=i,v.type="button";let N=(ge=r.closeButtonTooltipText)!=null?ge:"Close chat",C=(tt=r.closeButtonShowTooltip)!=null?tt:!0;v.setAttribute("aria-label",N),v.style.display=o?"":"none";let k=(me=r.closeButtonIconName)!=null?me:"x",z=(nt=r.closeButtonIconText)!=null?nt:"\xD7",_=ie(k,"20px",r.closeButtonColor||"",2);if(_?v.appendChild(_):v.textContent=z,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let U=r.closeButtonBorderWidth||"0px",Re=r.closeButtonBorderColor||"transparent";v.style.border=`${U} solid ${Re}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),I.appendChild(v),C&&N){let U=null,Re=()=>{if(U)return;U=g("div","tvw-clear-chat-tooltip"),U.textContent=N;let Wt=g("div");Wt.className="tvw-clear-chat-tooltip-arrow",U.appendChild(Wt);let gt=v.getBoundingClientRect();U.style.position="fixed",U.style.left=`${gt.left+gt.width/2}px`,U.style.top=`${gt.top-8}px`,U.style.transform="translate(-50%, -100%)",document.body.appendChild(U)},Xe=()=>{U&&U.parentNode&&(U.parentNode.removeChild(U),U=null)};I.addEventListener("mouseenter",Re),I.addEventListener("mouseleave",Xe),v.addEventListener("focus",Re),v.addEventListener("blur",Xe),I._cleanupTooltip=()=>{Xe(),I.removeEventListener("mouseenter",Re),I.removeEventListener("mouseleave",Xe),v.removeEventListener("focus",Re),v.removeEventListener("blur",Xe)}}return a!=="top-right"&&t.appendChild(I),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:v,closeButtonWrapper:I,clearChatButton:y,clearChatButtonWrapper:A}},en=(e,n,o)=>{var i,a,d,u;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"inline";e.appendChild(n.header),r==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var vs=e=>Ut({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),bs=e=>{var h,R,M,y;let{config:n,showClose:o=!0,onClose:t}=e,r=(h=n==null?void 0:n.launcher)!=null?h:{},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=(R=r.title)!=null?R:"Chat Assistant",s.appendChild(i);let a=(M=r.closeButtonSize)!=null?M:"32px",d=g("div",""),u=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");u.style.height=a,u.style.width=a,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=o?"":"none";let f=(y=r.closeButtonIconName)!=null?y:"x",p=ie(f,"20px",r.closeButtonColor||"",2);p?u.appendChild(p):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),s.appendChild(d);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Cs=e=>{var v,N,C,k,z,_,ne,re;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(v=n==null?void 0:n.launcher)!=null?v:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=s.headerIconSize)!=null?N:"56px",u=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");u.style.height=d,u.style.width=d;let f=s.headerIconName;if(f){let V=parseFloat(d)||24,J=ie(f,V*.5,"#ffffff",2);J?u.replaceChildren(J):u.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let V=g("img");V.src=s.iconUrl,V.alt="",V.className="tvw-rounded-xl tvw-object-cover",V.style.height=d,V.style.width=d,u.replaceChildren(V)}else u.textContent=(k=s.agentIconText)!=null?k:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(z=s.title)!=null?z:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(_=s.subtitle)!=null?_:"Here to help you get answers fast",p.append(m,w),a.append(u,p);let h=(ne=s.closeButtonSize)!=null?ne:"32px",R=g("div",""),M=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");M.style.height=h,M.style.width=h,M.type="button",M.setAttribute("aria-label","Close chat"),M.style.display=o?"":"none";let y=(re=s.closeButtonIconName)!=null?re:"x",A=ie(y,"20px",s.closeButtonColor||"",2);A?M.appendChild(A):M.textContent="\xD7",t&&M.addEventListener("click",t),R.appendChild(M),a.appendChild(R),i.appendChild(a);let I=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return I.textContent="Online and ready to help",i.appendChild(I),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:M,closeButtonWrapper:R,clearChatButton:null,clearChatButtonWrapper:null}},es={default:vs,minimal:bs,expanded:Cs},xs=e=>{var n;return(n=es[e])!=null?n:es.default},ln=(e,n,o)=>{var i,a,d;if(n!=null&&n.render){let u=n.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=g("div");f.style.display="none";let p=g("span"),m=g("span"),w=g("button");w.style.display="none";let h=g("div");return h.style.display="none",{header:u,iconHolder:f,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=xs(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.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 Vi=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'}},dn=e=>{var vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt,U,Re,Xe,Wt,gt,Pt,Fe,st,kt,mt,ht,P;let{config:n}=e,o=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=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");r.style.outline="none";let s=g("textarea");s.placeholder=(Rt=(vt=n==null?void 0:n.copy)==null?void 0:vt.inputPlaceholder)!=null?Rt:"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",s.rows=1;let i=(D=(Ft=n==null?void 0:n.theme)==null?void 0:Ft.inputFontFamily)!=null?D:"sans-serif",a=(lt=(fe=n==null?void 0:n.theme)==null?void 0:fe.inputFontWeight)!=null?lt:"400";s.style.fontFamily=Vi(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=(dt=n==null?void 0:n.sendButton)!=null?dt:{},w=(Ve=m.useIcon)!=null?Ve:!1,h=(ct=m.iconText)!=null?ct:"\u2191",R=m.iconName,M=(jt=m.tooltipText)!=null?jt:"Send message",y=($t=m.showTooltip)!=null?$t:!1,A=(Ot=m.size)!=null?Ot:"40px",I=m.backgroundColor,v=m.textColor,N=g("div","tvw-send-button-wrapper"),C=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(C.type="submit",w){if(C.style.width=A,C.style.height=A,C.style.minWidth=A,C.style.minHeight=A,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",R){let te=parseFloat(A)||24,we=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Ge=ie(R,te,we,2);Ge?(C.appendChild(Ge),C.style.color=we):(C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white"))}else C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white");I?C.style.backgroundColor=I:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(Ue=(F=n==null?void 0:n.copy)==null?void 0:F.sendButtonLabel)!=null?Ue:"Send",v?C.style.color=v:C.classList.add("tvw-text-white");if(m.borderWidth&&(C.style.borderWidth=m.borderWidth,C.style.borderStyle="solid"),m.borderColor&&(C.style.borderColor=m.borderColor),m.paddingX?(C.style.paddingLeft=m.paddingX,C.style.paddingRight=m.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),m.paddingY?(C.style.paddingTop=m.paddingY,C.style.paddingBottom=m.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),y&&M){let te=g("div","tvw-send-button-tooltip");te.textContent=M,N.appendChild(te)}N.appendChild(C);let k=(ge=n==null?void 0:n.voiceRecognition)!=null?ge:{},z=k.enabled===!0,_=null,ne=null,re=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(z&&re){ne=g("div","tvw-send-button-wrapper"),_=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),_.type="button",_.setAttribute("aria-label","Start voice recognition");let te=(tt=k.iconName)!=null?tt:"mic",we=(me=k.iconSize)!=null?me:A,Ge=parseFloat(we)||24,St=(nt=k.backgroundColor)!=null?nt:I,ze=(U=k.iconColor)!=null?U:v;_.style.width=we,_.style.height=we,_.style.minWidth=we,_.style.minHeight=we,_.style.fontSize="18px",_.style.lineHeight="1";let ft=ze||"currentColor",Lt=ie(te,Ge,ft,1.5);Lt?(_.appendChild(Lt),_.style.color=ft):(_.textContent="\u{1F3A4}",_.style.color=ft),St?_.style.backgroundColor=St:_.classList.add("tvw-bg-cw-primary"),ze?_.style.color=ze:!ze&&!v&&_.classList.add("tvw-text-white"),k.borderWidth&&(_.style.borderWidth=k.borderWidth,_.style.borderStyle="solid"),k.borderColor&&(_.style.borderColor=k.borderColor),k.paddingX&&(_.style.paddingLeft=k.paddingX,_.style.paddingRight=k.paddingX),k.paddingY&&(_.style.paddingTop=k.paddingY,_.style.paddingBottom=k.paddingY),ne.appendChild(_);let Ht=(Re=k.tooltipText)!=null?Re:"Start voice recognition";if(((Xe=k.showTooltip)!=null?Xe:!1)&&Ht){let Kt=g("div","tvw-send-button-tooltip");Kt.textContent=Ht,ne.appendChild(Kt)}}let V=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},J=V.enabled===!0,L=null,q=null,Z=null,de=null;if(J){de=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),de.style.display="none",Z=g("input"),Z.type="file",Z.accept=((gt=V.allowedTypes)!=null?gt:Yt).join(","),Z.multiple=((Pt=V.maxFiles)!=null?Pt:4)>1,Z.style.display="none",Z.setAttribute("aria-label","Attach files"),q=g("div","tvw-send-button-wrapper"),L=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),L.type="button",L.setAttribute("aria-label",(Fe=V.buttonTooltipText)!=null?Fe:"Attach file");let te=(st=V.buttonIconName)!=null?st:"paperclip",we=A,Ge=parseFloat(we)||40,St=Math.round(Ge*.6);L.style.width=we,L.style.height=we,L.style.minWidth=we,L.style.minHeight=we,L.style.fontSize="18px",L.style.lineHeight="1",L.style.backgroundColor="transparent",L.style.color="var(--cw-primary, #111827)",L.style.border="none",L.style.borderRadius="6px",L.style.transition="background-color 0.15s ease",L.addEventListener("mouseenter",()=>{L.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),L.addEventListener("mouseleave",()=>{L.style.backgroundColor="transparent"});let ze=ie(te,St,"currentColor",1.5);ze?L.appendChild(ze):L.textContent="\u{1F4CE}",L.addEventListener("click",Ht=>{Ht.preventDefault(),Z==null||Z.click()}),q.appendChild(L);let ft=(kt=V.buttonTooltipText)!=null?kt:"Attach file",Lt=g("div","tvw-send-button-tooltip");Lt.textContent=ft,q.appendChild(Lt)}r.addEventListener("click",te=>{te.target!==C&&te.target!==N&&te.target!==_&&te.target!==ne&&te.target!==L&&te.target!==q&&s.focus()}),de&&(de.style.gap="8px",r.append(de)),Z&&r.append(Z),r.append(s);let qe=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Ct=g("div","tvw-flex tvw-items-center tvw-gap-2");q&&Ct.append(q);let ee=g("div","tvw-flex tvw-items-center tvw-gap-1");ne&&ee.append(ne),ee.append(N),qe.append(Ct,ee),r.append(qe);let j=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),at=(mt=n==null?void 0:n.statusIndicator)!=null?mt:{},xt=(ht=at.visible)!=null?ht:!0;return j.style.display=xt?"":"none",j.textContent=(P=at.idleText)!=null?P:"Online",o.append(t,r,j),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:N,micButton:_,micButtonWrapper:ne,statusText:j,attachmentButton:L,attachmentButtonWrapper:q,attachmentInput:Z,attachmentPreviewsContainer:de,actionsRow:qe,leftActions:Ct,rightActions:ee}};var si=e=>{var d,u,f,p,m,w,h;if(!((u=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?u:!0)){let R=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),M=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(p=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?p:"100%";return R.style.width=y,M.style.width="100%",R.appendChild(M),{wrapper:R,panel:M}}let o=(m=e==null?void 0:e.launcher)!=null?m:{},t=o.position&&It[o.position]?It[o.position]:It["bottom-right"],r=g("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(h=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?h:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,r.appendChild(s),{wrapper:r,panel:s}},oi=(e,n=!0)=>{var w,h,R,M,y,A,I;let o=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=e==null?void 0:e.layout)==null?void 0:w.header,r=((h=e==null?void 0:e.layout)==null?void 0:h.showHeader)!==!1,s=t?ln(e,t,{showClose:n}):Ut({config:e,showClose:n}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(M=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?M:"Hello \u{1F44B}";let u=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(A=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?A:"Ask anything about your account or products.",a.append(d,u);let f=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let p=dn({config:e}),m=((I=e==null?void 0:e.layout)==null?void 0:I.showFooter)!==!1;return r?en(o,s,e):(s.header.style.display="none",en(o,s,e)),o.append(i),m||(p.footer.style.display="none"),o.append(p.footer),{container:o,body:i,messagesWrapper:f,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.statusText,introTitle:d,introSubtitle:u,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:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions}};var Hn=()=>{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 o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.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 r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",e.appendChild(n),e.appendChild(o),e.appendChild(t),e.appendChild(r),e},Xi=(e,n)=>{let o=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=g("img");r.src=t,r.alt=n==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=n==="user"?"U":"A",o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},ri=(e,n)=>{let o=g("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?o.textContent=n.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Gi=(e,n="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.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:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.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 o},Ss=(e,n,o)=>{var h,R,M,y,A,I;let t=(h=n.showCopy)!=null?h:!0,r=(R=n.showUpvote)!=null?R:!0,s=(M=n.showDownvote)!=null?M:!0,i=(y=n.visibility)!=null?y:"hover",a=(A=n.align)!=null?A:"right",d=(I=n.layout)!=null?I:"pill-inside",u={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],p=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=null,w=(v,N,C,k)=>{let z=document.createElement("button");z.className="tvw-message-action-btn",z.setAttribute("aria-label",N),z.setAttribute("title",N),k&&z.setAttribute("data-action",k);let _=ie(v,14,"currentColor",2);return _&&z.appendChild(_),z.addEventListener("click",ne=>{ne.preventDefault(),ne.stopPropagation(),C()}),z};if(t){let v=w("copy","Copy message",()=>{let N=e.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let C=ie("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=ie("copy",14,"currentColor",2);k&&(v.innerHTML="",v.appendChild(k))},2e3)}).catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",C)}),o!=null&&o.onCopy&&o.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");p.appendChild(v)}if(r){let v=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=p.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),m="upvote",v.classList.add("tvw-message-action-active");let k={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"upvote");p.appendChild(v)}if(s){let v=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=p.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),m="downvote",v.classList.add("tvw-message-action-active");let k={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"downvote");p.appendChild(v)}return p},cn=(e,n,o,t,r)=>{var I,v,N,C,k;let s=o!=null?o:{},i=(I=s.layout)!=null?I:"bubble",a=s.avatar,d=s.timestamp,u=(v=a==null?void 0:a.show)!=null?v:!1,f=(N=d==null?void 0:d.show)!=null?N:!1,p=(C=a==null?void 0:a.position)!=null?C:"left",m=(k=d==null?void 0:d.position)!=null?k:"below",w=Gi(e.role,i),h=g("div",w.join(" "));h.id=`bubble-${e.id}`,h.setAttribute("data-message-id",e.id);let R=document.createElement("div");if(R.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),f&&m==="inline"&&e.createdAt){let z=ri(e,d);z.classList.add("tvw-ml-2","tvw-inline"),R.appendChild(z)}if(h.appendChild(R),f&&m==="below"&&e.createdAt){let z=ri(e,d);z.classList.add("tvw-mt-1"),h.appendChild(z)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let z=Hn();h.appendChild(z)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let z=Ss(e,t,r);h.appendChild(z)}if(!u||e.role==="system")return h;let y=g("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),A=Xi(a,e.role);return p==="right"||p==="left"&&e.role==="user"?y.append(h,A):y.append(A,h),h.classList.remove("tvw-max-w-[85%]"),h.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},ii=(e,n,o,t,r)=>{let s=o!=null?o:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):cn(e,n,o,t,r)};var un=new Set,ai=(e,n)=>{let o=un.has(e),t=n.querySelector('button[data-expand-header="true"]'),r=n.querySelector(".tvw-border-t");if(!t||!r)return;t.setAttribute("aria-expanded",o?"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(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},As=e=>{let n=e.reasoning,o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let t=un.has(e.id),r=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");r.type="button",r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("data-expand-header","true"),r.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=$r(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),f=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let p=g("div","tvw-flex tvw-items-center tvw-ml-auto");p.append(d),r.append(s,p);let m=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let w=n.chunks.join(""),h=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return h.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(h),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),o.append(r,m),o};var pn=new Set,li=(e,n,o)=>{var u;let t=pn.has(e),r=(u=o==null?void 0:o.toolCall)!=null?u:{},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 f=r.toggleTextColor||r.headerTextColor||"currentColor",p=ie(t?"chevron-up":"chevron-down",16,f,2);p?d.appendChild(p):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Ts=(e,n)=>{var R;let o=e.toolCall,t=(R=n==null?void 0:n.toolCall)!=null?R:{},r=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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!o)return r;let s=pn.has(e.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),d=g("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Or(o),a.appendChild(d);let u=g("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",p=ie(s?"chevron-up":"chevron-down",16,f,2);p?u.appendChild(p):u.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(a,m);let w=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",t.contentBackgroundColor&&(w.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(w.style.color=t.contentTextColor),t.contentPaddingX&&(w.style.paddingLeft=t.contentPaddingX,w.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(w.style.paddingTop=t.contentPaddingY,w.style.paddingBottom=t.contentPaddingY),o.name){let M=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?M.style.color=t.contentTextColor:t.headerTextColor&&(M.style.color=t.headerTextColor),M.textContent=o.name,w.appendChild(M)}if(o.args!==void 0){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=ws(o.args),M.append(y,A),w.appendChild(M)}if(o.chunks&&o.chunks.length){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=o.chunks.join(`
|
|
16
|
-
`),M.append(y,A),w.appendChild(M)}if(o.status==="complete"&&o.result!==void 0){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=ws(o.result),M.append(y,A),w.appendChild(M)}if(o.status==="complete"&&typeof o.duration=="number"){let M=g("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(M.style.color=t.contentTextColor),M.textContent=`Duration: ${o.duration}ms`,w.appendChild(M)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let M=t.toggleTextColor||t.headerTextColor||"currentColor",y=ie(s?"chevron-up":"chevron-down",16,M,2);y?u.appendChild(y):u.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var di=e=>{let n=[];return{buttons:n,render:(t,r,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(w=>w.role==="user"))return;let f=document.createDocumentFragment(),p=r?r.isStreaming():!1,m=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'}};t.forEach(w=>{let h=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");h.type="button",h.textContent=w,h.disabled=p,a!=null&&a.fontFamily&&(h.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(h.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(h.style.paddingLeft=a.paddingX,h.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(h.style.paddingTop=a.paddingY,h.style.paddingBottom=a.paddingY),h.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(w))}),f.appendChild(h),n.push(h)}),e.appendChild(f)}}};var ci={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"}},Ms=(e,n,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var h,R,M;if(s.dataset.enhanced==="true")return;let i=(h=s.dataset.tvForm)!=null?h:"init";s.dataset.enhanced="true";let a=(R=ci[i])!=null?R:ci.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=g("div","tvw-space-y-1"),u=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=a.title,d.appendChild(u),a.description){let y=g("p","tvw-text-sm tvw-text-cw-muted");y.textContent=a.description,d.appendChild(y)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(y=>{var C,k;let A=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");A.htmlFor=`${n.id}-${i}-${y.name}`;let I=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=y.label,A.appendChild(I);let v=(C=y.type)!=null?C:"text",N;v==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=v),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}-${y.name}`,N.name=y.name,N.placeholder=(k=y.placeholder)!=null?k:"",y.required&&(N.required=!0),A.appendChild(N),f.appendChild(A)});let p=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),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=(M=a.submitLabel)!=null?M:"Submit",p.appendChild(m),p.appendChild(w),f.appendChild(p),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var N,C;y.preventDefault();let A=(N=o.formEndpoint)!=null?N:"/form",I=new FormData(f),v={};I.forEach((k,z)=>{v[z]=k}),v.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let k=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let z=await k.json();m.textContent=(C=z.message)!=null?C:"Thanks! We'll be in touch soon.",z.success&&z.nextPrompt&&await t.sendMessage(String(z.nextPrompt))}catch(k){m.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Es=class{constructor(){this.plugins=new Map}register(n){var o;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(o=n.onRegister)==null||o.call(n)}unregister(n){var t;let o=this.plugins.get(n);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=n.priority)!=null?r:0)})}getForInstance(n){let o=this.getAll();if(!n||n.length===0)return o;let t=new Set(n.map(s=>s.id));return[...o.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 o;return(o=n.onUnregister)==null?void 0:o.call(n)}),this.plugins.clear()}},Bn=new Es;var Ws={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"},ks={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"},Be={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ws,darkTheme:ks,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 ts(e){var n,o,t,r,s,i,a,d,u,f,p,m,w,h,R,M,y,A,I;return e?{...Be,...e,theme:{...Be.theme,...e.theme},darkTheme:{...Be.darkTheme,...e.darkTheme},launcher:{...Be.launcher,...e.launcher,clearChat:{...(n=Be.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Be.copy,...e.copy},sendButton:{...Be.sendButton,...e.sendButton},statusIndicator:{...Be.statusIndicator,...e.statusIndicator},voiceRecognition:{...Be.voiceRecognition,...e.voiceRecognition},features:{...Be.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Be.suggestionChips,suggestionChipsConfig:{...Be.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Be.layout,...e.layout,header:{...(r=Be.layout)==null?void 0:r.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Be.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(u=(d=Be.layout)==null?void 0:d.messages)==null?void 0:u.avatar,...(p=(f=e.layout)==null?void 0:f.messages)==null?void 0:p.avatar},timestamp:{...(w=(m=Be.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(R=(h=e.layout)==null?void 0:h.messages)==null?void 0:R.timestamp}},slots:{...(M=Be.layout)==null?void 0:M.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Be.markdown,...e.markdown,options:{...(A=Be.markdown)==null?void 0:A.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var ui=()=>{let e=new Map,n=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=e.get(r))==null||i.delete(s)};return{on:n,off:o,emit:(r,s)=>{var i;(i=e.get(r))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Qi=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Zi=e=>{let n=e.trim(),o=n.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<n.length;r+=1){let s=n[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(o,r+1)}return null},In=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Qi(e),o=Zi(n);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Ls=e=>typeof e=="string"?e:e==null?"":String(e),tn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ls(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Ls(o.element);if(t&&((r=n.document)!=null&&r.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:Ls(o.text)}}},pi=e=>Array.isArray(e)?e.map(n=>String(n)):[],Rn=e=>{let n=new Set(pi(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(pi(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((u,f)=>u||(f==null?void 0:f({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 u of e.handlers)if(u)try{let f=()=>{e.emit("action:resubmit",d)},p=u(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:f});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var ea=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}},ta=e=>e.map(n=>({...n,streaming:!1})),ns=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?ea(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?ta(o.messages):void 0};t.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=n();if(o)try{o.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Ps=class{constructor(){this.components=new Map}register(n,o){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,o)}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(([o,t])=>{this.register(o,t)})}},gn=new Ps;var mn=require("partial-json");function na(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function sa(e,n){if(!na(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:n}}function ss(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e;try{let r=(0,mn.parse)(o,mn.STR|mn.OBJ),s=sa(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function gi(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function os(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=gn.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:o,updateProps:a=>{r&&r(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function mi(){let e=ss();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rs(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 is(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 oa=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function as(e){let{onSubmit:n,onDismiss:o,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:u=oa}=e,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let h=document.createElement("h3");h.className="tvw-feedback-title",h.textContent=t,w.appendChild(h);let R=document.createElement("p");R.className="tvw-feedback-subtitle",R.textContent=r,w.appendChild(R),m.appendChild(w);let M=document.createElement("div");M.className="tvw-feedback-rating tvw-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let C=1;C<=5;C++){let k=document.createElement("button");k.type="button",k.className="tvw-feedback-rating-btn tvw-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),k.title=u[C-1],k.dataset.rating=String(C),k.innerHTML=`
|
|
15
|
+
`,o.addEventListener("click",n);let t=s=>{var y,A,B,v,N,C,k,z,_,ne,re,V;let i=(y=s.launcher)!=null?y:{},a=o.querySelector("[data-role='launcher-title']");a&&(a.textContent=(A=i.title)!=null?A:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(B=i.subtitle)!=null?B:"Get answers fast");let u=o.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let f=o.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let J=(v=i.agentIconSize)!=null?v:"40px";if(f.style.height=J,f.style.width=J,f.innerHTML="",i.agentIconName){let L=parseFloat(J)||24,q=ie(i.agentIconName,L*.6,"#ffffff",2);q?(f.appendChild(q),f.style.display=""):(f.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(C=i.agentIconText)!=null?C:"\u{1F4AC}",f.style.display="")}let p=o.querySelector("[data-role='launcher-image']");if(p){let J=(k=i.agentIconSize)!=null?k:"40px";p.style.height=J,p.style.width=J,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(p.src=i.iconUrl,p.style.display="block"):p.style.display="none"}let m=o.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let J=(z=i.callToActionIconSize)!=null?z:"32px";m.style.height=J,m.style.width=J,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("tvw-bg-cw-primary")):(m.style.backgroundColor="",m.classList.add("tvw-bg-cw-primary"));let L=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,L=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display="",m.innerHTML="",i.callToActionIconName){let q=parseFloat(J)||24,Z=Math.max(q-L,8),de=ie(i.callToActionIconName,Z,"currentColor",2);de?m.appendChild(de):m.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(ne=i.callToActionIconText)!=null?ne:"\u2197"}let w=i.position&&Bt[i.position]?Bt[i.position]:Bt["bottom-right"],h="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";o.className=`${h} ${w}`;let R="1px solid #e5e7eb",M="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(re=i.border)!=null?re:R,o.style.boxShadow=(V=i.shadow)!=null?V:M},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var Ut=e=>{var ne,re,V,J,L,q,Z,de,qe,Ct,ee,j,at,xt,vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt;let{config:n,showClose:o=!0}=e,t=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(ne=n==null?void 0:n.launcher)!=null?ne:{},s=(re=r.headerIconSize)!=null?re:"48px",i=(V=r.closeButtonSize)!=null?V:"32px",a=(J=r.closeButtonPlacement)!=null?J:"inline",d=(L=r.headerIconHidden)!=null?L:!1,u=r.headerIconName,f=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=s,f.style.width=s,!d)if(u){let U=parseFloat(s)||24,Re=ie(u,U*.6,"#ffffff",2);Re?f.replaceChildren(Re):f.textContent=(Z=(q=n==null?void 0:n.launcher)==null?void 0:q.agentIconText)!=null?Z:"\u{1F4AC}"}else if((de=n==null?void 0:n.launcher)!=null&&de.iconUrl){let U=g("img");U.src=n.launcher.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=s,U.style.width=s,f.replaceChildren(U)}else f.textContent=(Ct=(qe=n==null?void 0:n.launcher)==null?void 0:qe.agentIconText)!=null?Ct:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(j=(ee=n==null?void 0:n.launcher)==null?void 0:ee.title)!=null?j:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(xt=(at=n==null?void 0:n.launcher)==null?void 0:at.subtitle)!=null?xt:"Here to help you get answers fast",p.append(m,w),d?t.append(p):t.append(f,p);let h=(vt=r.clearChat)!=null?vt:{},R=(Rt=h.enabled)!=null?Rt:!0,M=(Ft=h.placement)!=null?Ft:"inline",y=null,A=null;if(R){let U=(D=h.size)!=null?D:"32px",Re=(fe=h.iconName)!=null?fe:"refresh-cw",Xe=(lt=h.iconColor)!=null?lt:"",Wt=(dt=h.backgroundColor)!=null?dt:"",gt=(Ve=h.borderWidth)!=null?Ve:"",Pt=(ct=h.borderColor)!=null?ct:"",Fe=(jt=h.borderRadius)!=null?jt:"",st=($t=h.paddingX)!=null?$t:"",kt=(Ot=h.paddingY)!=null?Ot:"",mt=(F=h.tooltipText)!=null?F:"Clear chat",ht=(Ue=h.showTooltip)!=null?Ue:!0;A=g("div",M==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),M==="top-right"&&(A.style.right="48px"),y=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),y.style.height=U,y.style.width=U,y.type="button",y.setAttribute("aria-label",mt);let P=ie(Re,"20px",Xe||"",2);if(P&&y.appendChild(P),Xe&&(y.style.color=Xe,y.classList.remove("tvw-text-cw-muted")),Wt&&(y.style.backgroundColor=Wt,y.classList.remove("hover:tvw-bg-gray-100")),gt||Pt){let te=gt||"0px",we=Pt||"transparent";y.style.border=`${te} solid ${we}`,y.classList.remove("tvw-border-none")}if(Fe&&(y.style.borderRadius=Fe,y.classList.remove("tvw-rounded-full")),st?(y.style.paddingLeft=st,y.style.paddingRight=st):(y.style.paddingLeft="",y.style.paddingRight=""),kt?(y.style.paddingTop=kt,y.style.paddingBottom=kt):(y.style.paddingTop="",y.style.paddingBottom=""),A.appendChild(y),ht&&mt&&y&&A){let te=null,we=()=>{if(te||!y)return;te=g("div","tvw-clear-chat-tooltip"),te.textContent=mt;let St=g("div");St.className="tvw-clear-chat-tooltip-arrow",te.appendChild(St);let ze=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${ze.left+ze.width/2}px`,te.style.top=`${ze.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Ge=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};A.addEventListener("mouseenter",we),A.addEventListener("mouseleave",Ge),y.addEventListener("focus",we),y.addEventListener("blur",Ge),A._cleanupTooltip=()=>{Ge(),A&&(A.removeEventListener("mouseenter",we),A.removeEventListener("mouseleave",Ge)),y&&(y.removeEventListener("focus",we),y.removeEventListener("blur",Ge))}}M==="inline"&&t.appendChild(A)}let B=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":R&&M==="inline"?"":"tvw-ml-auto"),v=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");v.style.height=i,v.style.width=i,v.type="button";let N=(ge=r.closeButtonTooltipText)!=null?ge:"Close chat",C=(tt=r.closeButtonShowTooltip)!=null?tt:!0;v.setAttribute("aria-label",N),v.style.display=o?"":"none";let k=(me=r.closeButtonIconName)!=null?me:"x",z=(nt=r.closeButtonIconText)!=null?nt:"\xD7",_=ie(k,"20px",r.closeButtonColor||"",2);if(_?v.appendChild(_):v.textContent=z,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let U=r.closeButtonBorderWidth||"0px",Re=r.closeButtonBorderColor||"transparent";v.style.border=`${U} solid ${Re}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),B.appendChild(v),C&&N){let U=null,Re=()=>{if(U)return;U=g("div","tvw-clear-chat-tooltip"),U.textContent=N;let Wt=g("div");Wt.className="tvw-clear-chat-tooltip-arrow",U.appendChild(Wt);let gt=v.getBoundingClientRect();U.style.position="fixed",U.style.left=`${gt.left+gt.width/2}px`,U.style.top=`${gt.top-8}px`,U.style.transform="translate(-50%, -100%)",document.body.appendChild(U)},Xe=()=>{U&&U.parentNode&&(U.parentNode.removeChild(U),U=null)};B.addEventListener("mouseenter",Re),B.addEventListener("mouseleave",Xe),v.addEventListener("focus",Re),v.addEventListener("blur",Xe),B._cleanupTooltip=()=>{Xe(),B.removeEventListener("mouseenter",Re),B.removeEventListener("mouseleave",Xe),v.removeEventListener("focus",Re),v.removeEventListener("blur",Xe)}}return a!=="top-right"&&t.appendChild(B),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:v,closeButtonWrapper:B,clearChatButton:y,clearChatButtonWrapper:A}},en=(e,n,o)=>{var i,a,d,u;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"inline";e.appendChild(n.header),r==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var vs=e=>Ut({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),bs=e=>{var h,R,M,y;let{config:n,showClose:o=!0,onClose:t}=e,r=(h=n==null?void 0:n.launcher)!=null?h:{},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=(R=r.title)!=null?R:"Chat Assistant",s.appendChild(i);let a=(M=r.closeButtonSize)!=null?M:"32px",d=g("div",""),u=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");u.style.height=a,u.style.width=a,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=o?"":"none";let f=(y=r.closeButtonIconName)!=null?y:"x",p=ie(f,"20px",r.closeButtonColor||"",2);p?u.appendChild(p):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),s.appendChild(d);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Cs=e=>{var v,N,C,k,z,_,ne,re;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(v=n==null?void 0:n.launcher)!=null?v:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=s.headerIconSize)!=null?N:"56px",u=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");u.style.height=d,u.style.width=d;let f=s.headerIconName;if(f){let V=parseFloat(d)||24,J=ie(f,V*.5,"#ffffff",2);J?u.replaceChildren(J):u.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let V=g("img");V.src=s.iconUrl,V.alt="",V.className="tvw-rounded-xl tvw-object-cover",V.style.height=d,V.style.width=d,u.replaceChildren(V)}else u.textContent=(k=s.agentIconText)!=null?k:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(z=s.title)!=null?z:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(_=s.subtitle)!=null?_:"Here to help you get answers fast",p.append(m,w),a.append(u,p);let h=(ne=s.closeButtonSize)!=null?ne:"32px",R=g("div",""),M=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");M.style.height=h,M.style.width=h,M.type="button",M.setAttribute("aria-label","Close chat"),M.style.display=o?"":"none";let y=(re=s.closeButtonIconName)!=null?re:"x",A=ie(y,"20px",s.closeButtonColor||"",2);A?M.appendChild(A):M.textContent="\xD7",t&&M.addEventListener("click",t),R.appendChild(M),a.appendChild(R),i.appendChild(a);let B=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return B.textContent="Online and ready to help",i.appendChild(B),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:M,closeButtonWrapper:R,clearChatButton:null,clearChatButtonWrapper:null}},es={default:vs,minimal:bs,expanded:Cs},xs=e=>{var n;return(n=es[e])!=null?n:es.default},ln=(e,n,o)=>{var i,a,d;if(n!=null&&n.render){let u=n.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=g("div");f.style.display="none";let p=g("span"),m=g("span"),w=g("button");w.style.display="none";let h=g("div");return h.style.display="none",{header:u,iconHolder:f,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=xs(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.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 Vi=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'}},dn=e=>{var vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt,U,Re,Xe,Wt,gt,Pt,Fe,st,kt,mt,ht,P;let{config:n}=e,o=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=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");r.style.outline="none";let s=g("textarea");s.placeholder=(Rt=(vt=n==null?void 0:n.copy)==null?void 0:vt.inputPlaceholder)!=null?Rt:"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",s.rows=1;let i=(D=(Ft=n==null?void 0:n.theme)==null?void 0:Ft.inputFontFamily)!=null?D:"sans-serif",a=(lt=(fe=n==null?void 0:n.theme)==null?void 0:fe.inputFontWeight)!=null?lt:"400";s.style.fontFamily=Vi(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=(dt=n==null?void 0:n.sendButton)!=null?dt:{},w=(Ve=m.useIcon)!=null?Ve:!1,h=(ct=m.iconText)!=null?ct:"\u2191",R=m.iconName,M=(jt=m.tooltipText)!=null?jt:"Send message",y=($t=m.showTooltip)!=null?$t:!1,A=(Ot=m.size)!=null?Ot:"40px",B=m.backgroundColor,v=m.textColor,N=g("div","tvw-send-button-wrapper"),C=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(C.type="submit",w){if(C.style.width=A,C.style.height=A,C.style.minWidth=A,C.style.minHeight=A,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",R){let te=parseFloat(A)||24,we=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Ge=ie(R,te,we,2);Ge?(C.appendChild(Ge),C.style.color=we):(C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white"))}else C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white");B?C.style.backgroundColor=B:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(Ue=(F=n==null?void 0:n.copy)==null?void 0:F.sendButtonLabel)!=null?Ue:"Send",v?C.style.color=v:C.classList.add("tvw-text-white");if(m.borderWidth&&(C.style.borderWidth=m.borderWidth,C.style.borderStyle="solid"),m.borderColor&&(C.style.borderColor=m.borderColor),m.paddingX?(C.style.paddingLeft=m.paddingX,C.style.paddingRight=m.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),m.paddingY?(C.style.paddingTop=m.paddingY,C.style.paddingBottom=m.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),y&&M){let te=g("div","tvw-send-button-tooltip");te.textContent=M,N.appendChild(te)}N.appendChild(C);let k=(ge=n==null?void 0:n.voiceRecognition)!=null?ge:{},z=k.enabled===!0,_=null,ne=null,re=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(z&&re){ne=g("div","tvw-send-button-wrapper"),_=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),_.type="button",_.setAttribute("aria-label","Start voice recognition");let te=(tt=k.iconName)!=null?tt:"mic",we=(me=k.iconSize)!=null?me:A,Ge=parseFloat(we)||24,St=(nt=k.backgroundColor)!=null?nt:B,ze=(U=k.iconColor)!=null?U:v;_.style.width=we,_.style.height=we,_.style.minWidth=we,_.style.minHeight=we,_.style.fontSize="18px",_.style.lineHeight="1";let ft=ze||"currentColor",Lt=ie(te,Ge,ft,1.5);Lt?(_.appendChild(Lt),_.style.color=ft):(_.textContent="\u{1F3A4}",_.style.color=ft),St?_.style.backgroundColor=St:_.classList.add("tvw-bg-cw-primary"),ze?_.style.color=ze:!ze&&!v&&_.classList.add("tvw-text-white"),k.borderWidth&&(_.style.borderWidth=k.borderWidth,_.style.borderStyle="solid"),k.borderColor&&(_.style.borderColor=k.borderColor),k.paddingX&&(_.style.paddingLeft=k.paddingX,_.style.paddingRight=k.paddingX),k.paddingY&&(_.style.paddingTop=k.paddingY,_.style.paddingBottom=k.paddingY),ne.appendChild(_);let Ht=(Re=k.tooltipText)!=null?Re:"Start voice recognition";if(((Xe=k.showTooltip)!=null?Xe:!1)&&Ht){let Kt=g("div","tvw-send-button-tooltip");Kt.textContent=Ht,ne.appendChild(Kt)}}let V=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},J=V.enabled===!0,L=null,q=null,Z=null,de=null;if(J){de=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),de.style.display="none",Z=g("input"),Z.type="file",Z.accept=((gt=V.allowedTypes)!=null?gt:Yt).join(","),Z.multiple=((Pt=V.maxFiles)!=null?Pt:4)>1,Z.style.display="none",Z.setAttribute("aria-label","Attach files"),q=g("div","tvw-send-button-wrapper"),L=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),L.type="button",L.setAttribute("aria-label",(Fe=V.buttonTooltipText)!=null?Fe:"Attach file");let te=(st=V.buttonIconName)!=null?st:"paperclip",we=A,Ge=parseFloat(we)||40,St=Math.round(Ge*.6);L.style.width=we,L.style.height=we,L.style.minWidth=we,L.style.minHeight=we,L.style.fontSize="18px",L.style.lineHeight="1",L.style.backgroundColor="transparent",L.style.color="var(--cw-primary, #111827)",L.style.border="none",L.style.borderRadius="6px",L.style.transition="background-color 0.15s ease",L.addEventListener("mouseenter",()=>{L.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),L.addEventListener("mouseleave",()=>{L.style.backgroundColor="transparent"});let ze=ie(te,St,"currentColor",1.5);ze?L.appendChild(ze):L.textContent="\u{1F4CE}",L.addEventListener("click",Ht=>{Ht.preventDefault(),Z==null||Z.click()}),q.appendChild(L);let ft=(kt=V.buttonTooltipText)!=null?kt:"Attach file",Lt=g("div","tvw-send-button-tooltip");Lt.textContent=ft,q.appendChild(Lt)}r.addEventListener("click",te=>{te.target!==C&&te.target!==N&&te.target!==_&&te.target!==ne&&te.target!==L&&te.target!==q&&s.focus()}),de&&(de.style.gap="8px",r.append(de)),Z&&r.append(Z),r.append(s);let qe=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Ct=g("div","tvw-flex tvw-items-center tvw-gap-2");q&&Ct.append(q);let ee=g("div","tvw-flex tvw-items-center tvw-gap-1");ne&&ee.append(ne),ee.append(N),qe.append(Ct,ee),r.append(qe);let j=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),at=(mt=n==null?void 0:n.statusIndicator)!=null?mt:{},xt=(ht=at.visible)!=null?ht:!0;return j.style.display=xt?"":"none",j.textContent=(P=at.idleText)!=null?P:"Online",o.append(t,r,j),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:N,micButton:_,micButtonWrapper:ne,statusText:j,attachmentButton:L,attachmentButtonWrapper:q,attachmentInput:Z,attachmentPreviewsContainer:de,actionsRow:qe,leftActions:Ct,rightActions:ee}};var si=e=>{var d,u,f,p,m,w,h;if(!((u=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?u:!0)){let R=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),M=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(p=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?p:"100%";return R.style.width=y,M.style.width="100%",R.appendChild(M),{wrapper:R,panel:M}}let o=(m=e==null?void 0:e.launcher)!=null?m:{},t=o.position&&Bt[o.position]?Bt[o.position]:Bt["bottom-right"],r=g("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(h=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?h:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,r.appendChild(s),{wrapper:r,panel:s}},oi=(e,n=!0)=>{var w,h,R,M,y,A,B;let o=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=e==null?void 0:e.layout)==null?void 0:w.header,r=((h=e==null?void 0:e.layout)==null?void 0:h.showHeader)!==!1,s=t?ln(e,t,{showClose:n}):Ut({config:e,showClose:n}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(M=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?M:"Hello \u{1F44B}";let u=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(A=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?A:"Ask anything about your account or products.",a.append(d,u);let f=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let p=dn({config:e}),m=((B=e==null?void 0:e.layout)==null?void 0:B.showFooter)!==!1;return r?en(o,s,e):(s.header.style.display="none",en(o,s,e)),o.append(i),m||(p.footer.style.display="none"),o.append(p.footer),{container:o,body:i,messagesWrapper:f,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.statusText,introTitle:d,introSubtitle:u,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:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions}};var Hn=()=>{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 o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.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 r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",e.appendChild(n),e.appendChild(o),e.appendChild(t),e.appendChild(r),e},Xi=(e,n)=>{let o=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=g("img");r.src=t,r.alt=n==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=n==="user"?"U":"A",o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},ri=(e,n)=>{let o=g("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?o.textContent=n.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Gi=(e,n="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.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:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.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 o},Ss=(e,n,o)=>{var h,R,M,y,A,B;let t=(h=n.showCopy)!=null?h:!0,r=(R=n.showUpvote)!=null?R:!0,s=(M=n.showDownvote)!=null?M:!0,i=(y=n.visibility)!=null?y:"hover",a=(A=n.align)!=null?A:"right",d=(B=n.layout)!=null?B:"pill-inside",u={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],p=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=null,w=(v,N,C,k)=>{let z=document.createElement("button");z.className="tvw-message-action-btn",z.setAttribute("aria-label",N),z.setAttribute("title",N),k&&z.setAttribute("data-action",k);let _=ie(v,14,"currentColor",2);return _&&z.appendChild(_),z.addEventListener("click",ne=>{ne.preventDefault(),ne.stopPropagation(),C()}),z};if(t){let v=w("copy","Copy message",()=>{let N=e.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let C=ie("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=ie("copy",14,"currentColor",2);k&&(v.innerHTML="",v.appendChild(k))},2e3)}).catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",C)}),o!=null&&o.onCopy&&o.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");p.appendChild(v)}if(r){let v=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=p.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),m="upvote",v.classList.add("tvw-message-action-active");let k={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"upvote");p.appendChild(v)}if(s){let v=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=p.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),m="downvote",v.classList.add("tvw-message-action-active");let k={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"downvote");p.appendChild(v)}return p},cn=(e,n,o,t,r)=>{var B,v,N,C,k;let s=o!=null?o:{},i=(B=s.layout)!=null?B:"bubble",a=s.avatar,d=s.timestamp,u=(v=a==null?void 0:a.show)!=null?v:!1,f=(N=d==null?void 0:d.show)!=null?N:!1,p=(C=a==null?void 0:a.position)!=null?C:"left",m=(k=d==null?void 0:d.position)!=null?k:"below",w=Gi(e.role,i),h=g("div",w.join(" "));h.id=`bubble-${e.id}`,h.setAttribute("data-message-id",e.id);let R=document.createElement("div");if(R.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),f&&m==="inline"&&e.createdAt){let z=ri(e,d);z.classList.add("tvw-ml-2","tvw-inline"),R.appendChild(z)}if(h.appendChild(R),f&&m==="below"&&e.createdAt){let z=ri(e,d);z.classList.add("tvw-mt-1"),h.appendChild(z)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let z=Hn();h.appendChild(z)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let z=Ss(e,t,r);h.appendChild(z)}if(!u||e.role==="system")return h;let y=g("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),A=Xi(a,e.role);return p==="right"||p==="left"&&e.role==="user"?y.append(h,A):y.append(A,h),h.classList.remove("tvw-max-w-[85%]"),h.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},ii=(e,n,o,t,r)=>{let s=o!=null?o:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):cn(e,n,o,t,r)};var un=new Set,ai=(e,n)=>{let o=un.has(e),t=n.querySelector('button[data-expand-header="true"]'),r=n.querySelector(".tvw-border-t");if(!t||!r)return;t.setAttribute("aria-expanded",o?"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(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},As=e=>{let n=e.reasoning,o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let t=un.has(e.id),r=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");r.type="button",r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("data-expand-header","true"),r.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=$r(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),f=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let p=g("div","tvw-flex tvw-items-center tvw-ml-auto");p.append(d),r.append(s,p);let m=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let w=n.chunks.join(""),h=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return h.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(h),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),o.append(r,m),o};var pn=new Set,li=(e,n,o)=>{var u;let t=pn.has(e),r=(u=o==null?void 0:o.toolCall)!=null?u:{},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 f=r.toggleTextColor||r.headerTextColor||"currentColor",p=ie(t?"chevron-up":"chevron-down",16,f,2);p?d.appendChild(p):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Ts=(e,n)=>{var R;let o=e.toolCall,t=(R=n==null?void 0:n.toolCall)!=null?R:{},r=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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!o)return r;let s=pn.has(e.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),d=g("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Or(o),a.appendChild(d);let u=g("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",p=ie(s?"chevron-up":"chevron-down",16,f,2);p?u.appendChild(p):u.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(a,m);let w=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",t.contentBackgroundColor&&(w.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(w.style.color=t.contentTextColor),t.contentPaddingX&&(w.style.paddingLeft=t.contentPaddingX,w.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(w.style.paddingTop=t.contentPaddingY,w.style.paddingBottom=t.contentPaddingY),o.name){let M=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?M.style.color=t.contentTextColor:t.headerTextColor&&(M.style.color=t.headerTextColor),M.textContent=o.name,w.appendChild(M)}if(o.args!==void 0){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=ws(o.args),M.append(y,A),w.appendChild(M)}if(o.chunks&&o.chunks.length){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=o.chunks.join(`
|
|
16
|
+
`),M.append(y,A),w.appendChild(M)}if(o.status==="complete"&&o.result!==void 0){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=ws(o.result),M.append(y,A),w.appendChild(M)}if(o.status==="complete"&&typeof o.duration=="number"){let M=g("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(M.style.color=t.contentTextColor),M.textContent=`Duration: ${o.duration}ms`,w.appendChild(M)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let M=t.toggleTextColor||t.headerTextColor||"currentColor",y=ie(s?"chevron-up":"chevron-down",16,M,2);y?u.appendChild(y):u.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var di=e=>{let n=[];return{buttons:n,render:(t,r,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(w=>w.role==="user"))return;let f=document.createDocumentFragment(),p=r?r.isStreaming():!1,m=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'}};t.forEach(w=>{let h=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");h.type="button",h.textContent=w,h.disabled=p,a!=null&&a.fontFamily&&(h.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(h.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(h.style.paddingLeft=a.paddingX,h.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(h.style.paddingTop=a.paddingY,h.style.paddingBottom=a.paddingY),h.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(w))}),f.appendChild(h),n.push(h)}),e.appendChild(f)}}};var ci={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"}},Ms=(e,n,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var h,R,M;if(s.dataset.enhanced==="true")return;let i=(h=s.dataset.tvForm)!=null?h:"init";s.dataset.enhanced="true";let a=(R=ci[i])!=null?R:ci.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=g("div","tvw-space-y-1"),u=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=a.title,d.appendChild(u),a.description){let y=g("p","tvw-text-sm tvw-text-cw-muted");y.textContent=a.description,d.appendChild(y)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(y=>{var C,k;let A=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");A.htmlFor=`${n.id}-${i}-${y.name}`;let B=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");B.textContent=y.label,A.appendChild(B);let v=(C=y.type)!=null?C:"text",N;v==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=v),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}-${y.name}`,N.name=y.name,N.placeholder=(k=y.placeholder)!=null?k:"",y.required&&(N.required=!0),A.appendChild(N),f.appendChild(A)});let p=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),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=(M=a.submitLabel)!=null?M:"Submit",p.appendChild(m),p.appendChild(w),f.appendChild(p),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var N,C;y.preventDefault();let A=(N=o.formEndpoint)!=null?N:"/form",B=new FormData(f),v={};B.forEach((k,z)=>{v[z]=k}),v.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let k=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let z=await k.json();m.textContent=(C=z.message)!=null?C:"Thanks! We'll be in touch soon.",z.success&&z.nextPrompt&&await t.sendMessage(String(z.nextPrompt))}catch(k){m.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Es=class{constructor(){this.plugins=new Map}register(n){var o;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(o=n.onRegister)==null||o.call(n)}unregister(n){var t;let o=this.plugins.get(n);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=n.priority)!=null?r:0)})}getForInstance(n){let o=this.getAll();if(!n||n.length===0)return o;let t=new Set(n.map(s=>s.id));return[...o.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 o;return(o=n.onUnregister)==null?void 0:o.call(n)}),this.plugins.clear()}},In=new Es;var Ws={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"},ks={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"},Ie={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ws,darkTheme:ks,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 ts(e){var n,o,t,r,s,i,a,d,u,f,p,m,w,h,R,M,y,A,B;return e?{...Ie,...e,theme:{...Ie.theme,...e.theme},darkTheme:{...Ie.darkTheme,...e.darkTheme},launcher:{...Ie.launcher,...e.launcher,clearChat:{...(n=Ie.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Ie.copy,...e.copy},sendButton:{...Ie.sendButton,...e.sendButton},statusIndicator:{...Ie.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ie.voiceRecognition,...e.voiceRecognition},features:{...Ie.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Ie.suggestionChips,suggestionChipsConfig:{...Ie.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ie.layout,...e.layout,header:{...(r=Ie.layout)==null?void 0:r.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Ie.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(u=(d=Ie.layout)==null?void 0:d.messages)==null?void 0:u.avatar,...(p=(f=e.layout)==null?void 0:f.messages)==null?void 0:p.avatar},timestamp:{...(w=(m=Ie.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(R=(h=e.layout)==null?void 0:h.messages)==null?void 0:R.timestamp}},slots:{...(M=Ie.layout)==null?void 0:M.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Ie.markdown,...e.markdown,options:{...(A=Ie.markdown)==null?void 0:A.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...Ie.messageActions,...e.messageActions}}:Ie}var ui=()=>{let e=new Map,n=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=e.get(r))==null||i.delete(s)};return{on:n,off:o,emit:(r,s)=>{var i;(i=e.get(r))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Qi=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Zi=e=>{let n=e.trim(),o=n.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<n.length;r+=1){let s=n[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(o,r+1)}return null},Bn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Qi(e),o=Zi(n);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Ls=e=>typeof e=="string"?e:e==null?"":String(e),tn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ls(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Ls(o.element);if(t&&((r=n.document)!=null&&r.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:Ls(o.text)}}},pi=e=>Array.isArray(e)?e.map(n=>String(n)):[],Rn=e=>{let n=new Set(pi(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(pi(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((u,f)=>u||(f==null?void 0:f({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 u of e.handlers)if(u)try{let f=()=>{e.emit("action:resubmit",d)},p=u(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:f});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var ea=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}},ta=e=>e.map(n=>({...n,streaming:!1})),ns=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?ea(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?ta(o.messages):void 0};t.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=n();if(o)try{o.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Ps=class{constructor(){this.components=new Map}register(n,o){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,o)}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(([o,t])=>{this.register(o,t)})}},gn=new Ps;var mn=require("partial-json");function na(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function sa(e,n){if(!na(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:n}}function ss(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e;try{let r=(0,mn.parse)(o,mn.STR|mn.OBJ),s=sa(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function gi(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function os(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=gn.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:o,updateProps:a=>{r&&r(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function mi(){let e=ss();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rs(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 is(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 oa=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function as(e){let{onSubmit:n,onDismiss:o,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:u=oa}=e,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let h=document.createElement("h3");h.className="tvw-feedback-title",h.textContent=t,w.appendChild(h);let R=document.createElement("p");R.className="tvw-feedback-subtitle",R.textContent=r,w.appendChild(R),m.appendChild(w);let M=document.createElement("div");M.className="tvw-feedback-rating tvw-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let C=1;C<=5;C++){let k=document.createElement("button");k.type="button",k.className="tvw-feedback-rating-btn tvw-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),k.title=u[C-1],k.dataset.rating=String(C),k.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
|
-
`,k.addEventListener("click",()=>{p=C,y.forEach((z,_)=>{let ne=_<C;z.classList.toggle("selected",ne),z.setAttribute("aria-checked",_===C-1?"true":"false")})}),y.push(k),M.appendChild(k)}m.appendChild(M);let A=null;if(d){let C=document.createElement("div");C.className="tvw-feedback-comment-container",A=document.createElement("textarea"),A.className="tvw-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),C.appendChild(A),m.appendChild(C)}let I=document.createElement("div");I.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=a,v.addEventListener("click",()=>{o==null||o(),f.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(p===null){M.classList.add("tvw-feedback-shake"),setTimeout(()=>M.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let C=(A==null?void 0:A.value.trim())||void 0;await n(p,C),f.remove()}catch(C){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(v),I.appendChild(N),m.appendChild(I),f.appendChild(m),f}function ls(e){let{onSubmit:n,onDismiss:o,title:t="How likely are you to recommend us?",subtitle:r="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:u="Not likely",highLabel:f="Very likely"}=e,p=document.createElement("div");p.className="tvw-feedback-container tvw-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let R=document.createElement("h3");R.className="tvw-feedback-title",R.textContent=t,h.appendChild(R);let M=document.createElement("p");M.className="tvw-feedback-subtitle",M.textContent=r,h.appendChild(M),w.appendChild(h);let y=document.createElement("div");y.className="tvw-feedback-rating tvw-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="tvw-feedback-labels";let I=document.createElement("span");I.className="tvw-feedback-label-low",I.textContent=u;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,A.appendChild(I),A.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let C=[];for(let re=0;re<=10;re++){let V=document.createElement("button");V.type="button",V.className="tvw-feedback-rating-btn tvw-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${re} out of 10`),V.textContent=String(re),V.dataset.rating=String(re),re<=6?V.classList.add("tvw-feedback-detractor"):re<=8?V.classList.add("tvw-feedback-passive"):V.classList.add("tvw-feedback-promoter"),V.addEventListener("click",()=>{m=re,C.forEach((J,L)=>{J.classList.toggle("selected",L===re),J.setAttribute("aria-checked",L===re?"true":"false")})}),C.push(V),N.appendChild(V)}y.appendChild(A),y.appendChild(N),w.appendChild(y);let k=null;if(d){let re=document.createElement("div");re.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"),re.appendChild(k),w.appendChild(re)}let z=document.createElement("div");z.className="tvw-feedback-actions";let _=document.createElement("button");_.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-skip",_.textContent=a,_.addEventListener("click",()=>{o==null||o(),p.remove()});let ne=document.createElement("button");return ne.type="button",ne.className="tvw-feedback-btn tvw-feedback-btn-submit",ne.textContent=i,ne.addEventListener("click",async()=>{if(m===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let re=(k==null?void 0:k.value.trim())||void 0;await n(m,re),p.remove()}catch(re){ne.disabled=!1,ne.textContent=i,console.error("[NPS Feedback] Failed to submit:",re)}}),z.appendChild(_),z.appendChild(ne),w.appendChild(z),p.appendChild(w),p}var hn="persona-chat-history",ra=30*1e3,Hs=e=>!e||typeof e!="object"?{}:{...e},hi=e=>e.map(n=>({...n,streaming:!1})),fi=(e,n,o)=>{let t=e!=null&&e.markdown?kn(e.markdown):null;return r=>{var a,d,u;let s=(a=r.text)!=null?a:"",i=(d=r.message.rawContent)!=null?d:null;if(n){let f=n.process({text:s,raw:i!=null?i:s,message:r.message,streaming:r.streaming});f!==null&&(s=f.text,f.persist||(r.message.__skipPersist=!0),f.resubmit&&!r.streaming&&o&&o())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...r,text:s,raw:(u=i!=null?i:r.text)!=null?u:""}):t?t(s):qn(s)}},ds=(e,n,o)=>{var Os,Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs,Gs,Qs,Zs,eo;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=ts(n),r=Bn.getForInstance(t.plugins);t.components&&gn.registerAll(t.components);let s=ui(),i=(Os=t.storageAdapter)!=null?Os:ns(),a={},d=null;if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l;else if(l){let c=l;c.metadata&&(a=Hs(c.metadata)),(Ns=c.messages)!=null&&Ns.length&&(t={...t,initialMessages:c.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let u=()=>a,f=l=>{var T;a=(T=l({...a}))!=null?T:{},le()},p=t.actionParsers&&t.actionParsers.length?t.actionParsers:[In],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[tn.message,tn.messageAndClick],w=Rn({parsers:p,handlers:m,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Ds=(js=t.launcher)==null?void 0:js.enabled)!=null?Ds:!0,R=(qs=(_s=t.launcher)==null?void 0:_s.autoExpand)!=null?qs:!1,M=R,y=h,A=(zs=(Us=t.layout)==null?void 0:Us.header)==null?void 0:zs.layout,I=h?R:!0,v=!1,N=null,C=()=>{v=!0,N&&clearTimeout(N),N=setTimeout(()=>{v&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),v=!1)},1e4)},k=fi(t,w,C),z=(Ys=(Js=t.features)==null?void 0:Js.showReasoning)!=null?Ys:!0,_=(Vs=(Ks=t.features)==null?void 0:Ks.showToolCalls)!=null?Vs:!0,ne={onCopy:l=>{var c,T;s.emit("message:copy",l),P!=null&&P.isClientTokenMode()&&P.submitMessageFeedback(l.id,"copy").catch(H=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",H)}),(T=(c=t.messageActions)==null?void 0:c.onCopy)==null||T.call(c,l)},onFeedback:l=>{var c,T;s.emit("message:feedback",l),P!=null&&P.isClientTokenMode()&&P.submitMessageFeedback(l.messageId,l.type).catch(H=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",H)}),(T=(c=t.messageActions)==null?void 0:c.onFeedback)==null||T.call(c,l)}},re=(Xs=t.statusIndicator)!=null?Xs:{},V=l=>{var c,T,H,b;return l==="idle"?(c=re.idleText)!=null?c:pt.idle:l==="connecting"?(T=re.connectingText)!=null?T:pt.connecting:l==="connected"?(H=re.connectedText)!=null?H:pt.connected:l==="error"?(b=re.errorText)!=null?b:pt.error:pt[l]},{wrapper:J,panel:L}=si(t),q=oi(t,h),{container:Z,body:de,messagesWrapper:qe,suggestions:Ct,textarea:ee,sendButton:j,sendButtonWrapper:at,composerForm:xt,statusText:vt,introTitle:Rt,introSubtitle:Ft,closeButton:D,iconHolder:fe,headerTitle:lt,headerSubtitle:dt,header:Ve,footer:ct,actionsRow:jt,leftActions:$t,rightActions:Ot}=q,F=q.micButton,Ue=q.micButtonWrapper,ge=q.attachmentButton,tt=q.attachmentButtonWrapper,me=q.attachmentInput,nt=q.attachmentPreviewsContainer,U=null;(Gs=t.attachments)!=null&&Gs.enabled&&me&&nt&&(U=Zt.fromConfig(t.attachments),U.setPreviewsContainer(nt),me.addEventListener("change",l=>{let c=l.target;U==null||U.handleFileSelect(c.files),c.value=""}));let Re=r.find(l=>l.renderHeader);if(Re!=null&&Re.renderHeader){let l=Re.renderHeader({config:t,defaultRenderer:()=>{let c=Ut({config:t,showClose:h});return en(Z,c,t),c.header},onClose:()=>S(!1,"user")});if(l){let c=Z.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),Ve=l)}}let Xe=r.find(l=>l.renderComposer);if(Xe!=null&&Xe.renderComposer){let l=Xe.renderComposer({config:t,defaultRenderer:()=>dn({config:t}).footer,onSubmit:c=>{P&&!P.isStreaming()&&P.sendMessage(c)},disabled:!1});l&&(ct.replaceWith(l),ct=l)}(()=>{var H,b;let l=(b=(H=t.layout)==null?void 0:H.slots)!=null?b:{},c=X=>{switch(X){case"body-top":return Z.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return qe;case"footer-top":return Ct;case"composer":return xt;case"footer-bottom":return vt;default:return null}},T=(X,ce)=>{var W;switch(X){case"header-left":case"header-center":case"header-right":if(X==="header-left")Ve.insertBefore(ce,Ve.firstChild);else if(X==="header-right")Ve.appendChild(ce);else{let K=Ve.querySelector(".tvw-flex-col");K?(W=K.parentNode)==null||W.insertBefore(ce,K.nextSibling):Ve.appendChild(ce)}break;case"body-top":{let K=de.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");K?K.replaceWith(ce):de.insertBefore(ce,de.firstChild);break}case"body-bottom":de.appendChild(ce);break;case"footer-top":Ct.replaceWith(ce);break;case"footer-bottom":vt.replaceWith(ce);break;default:break}};for(let[X,ce]of Object.entries(l))if(ce)try{let W=ce({config:t,defaultContent:()=>c(X)});W&&T(X,W)}catch(W){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${X}":`,W)}})();let gt=l=>{let T=l.target.closest('button[data-expand-header="true"]');if(!T)return;let H=T.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!H)return;let b=H.getAttribute("data-message-id");if(!b)return;let X=T.getAttribute("data-bubble-type");X==="reasoning"?(un.has(b)?un.delete(b):un.add(b),ai(b,H)):X==="tool"&&(pn.has(b)?pn.delete(b):pn.add(b),li(b,H,t))};qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),gt(l))}),qe.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),gt(l))}),L.appendChild(Z),e.appendChild(J);let Pt=()=>{var ue,Je,Ye,rt,Tt,Q,Me,Vt,Xt,On,Nn,hs,Ke,jn,Cn,xn;let l=(Je=(ue=t.launcher)==null?void 0:ue.sidebarMode)!=null?Je:!1,c=l||((rt=(Ye=t.launcher)==null?void 0:Ye.fullHeight)!=null?rt:!1),T=(Tt=t.theme)!=null?Tt:{},H=(Me=(Q=t.launcher)==null?void 0:Q.position)!=null?Me:"bottom-left",b=H==="bottom-left"||H==="top-left",X=l?"none":"1px solid var(--tvw-cw-border)",ce=l?b?"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)",W=l?"0":"16px",K=(Vt=T.panelBorder)!=null?Vt:X,G=(Xt=T.panelShadow)!=null?Xt:ce,Ce=(On=T.panelBorderRadius)!=null?On:W;e.style.cssText="",J.style.cssText="",L.style.cssText="",Z.style.cssText="",de.style.cssText="",ct.style.cssText="";let $=(hs=(Nn=t==null?void 0:t.launcher)==null?void 0:Nn.width)!=null?hs:t==null?void 0:t.launcherWidth,je=$!=null?$:"min(400px, calc(100vw - 24px))";l||(L.style.width=je,L.style.maxWidth=je),L.style.boxShadow=G,L.style.borderRadius=Ce,Z.style.border=K,Z.style.borderRadius=Ce;let Se=((Ke=t.launcher)==null?void 0:Ke.enabled)===!1;if(c&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.height="100%",Se&&(J.style.overflow="hidden"),L.style.display="flex",L.style.flexDirection="column",L.style.flex="1 1 0%",L.style.minHeight="0",L.style.maxHeight="100%",L.style.height="100%",L.style.overflow="hidden",Z.style.display="flex",Z.style.flexDirection="column",Z.style.flex="1 1 0%",Z.style.minHeight="0",Z.style.maxHeight="100%",Z.style.overflow="hidden",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.overflowY="auto",ct.style.flexShrink="0"),J.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&&!Se&&((jn=It[H])!=null?jn:It["bottom-right"]).split(" ").forEach(Sn=>J.classList.add(Sn)),l){let Jt=(xn=(Cn=t.launcher)==null?void 0:Cn.sidebarWidth)!=null?xn:"420px";J.style.cssText=`
|
|
20
|
+
`,k.addEventListener("click",()=>{p=C,y.forEach((z,_)=>{let ne=_<C;z.classList.toggle("selected",ne),z.setAttribute("aria-checked",_===C-1?"true":"false")})}),y.push(k),M.appendChild(k)}m.appendChild(M);let A=null;if(d){let C=document.createElement("div");C.className="tvw-feedback-comment-container",A=document.createElement("textarea"),A.className="tvw-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),C.appendChild(A),m.appendChild(C)}let B=document.createElement("div");B.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=a,v.addEventListener("click",()=>{o==null||o(),f.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(p===null){M.classList.add("tvw-feedback-shake"),setTimeout(()=>M.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let C=(A==null?void 0:A.value.trim())||void 0;await n(p,C),f.remove()}catch(C){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),B.appendChild(v),B.appendChild(N),m.appendChild(B),f.appendChild(m),f}function ls(e){let{onSubmit:n,onDismiss:o,title:t="How likely are you to recommend us?",subtitle:r="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:u="Not likely",highLabel:f="Very likely"}=e,p=document.createElement("div");p.className="tvw-feedback-container tvw-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let R=document.createElement("h3");R.className="tvw-feedback-title",R.textContent=t,h.appendChild(R);let M=document.createElement("p");M.className="tvw-feedback-subtitle",M.textContent=r,h.appendChild(M),w.appendChild(h);let y=document.createElement("div");y.className="tvw-feedback-rating tvw-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="tvw-feedback-labels";let B=document.createElement("span");B.className="tvw-feedback-label-low",B.textContent=u;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,A.appendChild(B),A.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let C=[];for(let re=0;re<=10;re++){let V=document.createElement("button");V.type="button",V.className="tvw-feedback-rating-btn tvw-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${re} out of 10`),V.textContent=String(re),V.dataset.rating=String(re),re<=6?V.classList.add("tvw-feedback-detractor"):re<=8?V.classList.add("tvw-feedback-passive"):V.classList.add("tvw-feedback-promoter"),V.addEventListener("click",()=>{m=re,C.forEach((J,L)=>{J.classList.toggle("selected",L===re),J.setAttribute("aria-checked",L===re?"true":"false")})}),C.push(V),N.appendChild(V)}y.appendChild(A),y.appendChild(N),w.appendChild(y);let k=null;if(d){let re=document.createElement("div");re.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"),re.appendChild(k),w.appendChild(re)}let z=document.createElement("div");z.className="tvw-feedback-actions";let _=document.createElement("button");_.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-skip",_.textContent=a,_.addEventListener("click",()=>{o==null||o(),p.remove()});let ne=document.createElement("button");return ne.type="button",ne.className="tvw-feedback-btn tvw-feedback-btn-submit",ne.textContent=i,ne.addEventListener("click",async()=>{if(m===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let re=(k==null?void 0:k.value.trim())||void 0;await n(m,re),p.remove()}catch(re){ne.disabled=!1,ne.textContent=i,console.error("[NPS Feedback] Failed to submit:",re)}}),z.appendChild(_),z.appendChild(ne),w.appendChild(z),p.appendChild(w),p}var hn="persona-chat-history",ra=30*1e3,Hs=e=>!e||typeof e!="object"?{}:{...e},hi=e=>e.map(n=>({...n,streaming:!1})),fi=(e,n,o)=>{let t=e!=null&&e.markdown?kn(e.markdown):null;return r=>{var a,d,u;let s=(a=r.text)!=null?a:"",i=(d=r.message.rawContent)!=null?d:null;if(n){let f=n.process({text:s,raw:i!=null?i:s,message:r.message,streaming:r.streaming});f!==null&&(s=f.text,f.persist||(r.message.__skipPersist=!0),f.resubmit&&!r.streaming&&o&&o())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...r,text:s,raw:(u=i!=null?i:r.text)!=null?u:""}):t?t(s):qn(s)}},ds=(e,n,o)=>{var Os,Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs,Gs,Qs,Zs,eo;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=ts(n),r=In.getForInstance(t.plugins);t.components&&gn.registerAll(t.components);let s=ui(),i=(Os=t.storageAdapter)!=null?Os:ns(),a={},d=null;if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l;else if(l){let c=l;c.metadata&&(a=Hs(c.metadata)),(Ns=c.messages)!=null&&Ns.length&&(t={...t,initialMessages:c.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let u=()=>a,f=l=>{var T;a=(T=l({...a}))!=null?T:{},le()},p=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Bn],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[tn.message,tn.messageAndClick],w=Rn({parsers:p,handlers:m,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Ds=(js=t.launcher)==null?void 0:js.enabled)!=null?Ds:!0,R=(qs=(_s=t.launcher)==null?void 0:_s.autoExpand)!=null?qs:!1,M=R,y=h,A=(zs=(Us=t.layout)==null?void 0:Us.header)==null?void 0:zs.layout,B=h?R:!0,v=!1,N=null,C=()=>{v=!0,N&&clearTimeout(N),N=setTimeout(()=>{v&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),v=!1)},1e4)},k=fi(t,w,C),z=(Ys=(Js=t.features)==null?void 0:Js.showReasoning)!=null?Ys:!0,_=(Vs=(Ks=t.features)==null?void 0:Ks.showToolCalls)!=null?Vs:!0,ne={onCopy:l=>{var c,T;s.emit("message:copy",l),P!=null&&P.isClientTokenMode()&&P.submitMessageFeedback(l.id,"copy").catch(H=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",H)}),(T=(c=t.messageActions)==null?void 0:c.onCopy)==null||T.call(c,l)},onFeedback:l=>{var c,T;s.emit("message:feedback",l),P!=null&&P.isClientTokenMode()&&P.submitMessageFeedback(l.messageId,l.type).catch(H=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",H)}),(T=(c=t.messageActions)==null?void 0:c.onFeedback)==null||T.call(c,l)}},re=(Xs=t.statusIndicator)!=null?Xs:{},V=l=>{var c,T,H,b;return l==="idle"?(c=re.idleText)!=null?c:pt.idle:l==="connecting"?(T=re.connectingText)!=null?T:pt.connecting:l==="connected"?(H=re.connectedText)!=null?H:pt.connected:l==="error"?(b=re.errorText)!=null?b:pt.error:pt[l]},{wrapper:J,panel:L}=si(t),q=oi(t,h),{container:Z,body:de,messagesWrapper:qe,suggestions:Ct,textarea:ee,sendButton:j,sendButtonWrapper:at,composerForm:xt,statusText:vt,introTitle:Rt,introSubtitle:Ft,closeButton:D,iconHolder:fe,headerTitle:lt,headerSubtitle:dt,header:Ve,footer:ct,actionsRow:jt,leftActions:$t,rightActions:Ot}=q,F=q.micButton,Ue=q.micButtonWrapper,ge=q.attachmentButton,tt=q.attachmentButtonWrapper,me=q.attachmentInput,nt=q.attachmentPreviewsContainer,U=null;(Gs=t.attachments)!=null&&Gs.enabled&&me&&nt&&(U=Zt.fromConfig(t.attachments),U.setPreviewsContainer(nt),me.addEventListener("change",l=>{let c=l.target;U==null||U.handleFileSelect(c.files),c.value=""}));let Re=r.find(l=>l.renderHeader);if(Re!=null&&Re.renderHeader){let l=Re.renderHeader({config:t,defaultRenderer:()=>{let c=Ut({config:t,showClose:h});return en(Z,c,t),c.header},onClose:()=>S(!1,"user")});if(l){let c=Z.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),Ve=l)}}let Xe=r.find(l=>l.renderComposer);if(Xe!=null&&Xe.renderComposer){let l=Xe.renderComposer({config:t,defaultRenderer:()=>dn({config:t}).footer,onSubmit:c=>{P&&!P.isStreaming()&&P.sendMessage(c)},disabled:!1});l&&(ct.replaceWith(l),ct=l)}(()=>{var H,b;let l=(b=(H=t.layout)==null?void 0:H.slots)!=null?b:{},c=X=>{switch(X){case"body-top":return Z.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return qe;case"footer-top":return Ct;case"composer":return xt;case"footer-bottom":return vt;default:return null}},T=(X,ce)=>{var W;switch(X){case"header-left":case"header-center":case"header-right":if(X==="header-left")Ve.insertBefore(ce,Ve.firstChild);else if(X==="header-right")Ve.appendChild(ce);else{let K=Ve.querySelector(".tvw-flex-col");K?(W=K.parentNode)==null||W.insertBefore(ce,K.nextSibling):Ve.appendChild(ce)}break;case"body-top":{let K=de.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");K?K.replaceWith(ce):de.insertBefore(ce,de.firstChild);break}case"body-bottom":de.appendChild(ce);break;case"footer-top":Ct.replaceWith(ce);break;case"footer-bottom":vt.replaceWith(ce);break;default:break}};for(let[X,ce]of Object.entries(l))if(ce)try{let W=ce({config:t,defaultContent:()=>c(X)});W&&T(X,W)}catch(W){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${X}":`,W)}})();let gt=l=>{let T=l.target.closest('button[data-expand-header="true"]');if(!T)return;let H=T.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!H)return;let b=H.getAttribute("data-message-id");if(!b)return;let X=T.getAttribute("data-bubble-type");X==="reasoning"?(un.has(b)?un.delete(b):un.add(b),ai(b,H)):X==="tool"&&(pn.has(b)?pn.delete(b):pn.add(b),li(b,H,t))};qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),gt(l))}),qe.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),gt(l))}),L.appendChild(Z),e.appendChild(J);let Pt=()=>{var ue,Je,Ye,rt,Tt,Q,Me,Vt,Xt,On,Nn,hs,Ke,jn,Cn,xn;let l=(Je=(ue=t.launcher)==null?void 0:ue.sidebarMode)!=null?Je:!1,c=l||((rt=(Ye=t.launcher)==null?void 0:Ye.fullHeight)!=null?rt:!1),T=(Tt=t.theme)!=null?Tt:{},H=(Me=(Q=t.launcher)==null?void 0:Q.position)!=null?Me:"bottom-left",b=H==="bottom-left"||H==="top-left",X=l?"none":"1px solid var(--tvw-cw-border)",ce=l?b?"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)",W=l?"0":"16px",K=(Vt=T.panelBorder)!=null?Vt:X,G=(Xt=T.panelShadow)!=null?Xt:ce,Ce=(On=T.panelBorderRadius)!=null?On:W;e.style.cssText="",J.style.cssText="",L.style.cssText="",Z.style.cssText="",de.style.cssText="",ct.style.cssText="";let $=(hs=(Nn=t==null?void 0:t.launcher)==null?void 0:Nn.width)!=null?hs:t==null?void 0:t.launcherWidth,je=$!=null?$:"min(400px, calc(100vw - 24px))";l||(L.style.width=je,L.style.maxWidth=je),L.style.boxShadow=G,L.style.borderRadius=Ce,Z.style.border=K,Z.style.borderRadius=Ce;let Se=((Ke=t.launcher)==null?void 0:Ke.enabled)===!1;if(c&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.height="100%",Se&&(J.style.overflow="hidden"),L.style.display="flex",L.style.flexDirection="column",L.style.flex="1 1 0%",L.style.minHeight="0",L.style.maxHeight="100%",L.style.height="100%",L.style.overflow="hidden",Z.style.display="flex",Z.style.flexDirection="column",Z.style.flex="1 1 0%",Z.style.minHeight="0",Z.style.maxHeight="100%",Z.style.overflow="hidden",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.overflowY="auto",ct.style.flexShrink="0"),J.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&&!Se&&((jn=Bt[H])!=null?jn:Bt["bottom-right"]).split(" ").forEach(Sn=>J.classList.add(Sn)),l){let Jt=(xn=(Cn=t.launcher)==null?void 0:Cn.sidebarWidth)!=null?xn:"420px";J.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
top: 0 !important;
|
|
23
23
|
bottom: 0 !important;
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
flex-shrink: 0 !important;
|
|
58
58
|
border-top: none !important;
|
|
59
59
|
padding: 8px 16px 12px 16px !important;
|
|
60
|
-
`}if(!Se){let Jt="max-height: -moz-available !important; max-height: stretch !important;",Sn=l?"":"padding-top: 1.25em !important;";J.style.cssText+=Jt+Sn}};Pt(),Zn(e,t);let Fe=[],st=null,kt=()=>{st&&(st(),st=null),t.colorScheme==="auto"&&(st=ei(()=>{Zn(e,t)}))};kt(),Fe.push(()=>{st&&(st(),st=null)});let mt=di(Ct),ht=null,P,te=!1,we=!0,Ge=0,St=0,ze=null,ft=!1,Lt=0,Ht=!1,fn=125,Kt=2e3,Fn=5,wn=50,sn=new Map,We={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},yn=(Zs=(Qs=t.voiceRecognition)==null?void 0:Qs.autoResume)!=null?Zs:!1,vn=l=>{s.emit("voice:state",{active:We.active,source:l,timestamp:Date.now()})},Dt=()=>{f(l=>({...l,voiceState:{active:We.active,timestamp:Date.now(),manuallyDeactivated:We.manuallyDeactivated}}))},$n=()=>{var H,b;if(((H=t.voiceRecognition)==null?void 0:H.enabled)===!1)return;let l=Hs(a.voiceState),c=!!l.active,T=Number((b=l.timestamp)!=null?b:0);We.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-T<ra&&setTimeout(()=>{We.active||(We.manuallyDeactivated=!1,be("restore"))},1e3)},B=()=>P?hi(P.getMessages()).filter(l=>!l.__skipPersist):[];function le(l){if(!(i!=null&&i.save))return;let T={messages:l?hi(l):P?B():[],metadata:a};try{let H=i.save(T);H instanceof Promise&&H.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)})}catch(H){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)}}let he=(l=!1)=>{if(!we)return;let c=Date.now();ft&&c<Lt&&!l||(ft&&c>=Lt&&(ft=!1),!(!l&&!te)&&(c-St<fn||(St=c,ze&&cancelAnimationFrame(ze),ze=requestAnimationFrame(()=>{ft||!we||(Ht=!0,de.scrollTop=de.scrollHeight,Ge=de.scrollTop,requestAnimationFrame(()=>{Ht=!1}),ze=null)}))))},Ee=null,Ze=()=>J.querySelector("#persona-scroll-container")||de,ot=(l,c=500)=>{let T=l.scrollTop,H=l.clientHeight,b=l.scrollHeight,X=b-T;if(T+H>=b-2||Math.abs(X)<5)return;Ee!==null&&(cancelAnimationFrame(Ee),Ee=null);let W=performance.now(),K=Ce=>1-Math.pow(1-Ce,3),G=Ce=>{let $=l.scrollHeight;$!==b&&(b=$,X=b-T);let je=Ce-W,Se=Math.min(je/c,1),ue=K(Se),Je=T+X*ue;l.scrollTop=Je,Se<1?Ee=requestAnimationFrame(G):(l.scrollTop=l.scrollHeight,Ee=null)};Ee=requestAnimationFrame(G)},$e=l=>{let c=new Map;l.forEach(T=>{let H=sn.get(T.id);c.set(T.id,{streaming:T.streaming,role:T.role}),!H&&T.role==="assistant"&&s.emit("assistant:message",T),T.role==="assistant"&&(H!=null&&H.streaming)&&T.streaming===!1&&s.emit("assistant:complete",T)}),sn.clear(),c.forEach((T,H)=>{sn.set(H,T)})},wt=(l,c,T)=>{let H=document.createElement("div");c.forEach(W=>{var je,Se;let K=null,G=r.find(ue=>!!(W.variant==="reasoning"&&ue.renderReasoning||W.variant==="tool"&&ue.renderToolCall||!W.variant&&ue.renderMessage)),Ce=(je=t.layout)==null?void 0:je.messages;if(G)if(W.variant==="reasoning"&&W.reasoning&&G.renderReasoning){if(!z)return;K=G.renderReasoning({message:W,defaultRenderer:()=>As(W),config:t})}else if(W.variant==="tool"&&W.toolCall&&G.renderToolCall){if(!_)return;K=G.renderToolCall({message:W,defaultRenderer:()=>Ts(W,t),config:t})}else G.renderMessage&&(K=G.renderMessage({message:W,defaultRenderer:()=>{let ue=cn(W,T,Ce,t.messageActions,ne);return W.role!=="user"&&Ms(ue,W,t,P),ue},config:t}));if(!K&&W.role==="assistant"&&!W.variant&&t.enableComponentStreaming!==!1&&rs(W)){let Je=is(W);if(Je){let Ye=os(Je,{config:t,message:W,transform:T});if(Ye){let rt=document.createElement("div");if(rt.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(" "),rt.id=`bubble-${W.id}`,rt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=T({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),rt.appendChild(Tt)}rt.appendChild(Ye),K=rt}}}if(!K)if(W.variant==="reasoning"&&W.reasoning){if(!z)return;K=As(W)}else if(W.variant==="tool"&&W.toolCall){if(!_)return;K=Ts(W,t)}else{let ue=(Se=t.layout)==null?void 0:Se.messages;ue!=null&&ue.renderUserMessage&&W.role==="user"?K=ue.renderUserMessage({message:W,config:t,streaming:!!W.streaming}):ue!=null&&ue.renderAssistantMessage&&W.role==="assistant"?K=ue.renderAssistantMessage({message:W,config:t,streaming:!!W.streaming}):K=cn(W,T,ue,t.messageActions,ne),W.role!=="user"&&K&&Ms(K,W,t,P)}let $=document.createElement("div");$.className="tvw-flex",$.id=`wrapper-${W.id}`,$.setAttribute("data-wrapper-id",W.id),W.role==="user"&&$.classList.add("tvw-justify-end"),$.appendChild(K),H.appendChild($)});let b=c.some(W=>W.role==="assistant"&&W.streaming),X=c[c.length-1],ce=(X==null?void 0:X.role)==="assistant"&&!X.streaming;if(te&&c.some(W=>W.role==="user")&&!b&&!ce){let W=Hn(),K=document.createElement("div");K.className=["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(" "),K.setAttribute("data-typing-indicator","true"),K.appendChild(W);let G=document.createElement("div");G.className="tvw-flex",G.id="wrapper-typing-indicator",G.setAttribute("data-wrapper-id","typing-indicator"),G.appendChild(K),H.appendChild(G)}ni(l,H),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let W=Ze();ot(W)})})},se=()=>{h&&(I?(J.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),L.classList.remove("tvw-scale-95","tvw-opacity-0"),L.classList.add("tvw-scale-100","tvw-opacity-100"),Oe?Oe.element.style.display="none":Ne&&(Ne.style.display="none")):(J.classList.add("tvw-pointer-events-none","tvw-opacity-0"),L.classList.remove("tvw-scale-100","tvw-opacity-100"),L.classList.add("tvw-scale-95","tvw-opacity-0"),Oe?Oe.element.style.display="":Ne&&(Ne.style.display="")))},S=(l,c="user")=>{if(!h||I===l)return;let T=I;I=l,se(),I&&(bn(),he(!0));let H={open:I,source:c,timestamp:Date.now()};I&&!T?s.emit("widget:opened",H):!I&&T&&s.emit("widget:closed",H),s.emit("widget:state",{open:I,launcherEnabled:h,voiceActive:We.active,streaming:P.isStreaming()})},E=l=>{j.disabled=l,F&&(F.disabled=l),mt.buttons.forEach(c=>{c.disabled=l})},Y=()=>{var b,X,ce,W,K,G,Ce,$,je,Se,ue,Je,Ye,rt;Rt.textContent=(X=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?X:"Hello \u{1F44B}",Ft.textContent=(W=(ce=t.copy)==null?void 0:ce.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",ee.placeholder=(G=(K=t.copy)==null?void 0:K.inputPlaceholder)!=null?G:"How can I help...",(($=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?$:!1)||(j.textContent=(Se=(je=t.copy)==null?void 0:je.sendButtonLabel)!=null?Se:"Send");let c=(Je=(ue=t.theme)==null?void 0:ue.inputFontFamily)!=null?Je:"sans-serif",T=(rt=(Ye=t.theme)==null?void 0:Ye.inputFontWeight)!=null?rt:"400",H=Tt=>{switch(Tt){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'}};ee.style.fontFamily=H(c),ee.style.fontWeight=T};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(c=>({...c,session_id:l}))}}),P=new an(t,{onMessagesChanged(l){wt(qe,l,k),P&&(l.some(H=>H.role==="user")?mt.render([],P,ee,l):mt.render(t.suggestionChips,P,ee,l,t.suggestionChipsConfig)),he(!te),$e(l);let c=[...l].reverse().find(T=>T.role==="user");We.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),le(l)},onStatusChanged(l){var H;let c=(H=t.statusIndicator)!=null?H:{},T=b=>{var X,ce,W,K;return b==="idle"?(X=c.idleText)!=null?X:pt.idle:b==="connecting"?(ce=c.connectingText)!=null?ce:pt.connecting:b==="connected"?(W=c.connectedText)!=null?W:pt.connected:b==="error"?(K=c.errorText)!=null?K:pt.error:pt[b]};vt.textContent=T(l)},onStreamingChanged(l){te=l,E(l),P&&wt(qe,P.getMessages(),k),l||he(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=Hs(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&P.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Pe=l=>{var b;l.preventDefault();let c=ee.value.trim(),T=(b=U==null?void 0:U.hasAttachments())!=null?b:!1;if(!c&&!T)return;let H;T&&(H=[],H.push(...U.getContentParts()),c&&H.push(Xn(c))),ee.value="",ee.style.height="auto",P.sendMessage(c,{contentParts:H}),T&&U.clearAttachments()},He=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),j.click())},ke=null,ye=!1,Ie=null,Le=null,ve=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,be=(l="user")=>{var X,ce,W,K;if(ye||P.isStreaming())return;let c=ve();if(!c)return;ke=new c;let H=(ce=((X=t.voiceRecognition)!=null?X:{}).pauseDuration)!=null?ce:2e3;ke.continuous=!0,ke.interimResults=!0,ke.lang="en-US";let b=ee.value;ke.onresult=G=>{let Ce="",$="";for(let Se=0;Se<G.results.length;Se++){let ue=G.results[Se],Je=ue[0].transcript;ue.isFinal?Ce+=Je+" ":$=Je}let je=b+Ce+$;ee.value=je,Ie&&clearTimeout(Ie),(Ce||$)&&(Ie=window.setTimeout(()=>{let Se=ee.value.trim();Se&&ke&&ye&&(Te(),ee.value="",ee.style.height="auto",P.sendMessage(Se,{viaVoice:!0}))},H))},ke.onerror=G=>{G.error!=="no-speech"&&Te()},ke.onend=()=>{if(ye){let G=ee.value.trim();G&&G!==b.trim()&&(ee.value="",ee.style.height="auto",P.sendMessage(G,{viaVoice:!0})),Te()}};try{if(ke.start(),ye=!0,We.active=!0,l!=="system"&&(We.manuallyDeactivated=!1),vn(l),Dt(),F){Le={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let G=(W=t.voiceRecognition)!=null?W:{},Ce=(K=G.recordingBackgroundColor)!=null?K:"#ef4444",$=G.recordingIconColor,je=G.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=Ce,$){F.style.color=$;let Se=F.querySelector("svg");Se&&Se.setAttribute("stroke",$)}je&&(F.style.borderColor=je),F.setAttribute("aria-label","Stop voice recognition")}}catch{Te("system")}},Te=(l="user")=>{if(ye){if(ye=!1,Ie&&(clearTimeout(Ie),Ie=null),ke){try{ke.stop()}catch{}ke=null}if(We.active=!1,vn(l),Dt(),F){if(F.classList.remove("tvw-voice-recording"),Le){F.style.backgroundColor=Le.backgroundColor,F.style.color=Le.color,F.style.borderColor=Le.borderColor;let c=F.querySelector("svg");c&&c.setAttribute("stroke",Le.color||"currentColor"),Le=null}F.setAttribute("aria-label","Start voice recognition")}}},Ae=(l,c)=>{var Je,Ye,rt,Tt,Q,Me,Vt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let H=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");b.type="button",b.setAttribute("aria-label","Start voice recognition");let X=(Je=l==null?void 0:l.iconName)!=null?Je:"mic",ce=(Ye=c==null?void 0:c.size)!=null?Ye:"40px",W=(rt=l==null?void 0:l.iconSize)!=null?rt:ce,K=parseFloat(W)||24,G=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,Ce=(Q=l==null?void 0:l.iconColor)!=null?Q:c==null?void 0:c.textColor;b.style.width=W,b.style.height=W,b.style.minWidth=W,b.style.minHeight=W,b.style.fontSize="18px",b.style.lineHeight="1";let $=Ce||"currentColor",je=ie(X,K,$,1.5);je?(b.appendChild(je),b.style.color=$):(b.textContent="\u{1F3A4}",b.style.color=$),G?b.style.backgroundColor=G:b.classList.add("tvw-bg-cw-primary"),Ce?b.style.color=Ce:!Ce&&!(c!=null&&c.textColor)&&b.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(b.style.borderWidth=l.borderWidth,b.style.borderStyle="solid"),l!=null&&l.borderColor&&(b.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(b.style.paddingLeft=l.paddingX,b.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(b.style.paddingTop=l.paddingY,b.style.paddingBottom=l.paddingY),H.appendChild(b);let Se=(Me=l==null?void 0:l.tooltipText)!=null?Me:"Start voice recognition";if(((Vt=l==null?void 0:l.showTooltip)!=null?Vt:!1)&&Se){let Xt=g("div","tvw-send-button-tooltip");Xt.textContent=Se,H.appendChild(Xt)}return{micButton:b,micButtonWrapper:H}},Qe=()=>{if(ye){let l=ee.value.trim();We.manuallyDeactivated=!0,Dt(),Te("user"),l&&(ee.value="",ee.style.height="auto",P.sendMessage(l))}else We.manuallyDeactivated=!1,Dt(),be("user")};F&&(F.addEventListener("click",Qe),Fe.push(()=>{Te("system"),F&&F.removeEventListener("click",Qe)}));let At=s.on("assistant:complete",()=>{yn&&(We.active||We.manuallyDeactivated||yn==="assistant"&&!We.lastUserMessageWasVoice||setTimeout(()=>{!We.active&&!We.manuallyDeactivated&&be("auto")},600))});Fe.push(At);let Bt=s.on("action:resubmit",()=>{setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)});Fe.push(Bt);let on=()=>{S(!I,"user")},Oe=null,Ne=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>Pn(t,on).element,onToggle:on});c&&(Ne=c)}Ne||(Oe=Pn(t,on))}Oe?e.appendChild(Oe.element):Ne&&e.appendChild(Ne),se(),mt.render(t.suggestionChips,P,ee,void 0,t.suggestionChipsConfig),Y(),E(P.isStreaming()),he(!0),$n();let bn=()=>{var T,H,b,X,ce,W,K,G;let l=(H=(T=t.launcher)==null?void 0:T.sidebarMode)!=null?H:!1,c=l||((X=(b=t.launcher)==null?void 0:b.fullHeight)!=null?X:!1);if(!h){L.style.height="",L.style.width="";return}if(!l){let Ce=(W=(ce=t==null?void 0:t.launcher)==null?void 0:ce.width)!=null?W:t==null?void 0:t.launcherWidth,$=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";L.style.width=$,L.style.maxWidth=$}if(!c){let Ce=window.innerHeight,$=64,je=(G=(K=t.launcher)==null?void 0:K.heightOffset)!=null?G:0,Se=Math.max(200,Ce-$),ue=Math.min(640,Se),Je=Math.max(200,ue-je);L.style.height=`${Je}px`}};bn(),window.addEventListener("resize",bn),Fe.push(()=>window.removeEventListener("resize",bn)),Ge=de.scrollTop;let Fs=()=>{let l=de.scrollTop,c=de.scrollHeight,T=de.clientHeight,H=c-l-T,b=Math.abs(l-Ge);if(Ge=l,!Ht&&!(b<=Fn)){if(!we&&H<wn){ft=!1,we=!0;return}we&&H>wn&&(ft=!0,Lt=Date.now()+Kt,we=!1)}};de.addEventListener("scroll",Fs,{passive:!0}),Fe.push(()=>de.removeEventListener("scroll",Fs)),Fe.push(()=>{ze&&cancelAnimationFrame(ze)});let $s=()=>{D&&(ht&&(D.removeEventListener("click",ht),ht=null),h?(D.style.display="",ht=()=>{I=!1,se()},D.addEventListener("click",ht)):D.style.display="none")};$s(),(()=>{let{clearChatButton:l}=q;l&&l.addEventListener("click",()=>{P.clearMessages();try{localStorage.removeItem(hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hn}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",H)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}a={},w.syncFromMetadata()})})(),xt.addEventListener("submit",Pe),ee.addEventListener("keydown",He),Fe.push(()=>{xt.removeEventListener("submit",Pe),ee.removeEventListener("keydown",He)}),Fe.push(()=>{P.cancel()}),Oe?Fe.push(()=>{Oe==null||Oe.destroy()}):Ne&&Fe.push(()=>{Ne==null||Ne.remove()});let _t={update(l){var to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Mo,Eo,Wo,ko,Lo,Po,Ho,Bo,Io,Ro,Fo,$o,Oo,No,jo,Do,_o,qo,Uo,zo,Jo,Yo,Ko,Vo,Xo,Go,Qo,Zo,er,tr,nr,sr,or,rr,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar,Tr,Mr,Er,Wr,kr;let c=t.toolCall,T=t.colorScheme;t={...t,...l},Pt(),Zn(e,t),t.colorScheme!==T&&kt();let H=Bn.getForInstance(t.plugins);if(r.length=0,r.push(...H),h=(no=(to=t.launcher)==null?void 0:to.enabled)!=null?no:!0,R=(oo=(so=t.launcher)==null?void 0:so.autoExpand)!=null?oo:!1,z=(io=(ro=t.features)==null?void 0:ro.showReasoning)!=null?io:!0,_=(lo=(ao=t.features)==null?void 0:ao.showToolCalls)!=null?lo:!0,((co=t.launcher)==null?void 0:co.enabled)===!1&&Oe&&(Oe.destroy(),Oe=null),((uo=t.launcher)==null?void 0:uo.enabled)===!1&&Ne&&(Ne.remove(),Ne=null),((po=t.launcher)==null?void 0:po.enabled)!==!1&&!Oe&&!Ne){let x=r.find(pe=>pe.renderLauncher);if(x!=null&&x.renderLauncher){let pe=x.renderLauncher({config:t,defaultRenderer:()=>Pn(t,on).element,onToggle:on});pe&&(Ne=pe,e.appendChild(Ne))}Ne||(Oe=Pn(t,on),e.appendChild(Oe.element))}Oe&&Oe.update(t),lt&&((go=t.launcher)==null?void 0:go.title)!==void 0&&(lt.textContent=t.launcher.title),dt&&((mo=t.launcher)==null?void 0:mo.subtitle)!==void 0&&(dt.textContent=t.launcher.subtitle);let b=(ho=t.layout)==null?void 0:ho.header;if((b==null?void 0:b.layout)!==A&&Ve){let x=b?ln(t,b,{showClose:h,onClose:()=>S(!1,"user")}):Ut({config:t,showClose:h,onClose:()=>S(!1,"user")});Ve.replaceWith(x.header),Ve=x.header,fe=x.iconHolder,lt=x.headerTitle,dt=x.headerSubtitle,D=x.closeButton,A=b==null?void 0:b.layout}else if(b&&(fe&&(fe.style.display=b.showIcon===!1?"none":""),lt&&(lt.style.display=b.showTitle===!1?"none":""),dt&&(dt.style.display=b.showSubtitle===!1?"none":""),D&&(D.style.display=b.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let x=b.showClearChat;if(x!==void 0){q.clearChatButtonWrapper.style.display=x?"":"none";let{closeButtonWrapper:pe}=q;pe&&!pe.classList.contains("tvw-absolute")&&(x?pe.classList.remove("tvw-ml-auto"):pe.classList.add("tvw-ml-auto"))}}let ce=((fo=t.layout)==null?void 0:fo.showHeader)!==!1;Ve&&(Ve.style.display=ce?"":"none");let W=((wo=t.layout)==null?void 0:wo.showFooter)!==!1;ct&&(ct.style.display=W?"":"none"),h!==y?h?S(R,"auto"):(I=!0,se()):R!==M&&S(R,"auto"),M=R,y=h,bn(),$s(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&P&&wt(qe,P.getMessages(),k);let $=(yo=t.launcher)!=null?yo:{},je=(vo=$.headerIconHidden)!=null?vo:!1,Se=(Co=(bo=t.layout)==null?void 0:bo.header)==null?void 0:Co.showIcon,ue=je||Se===!1,Je=$.headerIconName,Ye=(xo=$.headerIconSize)!=null?xo:"48px";if(fe){let x=Z.querySelector(".tvw-border-b-cw-divider"),pe=x==null?void 0:x.querySelector(".tvw-flex-col");if(ue)fe.style.display="none",x&&pe&&!x.contains(pe)&&x.insertBefore(pe,x.firstChild);else{if(fe.style.display="",fe.style.height=Ye,fe.style.width=Ye,x&&pe&&(x.contains(fe)?fe.nextSibling!==pe&&(fe.remove(),x.insertBefore(fe,pe)):x.insertBefore(fe,pe)),Je){let oe=parseFloat(Ye)||24,xe=ie(Je,oe*.6,"#ffffff",2);xe?fe.replaceChildren(xe):fe.textContent=(So=$.agentIconText)!=null?So:"\u{1F4AC}"}else if($.iconUrl){let oe=fe.querySelector("img");if(oe)oe.src=$.iconUrl,oe.style.height=Ye,oe.style.width=Ye;else{let xe=document.createElement("img");xe.src=$.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=Ye,xe.style.width=Ye,fe.replaceChildren(xe)}}else{let oe=fe.querySelector("svg"),xe=fe.querySelector("img");(oe||xe)&&fe.replaceChildren(),fe.textContent=(Ao=$.agentIconText)!=null?Ao:"\u{1F4AC}"}let De=fe.querySelector("img");De&&(De.style.height=Ye,De.style.width=Ye)}}let rt=(Mo=(To=t.layout)==null?void 0:To.header)==null?void 0:Mo.showTitle,Tt=(Wo=(Eo=t.layout)==null?void 0:Eo.header)==null?void 0:Wo.showSubtitle;if(lt&&(lt.style.display=rt===!1?"none":""),dt&&(dt.style.display=Tt===!1?"none":""),D){((Lo=(ko=t.layout)==null?void 0:ko.header)==null?void 0:Lo.showCloseButton)===!1?D.style.display="none":D.style.display="";let pe=(Po=$.closeButtonSize)!=null?Po:"32px",De=(Ho=$.closeButtonPlacement)!=null?Ho:"inline";D.style.height=pe,D.style.width=pe;let{closeButtonWrapper:oe}=q,xe=De==="top-right",ut=oe==null?void 0:oe.classList.contains("tvw-absolute");if(oe&&xe!==ut)if(oe.remove(),xe)oe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Z.style.position="relative",Z.appendChild(oe);else{let ae=(Io=(Bo=$.clearChat)==null?void 0:Bo.placement)!=null?Io:"inline",et=(Fo=(Ro=$.clearChat)==null?void 0:Ro.enabled)!=null?Fo:!0;oe.className=et&&ae==="inline"?"":"tvw-ml-auto";let bt=Z.querySelector(".tvw-border-b-cw-divider");bt&&bt.appendChild(oe)}if($.closeButtonColor?(D.style.color=$.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),$.closeButtonBackgroundColor?(D.style.backgroundColor=$.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),$.closeButtonBorderWidth||$.closeButtonBorderColor){let ae=$.closeButtonBorderWidth||"0px",et=$.closeButtonBorderColor||"transparent";D.style.border=`${ae} solid ${et}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");$.closeButtonBorderRadius?(D.style.borderRadius=$.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),$.closeButtonPaddingX?(D.style.paddingLeft=$.closeButtonPaddingX,D.style.paddingRight=$.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),$.closeButtonPaddingY?(D.style.paddingTop=$.closeButtonPaddingY,D.style.paddingBottom=$.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let it=($o=$.closeButtonIconName)!=null?$o:"x",Mt=(Oo=$.closeButtonIconText)!=null?Oo:"\xD7";D.innerHTML="";let yt=ie(it,"20px",$.closeButtonColor||"",2);yt?D.appendChild(yt):D.textContent=Mt;let _e=(No=$.closeButtonTooltipText)!=null?No:"Close chat",Et=(jo=$.closeButtonShowTooltip)!=null?jo:!0;if(D.setAttribute("aria-label",_e),oe&&(oe._cleanupTooltip&&(oe._cleanupTooltip(),delete oe._cleanupTooltip),Et&&_e)){let ae=null,et=()=>{if(ae||!D)return;ae=g("div","tvw-clear-chat-tooltip"),ae.textContent=_e;let En=g("div");En.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(En);let Gt=D.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Gt.left+Gt.width/2}px`,ae.style.top=`${Gt.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},bt=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};oe.addEventListener("mouseenter",et),oe.addEventListener("mouseleave",bt),D.addEventListener("focus",et),D.addEventListener("blur",bt),oe._cleanupTooltip=()=>{bt(),oe&&(oe.removeEventListener("mouseenter",et),oe.removeEventListener("mouseleave",bt)),D&&(D.removeEventListener("focus",et),D.removeEventListener("blur",bt))}}}let{clearChatButton:Q,clearChatButtonWrapper:Me}=q;if(Q){let x=(Do=$.clearChat)!=null?Do:{},pe=(_o=x.enabled)!=null?_o:!0,De=(Uo=(qo=t.layout)==null?void 0:qo.header)==null?void 0:Uo.showClearChat,oe=De!==void 0?De:pe,xe=(zo=x.placement)!=null?zo:"inline";if(Me){Me.style.display=oe?"":"none";let{closeButtonWrapper:ut}=q;ut&&!ut.classList.contains("tvw-absolute")&&(oe?ut.classList.remove("tvw-ml-auto"):ut.classList.add("tvw-ml-auto"));let it=xe==="top-right",Mt=Me.classList.contains("tvw-absolute");if(it!==Mt&&oe){if(Me.remove(),it)Me.className="tvw-absolute tvw-top-4 tvw-z-50",Me.style.right="48px",Z.style.position="relative",Z.appendChild(Me);else{Me.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Me.style.right="";let _e=Z.querySelector(".tvw-border-b-cw-divider"),Et=q.closeButtonWrapper;_e&&Et&&Et.parentElement===_e?_e.insertBefore(Me,Et):_e&&_e.appendChild(Me)}let yt=q.closeButtonWrapper;yt&&!yt.classList.contains("tvw-absolute")&&(it?yt.classList.add("tvw-ml-auto"):yt.classList.remove("tvw-ml-auto"))}}if(oe){let ut=(Jo=x.size)!=null?Jo:"32px";Q.style.height=ut,Q.style.width=ut;let it=(Yo=x.iconName)!=null?Yo:"refresh-cw",Mt=(Ko=x.iconColor)!=null?Ko:"";Q.innerHTML="";let yt=ie(it,"20px",Mt||"",2);if(yt&&Q.appendChild(yt),Mt?(Q.style.color=Mt,Q.classList.remove("tvw-text-cw-muted")):(Q.style.color="",Q.classList.add("tvw-text-cw-muted")),x.backgroundColor?(Q.style.backgroundColor=x.backgroundColor,Q.classList.remove("hover:tvw-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:tvw-bg-gray-100")),x.borderWidth||x.borderColor){let ae=x.borderWidth||"0px",et=x.borderColor||"transparent";Q.style.border=`${ae} solid ${et}`,Q.classList.remove("tvw-border-none")}else Q.style.border="",Q.classList.add("tvw-border-none");x.borderRadius?(Q.style.borderRadius=x.borderRadius,Q.classList.remove("tvw-rounded-full")):(Q.style.borderRadius="",Q.classList.add("tvw-rounded-full")),x.paddingX?(Q.style.paddingLeft=x.paddingX,Q.style.paddingRight=x.paddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),x.paddingY?(Q.style.paddingTop=x.paddingY,Q.style.paddingBottom=x.paddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let _e=(Vo=x.tooltipText)!=null?Vo:"Clear chat",Et=(Xo=x.showTooltip)!=null?Xo:!0;if(Q.setAttribute("aria-label",_e),Me&&(Me._cleanupTooltip&&(Me._cleanupTooltip(),delete Me._cleanupTooltip),Et&&_e)){let ae=null,et=()=>{if(ae||!Q)return;ae=g("div","tvw-clear-chat-tooltip"),ae.textContent=_e;let En=g("div");En.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(En);let Gt=Q.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Gt.left+Gt.width/2}px`,ae.style.top=`${Gt.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},bt=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};Me.addEventListener("mouseenter",et),Me.addEventListener("mouseleave",bt),Q.addEventListener("focus",et),Q.addEventListener("blur",bt),Me._cleanupTooltip=()=>{bt(),Me&&(Me.removeEventListener("mouseenter",et),Me.removeEventListener("mouseleave",bt)),Q&&(Q.removeEventListener("focus",et),Q.removeEventListener("blur",bt))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[In],Xt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[tn.message,tn.messageAndClick];w=Rn({parsers:Vt,handlers:Xt,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),k=fi(t,w,C),P.updateConfig(t),wt(qe,P.getMessages(),k),mt.render(t.suggestionChips,P,ee,void 0,t.suggestionChipsConfig),Y(),E(P.isStreaming());let On=((Go=t.voiceRecognition)==null?void 0:Go.enabled)===!0,Nn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(On&&Nn)if(!F||!Ue){let x=Ae(t.voiceRecognition,t.sendButton);x&&(F=x.micButton,Ue=x.micButtonWrapper,Ot.insertBefore(Ue,at),F.addEventListener("click",Qe),F.disabled=P.isStreaming())}else{let x=(Qo=t.voiceRecognition)!=null?Qo:{},pe=(Zo=t.sendButton)!=null?Zo:{},De=(er=x.iconName)!=null?er:"mic",oe=(tr=pe.size)!=null?tr:"40px",xe=(nr=x.iconSize)!=null?nr:oe,ut=parseFloat(xe)||24;F.style.width=xe,F.style.height=xe,F.style.minWidth=xe,F.style.minHeight=xe;let it=(or=(sr=x.iconColor)!=null?sr:pe.textColor)!=null?or:"currentColor";F.innerHTML="";let Mt=ie(De,ut,it,2);Mt?F.appendChild(Mt):F.textContent="\u{1F3A4}";let yt=(rr=x.backgroundColor)!=null?rr:pe.backgroundColor;yt?(F.style.backgroundColor=yt,F.classList.remove("tvw-bg-cw-primary")):(F.style.backgroundColor="",F.classList.add("tvw-bg-cw-primary")),it?(F.style.color=it,F.classList.remove("tvw-text-white")):!it&&!pe.textColor&&(F.style.color="",F.classList.add("tvw-text-white")),x.borderWidth?(F.style.borderWidth=x.borderWidth,F.style.borderStyle="solid"):(F.style.borderWidth="",F.style.borderStyle=""),x.borderColor?F.style.borderColor=x.borderColor:F.style.borderColor="",x.paddingX?(F.style.paddingLeft=x.paddingX,F.style.paddingRight=x.paddingX):(F.style.paddingLeft="",F.style.paddingRight=""),x.paddingY?(F.style.paddingTop=x.paddingY,F.style.paddingBottom=x.paddingY):(F.style.paddingTop="",F.style.paddingBottom="");let _e=Ue==null?void 0:Ue.querySelector(".tvw-send-button-tooltip"),Et=(ir=x.tooltipText)!=null?ir:"Start voice recognition";if(((ar=x.showTooltip)!=null?ar:!1)&&Et)if(_e)_e.textContent=Et,_e.style.display="";else{let et=document.createElement("div");et.className="tvw-send-button-tooltip",et.textContent=Et,Ue==null||Ue.insertBefore(et,F)}else _e&&(_e.style.display="none");Ue.style.display="",F.disabled=P.isStreaming()}else F&&Ue&&(Ue.style.display="none",ye&&Te());if(((lr=t.attachments)==null?void 0:lr.enabled)===!0)if(!tt||!ge){let x=(dr=t.attachments)!=null?dr:{},De=(ur=((cr=t.sendButton)!=null?cr:{}).size)!=null?ur:"40px";nt||(nt=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),nt.style.display="none",xt.insertBefore(nt,ee)),me||(me=document.createElement("input"),me.type="file",me.accept=((pr=x.allowedTypes)!=null?pr:Yt).join(","),me.multiple=((gr=x.maxFiles)!=null?gr:4)>1,me.style.display="none",me.setAttribute("aria-label","Attach files"),xt.insertBefore(me,ee)),tt=g("div","tvw-send-button-wrapper"),ge=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),ge.type="button",ge.setAttribute("aria-label",(mr=x.buttonTooltipText)!=null?mr:"Attach file");let oe=(hr=x.buttonIconName)!=null?hr:"paperclip",xe=De,ut=parseFloat(xe)||40,it=Math.round(ut*.6);ge.style.width=xe,ge.style.height=xe,ge.style.minWidth=xe,ge.style.minHeight=xe,ge.style.fontSize="18px",ge.style.lineHeight="1",ge.style.backgroundColor="transparent",ge.style.color="var(--cw-primary, #111827)",ge.style.border="none",ge.style.borderRadius="6px",ge.style.transition="background-color 0.15s ease",ge.addEventListener("mouseenter",()=>{ge.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),ge.addEventListener("mouseleave",()=>{ge.style.backgroundColor="transparent"});let Mt=ie(oe,it,"currentColor",1.5);Mt?ge.appendChild(Mt):ge.textContent="\u{1F4CE}",ge.addEventListener("click",Et=>{Et.preventDefault(),me==null||me.click()}),tt.appendChild(ge);let yt=(fr=x.buttonTooltipText)!=null?fr:"Attach file",_e=g("div","tvw-send-button-tooltip");_e.textContent=yt,tt.appendChild(_e),$t.append(tt),!U&&me&&nt&&(U=Zt.fromConfig(x),U.setPreviewsContainer(nt),me.addEventListener("change",async()=>{U&&(me!=null&&me.files)&&(await U.handleFileSelect(me.files),me.value="")}))}else{tt.style.display="";let x=(wr=t.attachments)!=null?wr:{};me&&(me.accept=((yr=x.allowedTypes)!=null?yr:Yt).join(","),me.multiple=((vr=x.maxFiles)!=null?vr:4)>1),U&&U.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else tt&&(tt.style.display="none"),U&&U.clearAttachments();let Ke=(br=t.sendButton)!=null?br:{},jn=(Cr=Ke.useIcon)!=null?Cr:!1,Cn=(xr=Ke.iconText)!=null?xr:"\u2191",xn=Ke.iconName,Jt=(Sr=Ke.tooltipText)!=null?Sr:"Send message",Sn=(Ar=Ke.showTooltip)!=null?Ar:!1,An=(Tr=Ke.size)!=null?Tr:"40px",Dn=Ke.backgroundColor,Nt=Ke.textColor;if(jn){if(j.style.width=An,j.style.height=An,j.style.minWidth=An,j.style.minHeight=An,j.style.fontSize="18px",j.style.lineHeight="1",j.innerHTML="",xn){let x=parseFloat(An)||24,pe=Nt&&typeof Nt=="string"&&Nt.trim()?Nt.trim():"currentColor",De=ie(xn,x,pe,2);De?(j.appendChild(De),j.style.color=pe):(j.textContent=Cn,Nt?j.style.color=Nt:j.classList.add("tvw-text-white"))}else j.textContent=Cn,Nt?j.style.color=Nt: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",Dn?(j.style.backgroundColor=Dn,j.classList.remove("tvw-bg-cw-primary")):j.classList.add("tvw-bg-cw-primary")}else j.textContent=(Er=(Mr=t.copy)==null?void 0:Mr.sendButtonLabel)!=null?Er:"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",Dn?(j.style.backgroundColor=Dn,j.classList.remove("tvw-bg-cw-accent")):j.classList.add("tvw-bg-cw-accent"),Nt?j.style.color=Nt:j.classList.add("tvw-text-white");Ke.borderWidth?(j.style.borderWidth=Ke.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),Ke.borderColor?j.style.borderColor=Ke.borderColor:j.style.borderColor="",Ke.paddingX?(j.style.paddingLeft=Ke.paddingX,j.style.paddingRight=Ke.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),Ke.paddingY?(j.style.paddingTop=Ke.paddingY,j.style.paddingBottom=Ke.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Tn=at==null?void 0:at.querySelector(".tvw-send-button-tooltip");if(Sn&&Jt)if(Tn)Tn.textContent=Jt,Tn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=Jt,at==null||at.insertBefore(x,j)}else Tn&&(Tn.style.display="none");let Mn=(Wr=t.statusIndicator)!=null?Wr:{},Ti=(kr=Mn.visible)!=null?kr:!0;if(vt.style.display=Ti?"":"none",P){let x=P.getStatus(),pe=De=>{var oe,xe,ut,it;return De==="idle"?(oe=Mn.idleText)!=null?oe:pt.idle:De==="connecting"?(xe=Mn.connectingText)!=null?xe:pt.connecting:De==="connected"?(ut=Mn.connectedText)!=null?ut:pt.connected:De==="error"?(it=Mn.errorText)!=null?it:pt.error:pt[De]};vt.textContent=pe(x)}},open(){h&&S(!0,"api")},close(){h&&S(!1,"api")},toggle(){h&&S(!I,"api")},clearChat(){P.clearMessages();try{localStorage.removeItem(hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hn}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let c=i.clear();c instanceof Promise&&c.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}a={},w.syncFromMetadata()},setMessage(l){return!ee||P.isStreaming()?!1:(!I&&h&&S(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(P.isStreaming())return!1;let c=(l==null?void 0:l.trim())||ee.value.trim();return c?(!I&&h&&S(!0,"system"),ee.value="",ee.style.height="auto",P.sendMessage(c),!0):!1},startVoiceRecognition(){return ye||P.isStreaming()||!ve()?!1:(!I&&h&&S(!0,"system"),We.manuallyDeactivated=!1,Dt(),be("user"),!0)},stopVoiceRecognition(){return ye?(We.manuallyDeactivated=!0,Dt(),Te("user"),!0):!1},injectMessage(l){return!I&&h&&S(!0,"system"),P.injectMessage(l)},injectAssistantMessage(l){!I&&h&&S(!0,"system");let c=P.injectAssistantMessage(l);return v&&(v=!1,N&&(clearTimeout(N),N=null),setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)),c},injectUserMessage(l){return!I&&h&&S(!0,"system"),P.injectUserMessage(l)},injectSystemMessage(l){return!I&&h&&S(!0,"system"),P.injectSystemMessage(l)},injectTestMessage(l){!I&&h&&S(!0,"system"),P.injectTestEvent(l)},getMessages(){return P.getMessages()},getStatus(){return P.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){f(l)},on(l,c){return s.on(l,c)},off(l,c){s.off(l,c)},isOpen(){return h&&I},isVoiceActive(){return We.active},getState(){return{open:h&&I,launcherEnabled:h,voiceActive:We.active,streaming:P.isStreaming()}},showCSATFeedback(l){!I&&h&&S(!0,"system");let c=qe.querySelector(".tvw-feedback-container");c&&c.remove();let T=as({onSubmit:async(H,b)=>{var X;P.isClientTokenMode()&&await P.submitCSATFeedback(H,b),(X=l==null?void 0:l.onSubmit)==null||X.call(l,H,b)},onDismiss:l==null?void 0:l.onDismiss,...l});qe.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&h&&S(!0,"system");let c=qe.querySelector(".tvw-feedback-container");c&&c.remove();let T=ls({onSubmit:async(H,b)=>{var X;P.isClientTokenMode()&&await P.submitNPSFeedback(H,b),(X=l==null?void 0:l.onSubmit)==null||X.call(l,H,b)},onDismiss:l==null?void 0:l.onDismiss,...l});qe.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return P.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return P.submitNPSFeedback(l,c)},destroy(){Fe.forEach(l=>l()),J.remove(),Oe==null||Oe.destroy(),Ne==null||Ne.remove(),ht&&D.removeEventListener("click",ht)}};if((((eo=o==null?void 0:o.debugTools)!=null?eo:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,c={controller:_t,getMessages:_t.getMessages,getStatus:_t.getStatus,getMetadata:_t.getPersistentMetadata,updateMetadata:_t.updatePersistentMetadata,clearHistory:()=>_t.clearChat(),setVoiceActive:T=>T?_t.startVoiceRecognition():_t.stopVoiceRecognition()};window.AgentWidgetBrowser=c,Fe.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return _t};var Bs={},ia=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},aa=()=>{try{if(typeof Bs!="undefined"&&Bs.url)return new URL("../widget.css",Bs.url).href}catch{}return null},wi=e=>{let n=aa(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let r=t.cloneNode(!0);e.insertBefore(r,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 o();else if(!document.head.querySelector("link[data-persona]")&&n){let r=document.createElement("link");r.rel="stylesheet",r.href=n,r.setAttribute("data-persona","true"),document.head.appendChild(r)}},Is=e=>{var u,f,p,m;let n=ia(e.target),o=document.createElement("div");o.className="persona-host";let t=(p=(f=(u=e.config)==null?void 0:u.launcher)==null?void 0:f.enabled)!=null?p:!0;t||(o.style.height="100%"),n.appendChild(o);let r=e.useShadowDom===!0,s,i;if(r){let w=o.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),wi(w)}else i=o,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"),o.appendChild(s),wi(o);let a=ds(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:o,destroy(){a.destroy(),o.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var yi={name:"@runtypelabs/persona",version:"1.38.3",description:"Themeable, plugable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var nn=yi.version;function zt(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function da(e){if(e)return{getHeaders:zt(e.getHeaders),onFeedback:zt(e.onFeedback),onCopy:zt(e.onCopy),requestMiddleware:zt(e.requestMiddleware),actionHandlers:zt(e.actionHandlers),actionParsers:zt(e.actionParsers),postprocessMessage:zt(e.postprocessMessage),contextProviders:zt(e.contextProviders),streamParser:zt(e.streamParser)}}var vi=`({ text, message }: any) => {
|
|
60
|
+
`}if(!Se){let Jt="max-height: -moz-available !important; max-height: stretch !important;",Sn=l?"":"padding-top: 1.25em !important;";J.style.cssText+=Jt+Sn}};Pt(),Zn(e,t);let Fe=[],st=null,kt=()=>{st&&(st(),st=null),t.colorScheme==="auto"&&(st=ei(()=>{Zn(e,t)}))};kt(),Fe.push(()=>{st&&(st(),st=null)});let mt=di(Ct),ht=null,P,te=!1,we=!0,Ge=0,St=0,ze=null,ft=!1,Lt=0,Ht=!1,fn=125,Kt=2e3,Fn=5,wn=50,sn=new Map,We={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},yn=(Zs=(Qs=t.voiceRecognition)==null?void 0:Qs.autoResume)!=null?Zs:!1,vn=l=>{s.emit("voice:state",{active:We.active,source:l,timestamp:Date.now()})},Dt=()=>{f(l=>({...l,voiceState:{active:We.active,timestamp:Date.now(),manuallyDeactivated:We.manuallyDeactivated}}))},$n=()=>{var H,b;if(((H=t.voiceRecognition)==null?void 0:H.enabled)===!1)return;let l=Hs(a.voiceState),c=!!l.active,T=Number((b=l.timestamp)!=null?b:0);We.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-T<ra&&setTimeout(()=>{We.active||(We.manuallyDeactivated=!1,be("restore"))},1e3)},I=()=>P?hi(P.getMessages()).filter(l=>!l.__skipPersist):[];function le(l){if(!(i!=null&&i.save))return;let T={messages:l?hi(l):P?I():[],metadata:a};try{let H=i.save(T);H instanceof Promise&&H.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)})}catch(H){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)}}let he=(l=!1)=>{if(!we)return;let c=Date.now();ft&&c<Lt&&!l||(ft&&c>=Lt&&(ft=!1),!(!l&&!te)&&(c-St<fn||(St=c,ze&&cancelAnimationFrame(ze),ze=requestAnimationFrame(()=>{ft||!we||(Ht=!0,de.scrollTop=de.scrollHeight,Ge=de.scrollTop,requestAnimationFrame(()=>{Ht=!1}),ze=null)}))))},Ee=null,Ze=()=>J.querySelector("#persona-scroll-container")||de,ot=(l,c=500)=>{let T=l.scrollTop,H=l.clientHeight,b=l.scrollHeight,X=b-T;if(T+H>=b-2||Math.abs(X)<5)return;Ee!==null&&(cancelAnimationFrame(Ee),Ee=null);let W=performance.now(),K=Ce=>1-Math.pow(1-Ce,3),G=Ce=>{let $=l.scrollHeight;$!==b&&(b=$,X=b-T);let je=Ce-W,Se=Math.min(je/c,1),ue=K(Se),Je=T+X*ue;l.scrollTop=Je,Se<1?Ee=requestAnimationFrame(G):(l.scrollTop=l.scrollHeight,Ee=null)};Ee=requestAnimationFrame(G)},$e=l=>{let c=new Map;l.forEach(T=>{let H=sn.get(T.id);c.set(T.id,{streaming:T.streaming,role:T.role}),!H&&T.role==="assistant"&&s.emit("assistant:message",T),T.role==="assistant"&&(H!=null&&H.streaming)&&T.streaming===!1&&s.emit("assistant:complete",T)}),sn.clear(),c.forEach((T,H)=>{sn.set(H,T)})},wt=(l,c,T)=>{let H=document.createElement("div");c.forEach(W=>{var je,Se;let K=null,G=r.find(ue=>!!(W.variant==="reasoning"&&ue.renderReasoning||W.variant==="tool"&&ue.renderToolCall||!W.variant&&ue.renderMessage)),Ce=(je=t.layout)==null?void 0:je.messages;if(G)if(W.variant==="reasoning"&&W.reasoning&&G.renderReasoning){if(!z)return;K=G.renderReasoning({message:W,defaultRenderer:()=>As(W),config:t})}else if(W.variant==="tool"&&W.toolCall&&G.renderToolCall){if(!_)return;K=G.renderToolCall({message:W,defaultRenderer:()=>Ts(W,t),config:t})}else G.renderMessage&&(K=G.renderMessage({message:W,defaultRenderer:()=>{let ue=cn(W,T,Ce,t.messageActions,ne);return W.role!=="user"&&Ms(ue,W,t,P),ue},config:t}));if(!K&&W.role==="assistant"&&!W.variant&&t.enableComponentStreaming!==!1&&rs(W)){let Je=is(W);if(Je){let Ye=os(Je,{config:t,message:W,transform:T});if(Ye){let rt=document.createElement("div");if(rt.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(" "),rt.id=`bubble-${W.id}`,rt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=T({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),rt.appendChild(Tt)}rt.appendChild(Ye),K=rt}}}if(!K)if(W.variant==="reasoning"&&W.reasoning){if(!z)return;K=As(W)}else if(W.variant==="tool"&&W.toolCall){if(!_)return;K=Ts(W,t)}else{let ue=(Se=t.layout)==null?void 0:Se.messages;ue!=null&&ue.renderUserMessage&&W.role==="user"?K=ue.renderUserMessage({message:W,config:t,streaming:!!W.streaming}):ue!=null&&ue.renderAssistantMessage&&W.role==="assistant"?K=ue.renderAssistantMessage({message:W,config:t,streaming:!!W.streaming}):K=cn(W,T,ue,t.messageActions,ne),W.role!=="user"&&K&&Ms(K,W,t,P)}let $=document.createElement("div");$.className="tvw-flex",$.id=`wrapper-${W.id}`,$.setAttribute("data-wrapper-id",W.id),W.role==="user"&&$.classList.add("tvw-justify-end"),$.appendChild(K),H.appendChild($)});let b=c.some(W=>W.role==="assistant"&&W.streaming),X=c[c.length-1],ce=(X==null?void 0:X.role)==="assistant"&&!X.streaming;if(te&&c.some(W=>W.role==="user")&&!b&&!ce){let W=Hn(),K=document.createElement("div");K.className=["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(" "),K.setAttribute("data-typing-indicator","true"),K.appendChild(W);let G=document.createElement("div");G.className="tvw-flex",G.id="wrapper-typing-indicator",G.setAttribute("data-wrapper-id","typing-indicator"),G.appendChild(K),H.appendChild(G)}ni(l,H),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let W=Ze();ot(W)})})},se=()=>{h&&(B?(J.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),L.classList.remove("tvw-scale-95","tvw-opacity-0"),L.classList.add("tvw-scale-100","tvw-opacity-100"),Oe?Oe.element.style.display="none":Ne&&(Ne.style.display="none")):(J.classList.add("tvw-pointer-events-none","tvw-opacity-0"),L.classList.remove("tvw-scale-100","tvw-opacity-100"),L.classList.add("tvw-scale-95","tvw-opacity-0"),Oe?Oe.element.style.display="":Ne&&(Ne.style.display="")))},S=(l,c="user")=>{if(!h||B===l)return;let T=B;B=l,se(),B&&(bn(),he(!0));let H={open:B,source:c,timestamp:Date.now()};B&&!T?s.emit("widget:opened",H):!B&&T&&s.emit("widget:closed",H),s.emit("widget:state",{open:B,launcherEnabled:h,voiceActive:We.active,streaming:P.isStreaming()})},E=l=>{j.disabled=l,F&&(F.disabled=l),mt.buttons.forEach(c=>{c.disabled=l})},Y=()=>{var b,X,ce,W,K,G,Ce,$,je,Se,ue,Je,Ye,rt;Rt.textContent=(X=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?X:"Hello \u{1F44B}",Ft.textContent=(W=(ce=t.copy)==null?void 0:ce.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",ee.placeholder=(G=(K=t.copy)==null?void 0:K.inputPlaceholder)!=null?G:"How can I help...",(($=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?$:!1)||(j.textContent=(Se=(je=t.copy)==null?void 0:je.sendButtonLabel)!=null?Se:"Send");let c=(Je=(ue=t.theme)==null?void 0:ue.inputFontFamily)!=null?Je:"sans-serif",T=(rt=(Ye=t.theme)==null?void 0:Ye.inputFontWeight)!=null?rt:"400",H=Tt=>{switch(Tt){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'}};ee.style.fontFamily=H(c),ee.style.fontWeight=T};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(c=>({...c,session_id:l}))}}),P=new an(t,{onMessagesChanged(l){wt(qe,l,k),P&&(l.some(H=>H.role==="user")?mt.render([],P,ee,l):mt.render(t.suggestionChips,P,ee,l,t.suggestionChipsConfig)),he(!te),$e(l);let c=[...l].reverse().find(T=>T.role==="user");We.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),le(l)},onStatusChanged(l){var H;let c=(H=t.statusIndicator)!=null?H:{},T=b=>{var X,ce,W,K;return b==="idle"?(X=c.idleText)!=null?X:pt.idle:b==="connecting"?(ce=c.connectingText)!=null?ce:pt.connecting:b==="connected"?(W=c.connectedText)!=null?W:pt.connected:b==="error"?(K=c.errorText)!=null?K:pt.error:pt[b]};vt.textContent=T(l)},onStreamingChanged(l){te=l,E(l),P&&wt(qe,P.getMessages(),k),l||he(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=Hs(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&P.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Pe=l=>{var b;l.preventDefault();let c=ee.value.trim(),T=(b=U==null?void 0:U.hasAttachments())!=null?b:!1;if(!c&&!T)return;let H;T&&(H=[],H.push(...U.getContentParts()),c&&H.push(Xn(c))),ee.value="",ee.style.height="auto",P.sendMessage(c,{contentParts:H}),T&&U.clearAttachments()},He=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),j.click())},ke=null,ye=!1,Be=null,Le=null,ve=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,be=(l="user")=>{var X,ce,W,K;if(ye||P.isStreaming())return;let c=ve();if(!c)return;ke=new c;let H=(ce=((X=t.voiceRecognition)!=null?X:{}).pauseDuration)!=null?ce:2e3;ke.continuous=!0,ke.interimResults=!0,ke.lang="en-US";let b=ee.value;ke.onresult=G=>{let Ce="",$="";for(let Se=0;Se<G.results.length;Se++){let ue=G.results[Se],Je=ue[0].transcript;ue.isFinal?Ce+=Je+" ":$=Je}let je=b+Ce+$;ee.value=je,Be&&clearTimeout(Be),(Ce||$)&&(Be=window.setTimeout(()=>{let Se=ee.value.trim();Se&&ke&&ye&&(Te(),ee.value="",ee.style.height="auto",P.sendMessage(Se,{viaVoice:!0}))},H))},ke.onerror=G=>{G.error!=="no-speech"&&Te()},ke.onend=()=>{if(ye){let G=ee.value.trim();G&&G!==b.trim()&&(ee.value="",ee.style.height="auto",P.sendMessage(G,{viaVoice:!0})),Te()}};try{if(ke.start(),ye=!0,We.active=!0,l!=="system"&&(We.manuallyDeactivated=!1),vn(l),Dt(),F){Le={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let G=(W=t.voiceRecognition)!=null?W:{},Ce=(K=G.recordingBackgroundColor)!=null?K:"#ef4444",$=G.recordingIconColor,je=G.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=Ce,$){F.style.color=$;let Se=F.querySelector("svg");Se&&Se.setAttribute("stroke",$)}je&&(F.style.borderColor=je),F.setAttribute("aria-label","Stop voice recognition")}}catch{Te("system")}},Te=(l="user")=>{if(ye){if(ye=!1,Be&&(clearTimeout(Be),Be=null),ke){try{ke.stop()}catch{}ke=null}if(We.active=!1,vn(l),Dt(),F){if(F.classList.remove("tvw-voice-recording"),Le){F.style.backgroundColor=Le.backgroundColor,F.style.color=Le.color,F.style.borderColor=Le.borderColor;let c=F.querySelector("svg");c&&c.setAttribute("stroke",Le.color||"currentColor"),Le=null}F.setAttribute("aria-label","Start voice recognition")}}},Ae=(l,c)=>{var Je,Ye,rt,Tt,Q,Me,Vt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let H=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");b.type="button",b.setAttribute("aria-label","Start voice recognition");let X=(Je=l==null?void 0:l.iconName)!=null?Je:"mic",ce=(Ye=c==null?void 0:c.size)!=null?Ye:"40px",W=(rt=l==null?void 0:l.iconSize)!=null?rt:ce,K=parseFloat(W)||24,G=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,Ce=(Q=l==null?void 0:l.iconColor)!=null?Q:c==null?void 0:c.textColor;b.style.width=W,b.style.height=W,b.style.minWidth=W,b.style.minHeight=W,b.style.fontSize="18px",b.style.lineHeight="1";let $=Ce||"currentColor",je=ie(X,K,$,1.5);je?(b.appendChild(je),b.style.color=$):(b.textContent="\u{1F3A4}",b.style.color=$),G?b.style.backgroundColor=G:b.classList.add("tvw-bg-cw-primary"),Ce?b.style.color=Ce:!Ce&&!(c!=null&&c.textColor)&&b.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(b.style.borderWidth=l.borderWidth,b.style.borderStyle="solid"),l!=null&&l.borderColor&&(b.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(b.style.paddingLeft=l.paddingX,b.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(b.style.paddingTop=l.paddingY,b.style.paddingBottom=l.paddingY),H.appendChild(b);let Se=(Me=l==null?void 0:l.tooltipText)!=null?Me:"Start voice recognition";if(((Vt=l==null?void 0:l.showTooltip)!=null?Vt:!1)&&Se){let Xt=g("div","tvw-send-button-tooltip");Xt.textContent=Se,H.appendChild(Xt)}return{micButton:b,micButtonWrapper:H}},Qe=()=>{if(ye){let l=ee.value.trim();We.manuallyDeactivated=!0,Dt(),Te("user"),l&&(ee.value="",ee.style.height="auto",P.sendMessage(l))}else We.manuallyDeactivated=!1,Dt(),be("user")};F&&(F.addEventListener("click",Qe),Fe.push(()=>{Te("system"),F&&F.removeEventListener("click",Qe)}));let At=s.on("assistant:complete",()=>{yn&&(We.active||We.manuallyDeactivated||yn==="assistant"&&!We.lastUserMessageWasVoice||setTimeout(()=>{!We.active&&!We.manuallyDeactivated&&be("auto")},600))});Fe.push(At);let It=s.on("action:resubmit",()=>{setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)});Fe.push(It);let on=()=>{S(!B,"user")},Oe=null,Ne=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>Pn(t,on).element,onToggle:on});c&&(Ne=c)}Ne||(Oe=Pn(t,on))}Oe?e.appendChild(Oe.element):Ne&&e.appendChild(Ne),se(),mt.render(t.suggestionChips,P,ee,void 0,t.suggestionChipsConfig),Y(),E(P.isStreaming()),he(!0),$n();let bn=()=>{var T,H,b,X,ce,W,K,G;let l=(H=(T=t.launcher)==null?void 0:T.sidebarMode)!=null?H:!1,c=l||((X=(b=t.launcher)==null?void 0:b.fullHeight)!=null?X:!1);if(!h){L.style.height="",L.style.width="";return}if(!l){let Ce=(W=(ce=t==null?void 0:t.launcher)==null?void 0:ce.width)!=null?W:t==null?void 0:t.launcherWidth,$=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";L.style.width=$,L.style.maxWidth=$}if(!c){let Ce=window.innerHeight,$=64,je=(G=(K=t.launcher)==null?void 0:K.heightOffset)!=null?G:0,Se=Math.max(200,Ce-$),ue=Math.min(640,Se),Je=Math.max(200,ue-je);L.style.height=`${Je}px`}};bn(),window.addEventListener("resize",bn),Fe.push(()=>window.removeEventListener("resize",bn)),Ge=de.scrollTop;let Fs=()=>{let l=de.scrollTop,c=de.scrollHeight,T=de.clientHeight,H=c-l-T,b=Math.abs(l-Ge);if(Ge=l,!Ht&&!(b<=Fn)){if(!we&&H<wn){ft=!1,we=!0;return}we&&H>wn&&(ft=!0,Lt=Date.now()+Kt,we=!1)}};de.addEventListener("scroll",Fs,{passive:!0}),Fe.push(()=>de.removeEventListener("scroll",Fs)),Fe.push(()=>{ze&&cancelAnimationFrame(ze)});let $s=()=>{D&&(ht&&(D.removeEventListener("click",ht),ht=null),h?(D.style.display="",ht=()=>{B=!1,se()},D.addEventListener("click",ht)):D.style.display="none")};$s(),(()=>{let{clearChatButton:l}=q;l&&l.addEventListener("click",()=>{P.clearMessages();try{localStorage.removeItem(hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hn}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",H)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}a={},w.syncFromMetadata()})})(),xt.addEventListener("submit",Pe),ee.addEventListener("keydown",He),Fe.push(()=>{xt.removeEventListener("submit",Pe),ee.removeEventListener("keydown",He)}),Fe.push(()=>{P.cancel()}),Oe?Fe.push(()=>{Oe==null||Oe.destroy()}):Ne&&Fe.push(()=>{Ne==null||Ne.remove()});let _t={update(l){var to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Mo,Eo,Wo,ko,Lo,Po,Ho,Io,Bo,Ro,Fo,$o,Oo,No,jo,Do,_o,qo,Uo,zo,Jo,Yo,Ko,Vo,Xo,Go,Qo,Zo,er,tr,nr,sr,or,rr,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar,Tr,Mr,Er,Wr,kr;let c=t.toolCall,T=t.colorScheme;t={...t,...l},Pt(),Zn(e,t),t.colorScheme!==T&&kt();let H=In.getForInstance(t.plugins);if(r.length=0,r.push(...H),h=(no=(to=t.launcher)==null?void 0:to.enabled)!=null?no:!0,R=(oo=(so=t.launcher)==null?void 0:so.autoExpand)!=null?oo:!1,z=(io=(ro=t.features)==null?void 0:ro.showReasoning)!=null?io:!0,_=(lo=(ao=t.features)==null?void 0:ao.showToolCalls)!=null?lo:!0,((co=t.launcher)==null?void 0:co.enabled)===!1&&Oe&&(Oe.destroy(),Oe=null),((uo=t.launcher)==null?void 0:uo.enabled)===!1&&Ne&&(Ne.remove(),Ne=null),((po=t.launcher)==null?void 0:po.enabled)!==!1&&!Oe&&!Ne){let x=r.find(pe=>pe.renderLauncher);if(x!=null&&x.renderLauncher){let pe=x.renderLauncher({config:t,defaultRenderer:()=>Pn(t,on).element,onToggle:on});pe&&(Ne=pe,e.appendChild(Ne))}Ne||(Oe=Pn(t,on),e.appendChild(Oe.element))}Oe&&Oe.update(t),lt&&((go=t.launcher)==null?void 0:go.title)!==void 0&&(lt.textContent=t.launcher.title),dt&&((mo=t.launcher)==null?void 0:mo.subtitle)!==void 0&&(dt.textContent=t.launcher.subtitle);let b=(ho=t.layout)==null?void 0:ho.header;if((b==null?void 0:b.layout)!==A&&Ve){let x=b?ln(t,b,{showClose:h,onClose:()=>S(!1,"user")}):Ut({config:t,showClose:h,onClose:()=>S(!1,"user")});Ve.replaceWith(x.header),Ve=x.header,fe=x.iconHolder,lt=x.headerTitle,dt=x.headerSubtitle,D=x.closeButton,A=b==null?void 0:b.layout}else if(b&&(fe&&(fe.style.display=b.showIcon===!1?"none":""),lt&&(lt.style.display=b.showTitle===!1?"none":""),dt&&(dt.style.display=b.showSubtitle===!1?"none":""),D&&(D.style.display=b.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let x=b.showClearChat;if(x!==void 0){q.clearChatButtonWrapper.style.display=x?"":"none";let{closeButtonWrapper:pe}=q;pe&&!pe.classList.contains("tvw-absolute")&&(x?pe.classList.remove("tvw-ml-auto"):pe.classList.add("tvw-ml-auto"))}}let ce=((fo=t.layout)==null?void 0:fo.showHeader)!==!1;Ve&&(Ve.style.display=ce?"":"none");let W=((wo=t.layout)==null?void 0:wo.showFooter)!==!1;ct&&(ct.style.display=W?"":"none"),h!==y?h?S(R,"auto"):(B=!0,se()):R!==M&&S(R,"auto"),M=R,y=h,bn(),$s(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&P&&wt(qe,P.getMessages(),k);let $=(yo=t.launcher)!=null?yo:{},je=(vo=$.headerIconHidden)!=null?vo:!1,Se=(Co=(bo=t.layout)==null?void 0:bo.header)==null?void 0:Co.showIcon,ue=je||Se===!1,Je=$.headerIconName,Ye=(xo=$.headerIconSize)!=null?xo:"48px";if(fe){let x=Z.querySelector(".tvw-border-b-cw-divider"),pe=x==null?void 0:x.querySelector(".tvw-flex-col");if(ue)fe.style.display="none",x&&pe&&!x.contains(pe)&&x.insertBefore(pe,x.firstChild);else{if(fe.style.display="",fe.style.height=Ye,fe.style.width=Ye,x&&pe&&(x.contains(fe)?fe.nextSibling!==pe&&(fe.remove(),x.insertBefore(fe,pe)):x.insertBefore(fe,pe)),Je){let oe=parseFloat(Ye)||24,xe=ie(Je,oe*.6,"#ffffff",2);xe?fe.replaceChildren(xe):fe.textContent=(So=$.agentIconText)!=null?So:"\u{1F4AC}"}else if($.iconUrl){let oe=fe.querySelector("img");if(oe)oe.src=$.iconUrl,oe.style.height=Ye,oe.style.width=Ye;else{let xe=document.createElement("img");xe.src=$.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=Ye,xe.style.width=Ye,fe.replaceChildren(xe)}}else{let oe=fe.querySelector("svg"),xe=fe.querySelector("img");(oe||xe)&&fe.replaceChildren(),fe.textContent=(Ao=$.agentIconText)!=null?Ao:"\u{1F4AC}"}let De=fe.querySelector("img");De&&(De.style.height=Ye,De.style.width=Ye)}}let rt=(Mo=(To=t.layout)==null?void 0:To.header)==null?void 0:Mo.showTitle,Tt=(Wo=(Eo=t.layout)==null?void 0:Eo.header)==null?void 0:Wo.showSubtitle;if(lt&&(lt.style.display=rt===!1?"none":""),dt&&(dt.style.display=Tt===!1?"none":""),D){((Lo=(ko=t.layout)==null?void 0:ko.header)==null?void 0:Lo.showCloseButton)===!1?D.style.display="none":D.style.display="";let pe=(Po=$.closeButtonSize)!=null?Po:"32px",De=(Ho=$.closeButtonPlacement)!=null?Ho:"inline";D.style.height=pe,D.style.width=pe;let{closeButtonWrapper:oe}=q,xe=De==="top-right",ut=oe==null?void 0:oe.classList.contains("tvw-absolute");if(oe&&xe!==ut)if(oe.remove(),xe)oe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Z.style.position="relative",Z.appendChild(oe);else{let ae=(Bo=(Io=$.clearChat)==null?void 0:Io.placement)!=null?Bo:"inline",et=(Fo=(Ro=$.clearChat)==null?void 0:Ro.enabled)!=null?Fo:!0;oe.className=et&&ae==="inline"?"":"tvw-ml-auto";let bt=Z.querySelector(".tvw-border-b-cw-divider");bt&&bt.appendChild(oe)}if($.closeButtonColor?(D.style.color=$.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),$.closeButtonBackgroundColor?(D.style.backgroundColor=$.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),$.closeButtonBorderWidth||$.closeButtonBorderColor){let ae=$.closeButtonBorderWidth||"0px",et=$.closeButtonBorderColor||"transparent";D.style.border=`${ae} solid ${et}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");$.closeButtonBorderRadius?(D.style.borderRadius=$.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),$.closeButtonPaddingX?(D.style.paddingLeft=$.closeButtonPaddingX,D.style.paddingRight=$.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),$.closeButtonPaddingY?(D.style.paddingTop=$.closeButtonPaddingY,D.style.paddingBottom=$.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let it=($o=$.closeButtonIconName)!=null?$o:"x",Mt=(Oo=$.closeButtonIconText)!=null?Oo:"\xD7";D.innerHTML="";let yt=ie(it,"20px",$.closeButtonColor||"",2);yt?D.appendChild(yt):D.textContent=Mt;let _e=(No=$.closeButtonTooltipText)!=null?No:"Close chat",Et=(jo=$.closeButtonShowTooltip)!=null?jo:!0;if(D.setAttribute("aria-label",_e),oe&&(oe._cleanupTooltip&&(oe._cleanupTooltip(),delete oe._cleanupTooltip),Et&&_e)){let ae=null,et=()=>{if(ae||!D)return;ae=g("div","tvw-clear-chat-tooltip"),ae.textContent=_e;let En=g("div");En.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(En);let Gt=D.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Gt.left+Gt.width/2}px`,ae.style.top=`${Gt.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},bt=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};oe.addEventListener("mouseenter",et),oe.addEventListener("mouseleave",bt),D.addEventListener("focus",et),D.addEventListener("blur",bt),oe._cleanupTooltip=()=>{bt(),oe&&(oe.removeEventListener("mouseenter",et),oe.removeEventListener("mouseleave",bt)),D&&(D.removeEventListener("focus",et),D.removeEventListener("blur",bt))}}}let{clearChatButton:Q,clearChatButtonWrapper:Me}=q;if(Q){let x=(Do=$.clearChat)!=null?Do:{},pe=(_o=x.enabled)!=null?_o:!0,De=(Uo=(qo=t.layout)==null?void 0:qo.header)==null?void 0:Uo.showClearChat,oe=De!==void 0?De:pe,xe=(zo=x.placement)!=null?zo:"inline";if(Me){Me.style.display=oe?"":"none";let{closeButtonWrapper:ut}=q;ut&&!ut.classList.contains("tvw-absolute")&&(oe?ut.classList.remove("tvw-ml-auto"):ut.classList.add("tvw-ml-auto"));let it=xe==="top-right",Mt=Me.classList.contains("tvw-absolute");if(it!==Mt&&oe){if(Me.remove(),it)Me.className="tvw-absolute tvw-top-4 tvw-z-50",Me.style.right="48px",Z.style.position="relative",Z.appendChild(Me);else{Me.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Me.style.right="";let _e=Z.querySelector(".tvw-border-b-cw-divider"),Et=q.closeButtonWrapper;_e&&Et&&Et.parentElement===_e?_e.insertBefore(Me,Et):_e&&_e.appendChild(Me)}let yt=q.closeButtonWrapper;yt&&!yt.classList.contains("tvw-absolute")&&(it?yt.classList.add("tvw-ml-auto"):yt.classList.remove("tvw-ml-auto"))}}if(oe){let ut=(Jo=x.size)!=null?Jo:"32px";Q.style.height=ut,Q.style.width=ut;let it=(Yo=x.iconName)!=null?Yo:"refresh-cw",Mt=(Ko=x.iconColor)!=null?Ko:"";Q.innerHTML="";let yt=ie(it,"20px",Mt||"",2);if(yt&&Q.appendChild(yt),Mt?(Q.style.color=Mt,Q.classList.remove("tvw-text-cw-muted")):(Q.style.color="",Q.classList.add("tvw-text-cw-muted")),x.backgroundColor?(Q.style.backgroundColor=x.backgroundColor,Q.classList.remove("hover:tvw-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:tvw-bg-gray-100")),x.borderWidth||x.borderColor){let ae=x.borderWidth||"0px",et=x.borderColor||"transparent";Q.style.border=`${ae} solid ${et}`,Q.classList.remove("tvw-border-none")}else Q.style.border="",Q.classList.add("tvw-border-none");x.borderRadius?(Q.style.borderRadius=x.borderRadius,Q.classList.remove("tvw-rounded-full")):(Q.style.borderRadius="",Q.classList.add("tvw-rounded-full")),x.paddingX?(Q.style.paddingLeft=x.paddingX,Q.style.paddingRight=x.paddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),x.paddingY?(Q.style.paddingTop=x.paddingY,Q.style.paddingBottom=x.paddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let _e=(Vo=x.tooltipText)!=null?Vo:"Clear chat",Et=(Xo=x.showTooltip)!=null?Xo:!0;if(Q.setAttribute("aria-label",_e),Me&&(Me._cleanupTooltip&&(Me._cleanupTooltip(),delete Me._cleanupTooltip),Et&&_e)){let ae=null,et=()=>{if(ae||!Q)return;ae=g("div","tvw-clear-chat-tooltip"),ae.textContent=_e;let En=g("div");En.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(En);let Gt=Q.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Gt.left+Gt.width/2}px`,ae.style.top=`${Gt.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},bt=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};Me.addEventListener("mouseenter",et),Me.addEventListener("mouseleave",bt),Q.addEventListener("focus",et),Q.addEventListener("blur",bt),Me._cleanupTooltip=()=>{bt(),Me&&(Me.removeEventListener("mouseenter",et),Me.removeEventListener("mouseleave",bt)),Q&&(Q.removeEventListener("focus",et),Q.removeEventListener("blur",bt))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Bn],Xt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[tn.message,tn.messageAndClick];w=Rn({parsers:Vt,handlers:Xt,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),k=fi(t,w,C),P.updateConfig(t),wt(qe,P.getMessages(),k),mt.render(t.suggestionChips,P,ee,void 0,t.suggestionChipsConfig),Y(),E(P.isStreaming());let On=((Go=t.voiceRecognition)==null?void 0:Go.enabled)===!0,Nn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(On&&Nn)if(!F||!Ue){let x=Ae(t.voiceRecognition,t.sendButton);x&&(F=x.micButton,Ue=x.micButtonWrapper,Ot.insertBefore(Ue,at),F.addEventListener("click",Qe),F.disabled=P.isStreaming())}else{let x=(Qo=t.voiceRecognition)!=null?Qo:{},pe=(Zo=t.sendButton)!=null?Zo:{},De=(er=x.iconName)!=null?er:"mic",oe=(tr=pe.size)!=null?tr:"40px",xe=(nr=x.iconSize)!=null?nr:oe,ut=parseFloat(xe)||24;F.style.width=xe,F.style.height=xe,F.style.minWidth=xe,F.style.minHeight=xe;let it=(or=(sr=x.iconColor)!=null?sr:pe.textColor)!=null?or:"currentColor";F.innerHTML="";let Mt=ie(De,ut,it,2);Mt?F.appendChild(Mt):F.textContent="\u{1F3A4}";let yt=(rr=x.backgroundColor)!=null?rr:pe.backgroundColor;yt?(F.style.backgroundColor=yt,F.classList.remove("tvw-bg-cw-primary")):(F.style.backgroundColor="",F.classList.add("tvw-bg-cw-primary")),it?(F.style.color=it,F.classList.remove("tvw-text-white")):!it&&!pe.textColor&&(F.style.color="",F.classList.add("tvw-text-white")),x.borderWidth?(F.style.borderWidth=x.borderWidth,F.style.borderStyle="solid"):(F.style.borderWidth="",F.style.borderStyle=""),x.borderColor?F.style.borderColor=x.borderColor:F.style.borderColor="",x.paddingX?(F.style.paddingLeft=x.paddingX,F.style.paddingRight=x.paddingX):(F.style.paddingLeft="",F.style.paddingRight=""),x.paddingY?(F.style.paddingTop=x.paddingY,F.style.paddingBottom=x.paddingY):(F.style.paddingTop="",F.style.paddingBottom="");let _e=Ue==null?void 0:Ue.querySelector(".tvw-send-button-tooltip"),Et=(ir=x.tooltipText)!=null?ir:"Start voice recognition";if(((ar=x.showTooltip)!=null?ar:!1)&&Et)if(_e)_e.textContent=Et,_e.style.display="";else{let et=document.createElement("div");et.className="tvw-send-button-tooltip",et.textContent=Et,Ue==null||Ue.insertBefore(et,F)}else _e&&(_e.style.display="none");Ue.style.display="",F.disabled=P.isStreaming()}else F&&Ue&&(Ue.style.display="none",ye&&Te());if(((lr=t.attachments)==null?void 0:lr.enabled)===!0)if(!tt||!ge){let x=(dr=t.attachments)!=null?dr:{},De=(ur=((cr=t.sendButton)!=null?cr:{}).size)!=null?ur:"40px";nt||(nt=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),nt.style.display="none",xt.insertBefore(nt,ee)),me||(me=document.createElement("input"),me.type="file",me.accept=((pr=x.allowedTypes)!=null?pr:Yt).join(","),me.multiple=((gr=x.maxFiles)!=null?gr:4)>1,me.style.display="none",me.setAttribute("aria-label","Attach files"),xt.insertBefore(me,ee)),tt=g("div","tvw-send-button-wrapper"),ge=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),ge.type="button",ge.setAttribute("aria-label",(mr=x.buttonTooltipText)!=null?mr:"Attach file");let oe=(hr=x.buttonIconName)!=null?hr:"paperclip",xe=De,ut=parseFloat(xe)||40,it=Math.round(ut*.6);ge.style.width=xe,ge.style.height=xe,ge.style.minWidth=xe,ge.style.minHeight=xe,ge.style.fontSize="18px",ge.style.lineHeight="1",ge.style.backgroundColor="transparent",ge.style.color="var(--cw-primary, #111827)",ge.style.border="none",ge.style.borderRadius="6px",ge.style.transition="background-color 0.15s ease",ge.addEventListener("mouseenter",()=>{ge.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),ge.addEventListener("mouseleave",()=>{ge.style.backgroundColor="transparent"});let Mt=ie(oe,it,"currentColor",1.5);Mt?ge.appendChild(Mt):ge.textContent="\u{1F4CE}",ge.addEventListener("click",Et=>{Et.preventDefault(),me==null||me.click()}),tt.appendChild(ge);let yt=(fr=x.buttonTooltipText)!=null?fr:"Attach file",_e=g("div","tvw-send-button-tooltip");_e.textContent=yt,tt.appendChild(_e),$t.append(tt),!U&&me&&nt&&(U=Zt.fromConfig(x),U.setPreviewsContainer(nt),me.addEventListener("change",async()=>{U&&(me!=null&&me.files)&&(await U.handleFileSelect(me.files),me.value="")}))}else{tt.style.display="";let x=(wr=t.attachments)!=null?wr:{};me&&(me.accept=((yr=x.allowedTypes)!=null?yr:Yt).join(","),me.multiple=((vr=x.maxFiles)!=null?vr:4)>1),U&&U.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else tt&&(tt.style.display="none"),U&&U.clearAttachments();let Ke=(br=t.sendButton)!=null?br:{},jn=(Cr=Ke.useIcon)!=null?Cr:!1,Cn=(xr=Ke.iconText)!=null?xr:"\u2191",xn=Ke.iconName,Jt=(Sr=Ke.tooltipText)!=null?Sr:"Send message",Sn=(Ar=Ke.showTooltip)!=null?Ar:!1,An=(Tr=Ke.size)!=null?Tr:"40px",Dn=Ke.backgroundColor,Nt=Ke.textColor;if(jn){if(j.style.width=An,j.style.height=An,j.style.minWidth=An,j.style.minHeight=An,j.style.fontSize="18px",j.style.lineHeight="1",j.innerHTML="",xn){let x=parseFloat(An)||24,pe=Nt&&typeof Nt=="string"&&Nt.trim()?Nt.trim():"currentColor",De=ie(xn,x,pe,2);De?(j.appendChild(De),j.style.color=pe):(j.textContent=Cn,Nt?j.style.color=Nt:j.classList.add("tvw-text-white"))}else j.textContent=Cn,Nt?j.style.color=Nt: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",Dn?(j.style.backgroundColor=Dn,j.classList.remove("tvw-bg-cw-primary")):j.classList.add("tvw-bg-cw-primary")}else j.textContent=(Er=(Mr=t.copy)==null?void 0:Mr.sendButtonLabel)!=null?Er:"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",Dn?(j.style.backgroundColor=Dn,j.classList.remove("tvw-bg-cw-accent")):j.classList.add("tvw-bg-cw-accent"),Nt?j.style.color=Nt:j.classList.add("tvw-text-white");Ke.borderWidth?(j.style.borderWidth=Ke.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),Ke.borderColor?j.style.borderColor=Ke.borderColor:j.style.borderColor="",Ke.paddingX?(j.style.paddingLeft=Ke.paddingX,j.style.paddingRight=Ke.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),Ke.paddingY?(j.style.paddingTop=Ke.paddingY,j.style.paddingBottom=Ke.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Tn=at==null?void 0:at.querySelector(".tvw-send-button-tooltip");if(Sn&&Jt)if(Tn)Tn.textContent=Jt,Tn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=Jt,at==null||at.insertBefore(x,j)}else Tn&&(Tn.style.display="none");let Mn=(Wr=t.statusIndicator)!=null?Wr:{},Ti=(kr=Mn.visible)!=null?kr:!0;if(vt.style.display=Ti?"":"none",P){let x=P.getStatus(),pe=De=>{var oe,xe,ut,it;return De==="idle"?(oe=Mn.idleText)!=null?oe:pt.idle:De==="connecting"?(xe=Mn.connectingText)!=null?xe:pt.connecting:De==="connected"?(ut=Mn.connectedText)!=null?ut:pt.connected:De==="error"?(it=Mn.errorText)!=null?it:pt.error:pt[De]};vt.textContent=pe(x)}},open(){h&&S(!0,"api")},close(){h&&S(!1,"api")},toggle(){h&&S(!B,"api")},clearChat(){P.clearMessages();try{localStorage.removeItem(hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hn}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let c=i.clear();c instanceof Promise&&c.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}a={},w.syncFromMetadata()},setMessage(l){return!ee||P.isStreaming()?!1:(!B&&h&&S(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(P.isStreaming())return!1;let c=(l==null?void 0:l.trim())||ee.value.trim();return c?(!B&&h&&S(!0,"system"),ee.value="",ee.style.height="auto",P.sendMessage(c),!0):!1},startVoiceRecognition(){return ye||P.isStreaming()||!ve()?!1:(!B&&h&&S(!0,"system"),We.manuallyDeactivated=!1,Dt(),be("user"),!0)},stopVoiceRecognition(){return ye?(We.manuallyDeactivated=!0,Dt(),Te("user"),!0):!1},injectMessage(l){return!B&&h&&S(!0,"system"),P.injectMessage(l)},injectAssistantMessage(l){!B&&h&&S(!0,"system");let c=P.injectAssistantMessage(l);return v&&(v=!1,N&&(clearTimeout(N),N=null),setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)),c},injectUserMessage(l){return!B&&h&&S(!0,"system"),P.injectUserMessage(l)},injectSystemMessage(l){return!B&&h&&S(!0,"system"),P.injectSystemMessage(l)},injectTestMessage(l){!B&&h&&S(!0,"system"),P.injectTestEvent(l)},getMessages(){return P.getMessages()},getStatus(){return P.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){f(l)},on(l,c){return s.on(l,c)},off(l,c){s.off(l,c)},isOpen(){return h&&B},isVoiceActive(){return We.active},getState(){return{open:h&&B,launcherEnabled:h,voiceActive:We.active,streaming:P.isStreaming()}},showCSATFeedback(l){!B&&h&&S(!0,"system");let c=qe.querySelector(".tvw-feedback-container");c&&c.remove();let T=as({onSubmit:async(H,b)=>{var X;P.isClientTokenMode()&&await P.submitCSATFeedback(H,b),(X=l==null?void 0:l.onSubmit)==null||X.call(l,H,b)},onDismiss:l==null?void 0:l.onDismiss,...l});qe.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!B&&h&&S(!0,"system");let c=qe.querySelector(".tvw-feedback-container");c&&c.remove();let T=ls({onSubmit:async(H,b)=>{var X;P.isClientTokenMode()&&await P.submitNPSFeedback(H,b),(X=l==null?void 0:l.onSubmit)==null||X.call(l,H,b)},onDismiss:l==null?void 0:l.onDismiss,...l});qe.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return P.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return P.submitNPSFeedback(l,c)},destroy(){Fe.forEach(l=>l()),J.remove(),Oe==null||Oe.destroy(),Ne==null||Ne.remove(),ht&&D.removeEventListener("click",ht)}};if((((eo=o==null?void 0:o.debugTools)!=null?eo:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,c={controller:_t,getMessages:_t.getMessages,getStatus:_t.getStatus,getMetadata:_t.getPersistentMetadata,updateMetadata:_t.updatePersistentMetadata,clearHistory:()=>_t.clearChat(),setVoiceActive:T=>T?_t.startVoiceRecognition():_t.stopVoiceRecognition()};window.AgentWidgetBrowser=c,Fe.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return _t};var Is={},ia=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},aa=()=>{try{if(typeof Is!="undefined"&&Is.url)return new URL("../widget.css",Is.url).href}catch{}return null},wi=e=>{let n=aa(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let r=t.cloneNode(!0);e.insertBefore(r,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 o();else if(!document.head.querySelector("link[data-persona]")&&n){let r=document.createElement("link");r.rel="stylesheet",r.href=n,r.setAttribute("data-persona","true"),document.head.appendChild(r)}},Bs=e=>{var u,f,p,m;let n=ia(e.target),o=document.createElement("div");o.className="persona-host";let t=(p=(f=(u=e.config)==null?void 0:u.launcher)==null?void 0:f.enabled)!=null?p:!0;t||(o.style.height="100%"),n.appendChild(o);let r=e.useShadowDom===!0,s,i;if(r){let w=o.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),wi(w)}else i=o,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"),o.appendChild(s),wi(o);let a=ds(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:o,destroy(){a.destroy(),o.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var yi={name:"@runtypelabs/persona",version:"1.39.0",description:"Themeable, plugable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var nn=yi.version;function zt(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function da(e){if(e)return{getHeaders:zt(e.getHeaders),onFeedback:zt(e.onFeedback),onCopy:zt(e.onCopy),requestMiddleware:zt(e.requestMiddleware),actionHandlers:zt(e.actionHandlers),actionParsers:zt(e.actionParsers),postprocessMessage:zt(e.postprocessMessage),contextProviders:zt(e.contextProviders),streamParser:zt(e.streamParser)}}var vi=`({ 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
|
|
@@ -136,5 +136,5 @@
|
|
|
136
136
|
`)}function ya(e,n){let o=n==null?void 0:n.hooks,t=Ai(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
|
|
137
137
|
`).map((i,a)=>a===0?i:" "+i).join(`
|
|
138
138
|
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${nn}/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 o!=null&&o.getHeaders&&(s.push(` widgetConfig.getHeaders = ${o.getHeaders};`),s.push("")),o!=null&&o.contextProviders&&(s.push(` widgetConfig.contextProviders = ${o.contextProviders};`),s.push("")),o!=null&&o.streamParser?s.push(` widgetConfig.streamParser = ${o.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${ua});`),s.push(" };")),s.push(""),o!=null&&o.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${o.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${bi}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${bi}`),s.push(" ];")),s.push(""),o!=null&&o.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${o.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${xi}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${xi}`),s.push(" ];")),s.push(""),o!=null&&o.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${o.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(""),o!=null&&o.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${o.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(o!=null&&o.onFeedback||o!=null&&o.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),o!=null&&o.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${o.onFeedback};`),o!=null&&o.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${o.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 va=
|
|
139
|
+
`)}var va=Bs;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,validateImageFile});
|
|
140
140
|
//# sourceMappingURL=index.cjs.map
|