@runtypelabs/persona 1.40.0 → 1.41.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/README.md +151 -0
- package/dist/index.cjs +26 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +211 -3
- package/dist/index.d.ts +211 -3
- package/dist/index.global.js +51 -51
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +28 -28
- package/dist/index.js.map +1 -1
- package/dist/widget.css +7 -0
- package/package.json +1 -1
- package/src/components/composer-builder.ts +1 -1
- package/src/components/message-bubble.ts +63 -8
- package/src/index.ts +14 -3
- package/src/plugins/types.ts +38 -1
- package/src/styles/widget.css +7 -0
- package/src/types.ts +163 -0
- package/src/ui.ts +172 -44
- package/src/utils/morph.ts +3 -1
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ys=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)}},
|
|
1
|
+
"use strict";var Ri=Object.create;var qn=Object.defineProperty;var Fi=Object.getOwnPropertyDescriptor;var $i=Object.getOwnPropertyNames;var Oi=Object.getPrototypeOf,Ni=Object.prototype.hasOwnProperty;var ji=(e,n)=>{for(var r in n)qn(e,r,{get:n[r],enumerable:!0})},Oo=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of $i(n))!Ni.call(e,o)&&o!==r&&qn(e,o,{get:()=>n[o],enumerable:!(t=Fi(n,o))||t.enumerable});return e};var Di=(e,n,r)=>(r=e!=null?Ri(Oi(e)):{},Oo(n||!e||!e.__esModule?qn(r,"default",{value:e,enumerable:!0}):r,e)),_i=e=>Oo(qn({},"__esModule",{value:!0}),e);var Ia={};ji(Ia,{AgentWidgetClient:()=>nn,AgentWidgetSession:()=>pn,AttachmentManager:()=>sn,DEFAULT_DARK_THEME:()=>Is,DEFAULT_LIGHT_THEME:()=>Ws,DEFAULT_WIDGET_CONFIG:()=>Oe,VERSION:()=>ln,attachHeaderToContainer:()=>rn,buildComposer:()=>mn,buildDefaultHeader:()=>bs,buildExpandedHeader:()=>xs,buildHeader:()=>Kt,buildHeaderWithLayout:()=>gn,buildMinimalHeader:()=>Cs,componentRegistry:()=>yn,createActionManager:()=>On,createAgentExperience:()=>cs,createBubbleWithLayout:()=>mi,createCSATFeedback:()=>ls,createComponentMiddleware:()=>xi,createComponentStreamParser:()=>rs,createDirectivePostprocessor:()=>qo,createFlexibleJsonStreamParser:()=>Yo,createImagePart:()=>ti,createJsonStreamParser:()=>Vn,createLocalStorageAdapter:()=>ss,createMarkdownProcessor:()=>Pn,createMarkdownProcessorFromConfig:()=>Hn,createMessageActions:()=>Ts,createNPSFeedback:()=>ds,createPlainTextParser:()=>Yn,createRegexJsonParser:()=>Kn,createStandardBubble:()=>hn,createTextPart:()=>Gn,createTypingIndicator:()=>on,createXmlParser:()=>Xn,default:()=>Wa,defaultActionHandlers:()=>an,defaultJsonActionParser:()=>$n,directivePostprocessor:()=>Uo,escapeHtml:()=>Un,extractComponentDirectiveFromMessage:()=>as,fileToImagePart:()=>ni,generateAssistantMessageId:()=>un,generateCodeSnippet:()=>Ii,generateMessageId:()=>Xo,generateUserMessageId:()=>Bn,getDisplayText:()=>Qo,getHeaderLayout:()=>Ss,getImageParts:()=>ei,hasComponentDirective:()=>is,hasImages:()=>Zo,headerLayouts:()=>ts,initAgentWidget:()=>Fs,isComponentDirectiveType:()=>Ci,markdownPostprocessor:()=>ws,mergeWithDefaults:()=>ns,normalizeContent:()=>Go,pluginRegistry:()=>Fn,renderComponentDirective:()=>os,renderLoadingIndicatorWithFallback:()=>As,validateImageFile:()=>si});module.exports=_i(Ia);var jo=require("marked"),qi=e=>{if(e)return e},Pn=e=>{var o,s;let n=e==null?void 0:e.markedOptions,r=new jo.Marked({gfm:(o=n==null?void 0:n.gfm)!=null?o:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),t=qi(e==null?void 0:e.renderer);return t&&r.use({renderer:t}),i=>r.parse(i)},Hn=e=>e?Pn({markedOptions:e.options,renderer:e.renderer}):Pn(),Ui=Pn(),ws=e=>Ui(e),Un=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Do=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),No=e=>`%%FORM_PLACEHOLDER_${e}%%`,_o=(e,n)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=No(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,o)=>{let s=No(n.length);return n.push({token:s,type:o}),s}),r},qo=e=>{let n=Hn(e);return r=>{let t=[],o=_o(r,t),s=n(o);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${Do(a)}"></div>`;s=s.replace(d,f)}),s}},Uo=e=>{let n=[],r=_o(e,n),t=ws(r);return n.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Do(s)}"></div>`;t=t.replace(i,d)}),t};var Yt=require("partial-json"),zn=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ys=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)}},zi=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),r=(a=e.startedAt)!=null?a:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},zo=e=>e.status==="complete"?zi(e):e.status==="pending"?"Waiting":"",Ji=e=>{var o,s,i;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((i=(s=e.startedAt)!=null?s:e.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Jo=e=>e.status==="complete"?Ji(e):"Using tool...",Yi=()=>{let e=null,n=0,r=t=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=t.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let 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()=>{}}},Jn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Yn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Kn=()=>{var n;let e=Ji();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)}},Vn=()=>{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,Ut.parse)(o,Ut.STR|Ut.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?zn(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=zn(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Jr=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?zn(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?zn(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,Ut.parse)(s,Ut.STR|Ut.OBJ),c=r(a);c!==null&&(n=c)}catch{}return o=s.length,{text:n||"",raw:s}},close:()=>{}}},Xn=()=>{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 Yi="https://api.runtype.com/v1/dispatch",Yr="https://api.runtype.com",Kr=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 Ki(e){switch(e){case"json":return Vn;case"regex-json":return Kn;case"xml":return Xn;case"plain":default:return Yn}}var en=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=n.apiUrl)!=null?o:Yi,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Ki(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$/,""))||Yr;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$/,""))||Yr}/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 c=await this.initSession();if(new Date>=new Date(c.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:c.sessionId,messages:n.messages.filter(Kr).map(w=>{var y,M,E;return{id:w.id,role:w.role,content:(E=(M=(y=w.contentParts)!=null?y:w.llmContent)!=null?M:w.rawContent)!=null?E: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 M=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:M}),M}if(m.status===429){let M=new Error(w.hint||"Message limit reached for this session.");throw o({type:"error",error:M}),M}let y=new Error(w.error||"Failed to send message");throw o({type:"error",error:y}),y}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(c){let u=c instanceof Error?c:new Error(String(c));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 c=a instanceof Error?a:new Error(String(a));throw o({type:"error",error:c}),c}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(Kr).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 c={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=c,r(c),c};if(i.text!==void 0){let c=a();c.content+=i.text,r(c)}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 se,oe,Te,Ue,vt,Q,j,pt,bt,Ct,$t,Ot,D,ye,rt,it,Ve,at,_t,Nt,jt,R,ze,he,Ze,fe,V,re,Xe,lt,St,Lt,Pt,We,et,kt,At,ct,b,xe,$e,gt,tt,mt,ht,Ht,Vt,Xt,$n,On,yn,rn,Me,vn,bn,qt;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),c=0,u=()=>a+c++,f=I=>{let ue=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,Ce=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,Le=I.tools?I.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...I,reasoning:ue,toolCall:Ce,tools:Le}},p=I=>{o({type:"message",message:f(I)})},m=null,w={current:null},y=new Map,M=new Map,E={lastId:null,byStep:new Map},v={lastId:null,byCall:new Map},W=I=>{if(I==null)return null;try{return String(I)}catch{return null}},z=I=>{var ue,Ce,Le,Pe,nt;return W((nt=(Pe=(Le=(Ce=(ue=I.stepId)!=null?ue:I.step_id)!=null?Ce:I.step)!=null?Le:I.parentId)!=null?Pe:I.flowStepId)!=null?nt:I.flow_step_id)},h=I=>{var ue,Ce,Le,Pe,nt,Oe,F;return W((F=(Oe=(nt=(Pe=(Le=(Ce=(ue=I.callId)!=null?ue:I.call_id)!=null?Ce:I.requestId)!=null?Le:I.request_id)!=null?Pe:I.toolCallId)!=null?nt:I.tool_call_id)!=null?Oe:I.stepId)!=null?F:I.step_id)},O=()=>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),A=(I,ue)=>{E.lastId=ue,I&&E.byStep.set(I,ue)},L=(I,ue)=>{var nt;let Ce=(nt=I.reasoningId)!=null?nt:I.id,Le=z(I);if(Ce){let Oe=String(Ce);return A(Le,Oe),Oe}if(Le){let Oe=E.byStep.get(Le);if(Oe)return E.lastId=Oe,Oe}if(E.lastId&&!ue)return E.lastId;if(!ue)return null;let Pe=`reason-${u()}`;return A(Le,Pe),Pe},U=I=>{let ue=y.get(I);if(ue)return ue;let Ce={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:I,status:"streaming",chunks:[]}};return y.set(I,Ce),p(Ce),Ce},_=(I,ue)=>{v.lastId=ue,I&&v.byCall.set(I,ue)},Z=(I,ue)=>{var nt;let Ce=(nt=I.toolId)!=null?nt:I.id,Le=h(I);if(Ce){let Oe=String(Ce);return _(Le,Oe),Oe}if(Le){let Oe=v.byCall.get(Le);if(Oe)return v.lastId=Oe,Oe}if(v.lastId&&!ue)return v.lastId;if(!ue)return null;let Pe=`tool-${u()}`;return _(Le,Pe),Pe},ie=I=>{let ue=M.get(I);if(ue)return ue;let Ce={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:I,status:"pending"}};return M.set(I,Ce),p(Ce),Ce},J=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let ue=Number(I);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Ce=Date.parse(I);if(!Number.isNaN(Ce))return Ce}return Date.now()},we=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},B=new Map,N=new Map;for(;;){let{done:I,value:ue}=await r.read();if(I)break;i+=s.decode(ue,{stream:!0});let Ce=i.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},Jn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Yn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Kn=()=>{var n;let e=Yi();return{processChunk:async r=>{let t=r.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Vn=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e!==null||e===""?{text:e||"",raw:r}:null;try{let o=(0,Yt.parse)(r,Yt.STR|Yt.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?zn(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=zn(o.text)))}catch{}return n=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Yo=e=>{let n=null,r=0,o=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?zn(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?zn(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let a=(0,Yt.parse)(s,Yt.STR|Yt.OBJ),d=o(a);d!==null&&(n=d)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Xn=()=>{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 Ki="https://api.runtype.com/v1/dispatch",Ko="https://api.runtype.com",Vo=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 Vi(e){switch(e){case"json":return Vn;case"regex-json":return Kn;case"xml":return Xn;case"plain":default:return Yn}}var nn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,t,o;this.apiUrl=(r=n.apiUrl)!=null?r:Ki,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Vi(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(n){var t;let r=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ko;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(r=(n=this.config).onSessionInit)==null||r.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ko}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"csat",rating:n,comment:r})}async submitNPSFeedback(n,r){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:t.sessionId,type:"nps",rating:n,comment:r})}async dispatch(n,r){return this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let w=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:w}),w}let 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(Vo).map(w=>{var A,b,T;return{id:w.id,role:w.role,content:(T=(b=(A=w.contentParts)!=null?A:w.llmContent)!=null?b:w.rawContent)!=null?T: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 b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}if(m.status===429){let b=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let A=new Error(w.error||"Failed to send message");throw r({type:"error",error:A}),A}if(!m.body){let w=new Error("No response body received");throw r({type:"error",error:w}),w}r({type:"status",status:"connected"});try{await this.streamResponse(m.body,r,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&r({type:"error",error:u}),u}}async dispatchProxy(n,r){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async buildPayload(n){let t={messages:n.slice().filter(Vo).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(t.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...t},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return t}async handleCustomSSEEvent(n,r,t,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(t.current&&(t.current.streaming=!1,o(t.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,r,t){var oe,ie,Le,Ye,bt,Q,D,gt,Ct,xt,Ot,Nt,_,Se,it,at,Xe,lt,zt,jt,Dt,R,Ke,ye,tt,ve,G,ae,Ge,dt,At,Wt,It,Pe,nt,Lt,Tt,ct,v,Te,je,mt,st,ht,ft,Pt,Zt,en,Nn,jn,Cn,dn,ke,xn,Sn,Jt;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=H=>{let ge=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,Me=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,He=H.tools?H.tools.map(Be=>({...Be,chunks:Be.chunks?[...Be.chunks]:void 0})):void 0;return{...H,reasoning:ge,toolCall:Me,tools:He}},p=H=>{r({type:"message",message:f(H)})},m=null,w={current:null},A=new Map,b=new Map,T={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},L=H=>{if(H==null)return null;try{return String(H)}catch{return null}},U=H=>{var ge,Me,He,Be,rt;return L((rt=(Be=(He=(Me=(ge=H.stepId)!=null?ge:H.step_id)!=null?Me:H.step)!=null?He:H.parentId)!=null?Be:H.flowStepId)!=null?rt:H.flow_step_id)},h=H=>{var ge,Me,He,Be,rt,De,F;return L((F=(De=(rt=(Be=(He=(Me=(ge=H.callId)!=null?ge:H.call_id)!=null?Me:H.requestId)!=null?He:H.request_id)!=null?Be:H.toolCallId)!=null?rt:H.tool_call_id)!=null?De:H.stepId)!=null?F:H.step_id)},O=()=>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),M=(H,ge)=>{T.lastId=ge,H&&T.byStep.set(H,ge)},W=(H,ge)=>{var rt;let Me=(rt=H.reasoningId)!=null?rt:H.id,He=U(H);if(Me){let De=String(Me);return M(He,De),De}if(He){let De=T.byStep.get(He);if(De)return T.lastId=De,De}if(T.lastId&&!ge)return T.lastId;if(!ge)return null;let Be=`reason-${u()}`;return M(He,Be),Be},V=H=>{let ge=A.get(H);if(ge)return ge;let Me={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:H,status:"streaming",chunks:[]}};return A.set(H,Me),p(Me),Me},$=(H,ge)=>{y.lastId=ge,H&&y.byCall.set(H,ge)},Z=(H,ge)=>{var rt;let Me=(rt=H.toolId)!=null?rt:H.id,He=h(H);if(Me){let De=String(Me);return $(He,De),De}if(He){let De=y.byCall.get(He);if(De)return y.lastId=De,De}if(y.lastId&&!ge)return y.lastId;if(!ge)return null;let Be=`tool-${u()}`;return $(He,Be),Be},le=H=>{let ge=b.get(H);if(ge)return ge;let Me={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:H,status:"pending"}};return b.set(H,Me),p(Me),Me},z=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let ge=Number(H);if(!Number.isNaN(ge)&&Number.isFinite(ge))return ge;let Me=Date.parse(H);if(!Number.isNaN(Me))return Me}return Date.now()},xe=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},B=new Map,N=new Map;for(;;){let{done:H,value:ge}=await o.read();if(H)break;i+=s.decode(ge,{stream:!0});let Me=i.split(`
|
|
5
5
|
|
|
6
|
-
`);i=(
|
|
7
|
-
`),nt="message",Oe="";for(let ee of Pe)ee.startsWith("event:")?nt=ee.replace("event:","").trim():ee.startsWith("data:")&&(Oe+=ee.replace("data:","").trim());if(!Oe)continue;let F;try{F=JSON.parse(Oe)}catch(ee){o({type:"error",error:ee instanceof Error?ee:new Error("Failed to parse chat stream payload")});continue}let It=nt!=="message"?nt:(oe=F.type)!=null?oe:"message";if(this.parseSSEEvent){w.current=m;let ee=await this.handleCustomSSEEvent(F,o,w,p,u);if(w.current&&!m&&(m=w.current),ee)continue}if(It==="reason_start"){let ee=(Te=L(F,!0))!=null?Te:`reason-${u()}`,H=U(ee);H.reasoning=(Ue=H.reasoning)!=null?Ue:{id:ee,status:"streaming",chunks:[]},H.reasoning.startedAt=(Q=H.reasoning.startedAt)!=null?Q:J((vt=F.startedAt)!=null?vt:F.timestamp),H.reasoning.completedAt=void 0,H.reasoning.durationMs=void 0,H.streaming=!0,H.reasoning.status="streaming",p(H)}else if(It==="reason_chunk"){let ee=(pt=(j=L(F,!1))!=null?j:L(F,!0))!=null?pt:`reason-${u()}`,H=U(ee);H.reasoning=(bt=H.reasoning)!=null?bt:{id:ee,status:"streaming",chunks:[]},H.reasoning.startedAt=($t=H.reasoning.startedAt)!=null?$t:J((Ct=F.startedAt)!=null?Ct:F.timestamp);let C=(ye=(D=(Ot=F.reasoningText)!=null?Ot:F.text)!=null?D:F.delta)!=null?ye:"";if(C&&F.hidden!==!0&&H.reasoning.chunks.push(String(C)),H.reasoning.status=F.done?"complete":"streaming",F.done){H.reasoning.completedAt=J((rt=F.completedAt)!=null?rt:F.timestamp);let Y=(it=H.reasoning.startedAt)!=null?it:Date.now();H.reasoning.durationMs=Math.max(0,((Ve=H.reasoning.completedAt)!=null?Ve:Date.now())-Y)}H.streaming=H.reasoning.status!=="complete",p(H)}else if(It==="reason_complete"){let ee=(_t=(at=L(F,!1))!=null?at:L(F,!0))!=null?_t:`reason-${u()}`,H=y.get(ee);if(H!=null&&H.reasoning){H.reasoning.status="complete",H.reasoning.completedAt=J((Nt=F.completedAt)!=null?Nt:F.timestamp);let Y=(jt=H.reasoning.startedAt)!=null?jt:Date.now();H.reasoning.durationMs=Math.max(0,((R=H.reasoning.completedAt)!=null?R:Date.now())-Y),H.streaming=!1,p(H)}let C=z(F);C&&E.byStep.delete(C)}else if(It==="tool_start"){let ee=(ze=Z(F,!0))!=null?ze:`tool-${u()}`,H=ie(ee),C=(he=H.toolCall)!=null?he:{id:ee,status:"pending"};C.name=(Ze=F.toolName)!=null?Ze:C.name,C.status="running",F.args!==void 0&&(C.args=F.args),C.startedAt=(V=C.startedAt)!=null?V:J((fe=F.startedAt)!=null?fe:F.timestamp),C.completedAt=void 0,C.durationMs=void 0,H.toolCall=C,H.streaming=!0,p(H)}else if(It==="tool_chunk"){let ee=(Xe=(re=Z(F,!1))!=null?re:Z(F,!0))!=null?Xe:`tool-${u()}`,H=ie(ee),C=(lt=H.toolCall)!=null?lt:{id:ee,status:"running"};C.startedAt=(Lt=C.startedAt)!=null?Lt:J((St=F.startedAt)!=null?St:F.timestamp);let Y=(et=(We=(Pt=F.text)!=null?Pt:F.delta)!=null?We:F.message)!=null?et:"";Y&&(C.chunks=(kt=C.chunks)!=null?kt:[],C.chunks.push(String(Y))),C.status="running",H.toolCall=C,H.streaming=!0,p(H)}else if(It==="tool_complete"){let ee=(ct=(At=Z(F,!1))!=null?At:Z(F,!0))!=null?ct:`tool-${u()}`,H=ie(ee),C=(b=H.toolCall)!=null?b:{id:ee,status:"running"};if(C.status="complete",F.result!==void 0&&(C.result=F.result),typeof F.duration=="number"&&(C.duration=F.duration),C.completedAt=J((xe=F.completedAt)!=null?xe:F.timestamp),typeof F.duration=="number")C.durationMs=F.duration;else{let He=($e=C.startedAt)!=null?$e:Date.now();C.durationMs=Math.max(0,((gt=C.completedAt)!=null?gt:Date.now())-He)}H.toolCall=C,H.streaming=!1,p(H);let Y=h(F);Y&&v.byCall.delete(Y)}else if(It==="step_chunk"){let ee=F.stepType,H=F.executionType;if(ee==="tool"||H==="context")continue;let C=O(),Y=(Ht=(ht=(mt=(tt=F.text)!=null?tt:F.delta)!=null?mt:F.content)!=null?ht:F.chunk)!=null?Ht:"";if(Y){let Ie=((Vt=N.get(C.id))!=null?Vt:"")+Y;C.rawContent=Ie,B.has(C.id)||B.set(C.id,this.createStreamParser());let ft=B.get(C.id),pe=Ie.trim().startsWith("{")||Ie.trim().startsWith("[");if(pe&&N.set(C.id,Ie),ft.__isPlainTextParser===!0){C.content+=Y,N.delete(C.id),B.delete(C.id),C.rawContent=void 0,p(C);continue}let Be=ft.processChunk(Ie);if(Be instanceof Promise)Be.then(ae=>{var Fe;let Se=typeof ae=="string"?ae:(Fe=ae==null?void 0:ae.text)!=null?Fe:null;if(Se!==null&&Se.trim()!==""){let ce=m;ce&&ce.id===C.id&&(ce.content=Se,p(ce))}else if(!pe&&!Ie.trim().startsWith("<")){let ce=m;ce&&ce.id===C.id&&(ce.content+=Y,N.delete(ce.id),B.delete(ce.id),ce.rawContent=void 0,p(ce))}}).catch(()=>{C.content+=Y,N.delete(C.id),B.delete(C.id),C.rawContent=void 0,p(C)});else{let ae=typeof Be=="string"?Be:(Xt=Be==null?void 0:Be.text)!=null?Xt:null;ae!==null&&ae.trim()!==""?(C.content=ae,p(C)):!pe&&!Ie.trim().startsWith("<")&&(C.content+=Y,N.delete(C.id),B.delete(C.id),C.rawContent=void 0,p(C))}}if(F.isComplete){let He=(On=($n=F.result)==null?void 0:$n.response)!=null?On:C.content;if(He){let Ie=N.get(C.id),ft=Ie!=null?Ie:we(He);C.rawContent=ft;let pe=B.get(C.id),Ee=null,Be=!1;if(pe&&(Ee=pe.getExtractedText(),Ee===null&&(Ee=Jn(ft)),Ee===null)){let ae=pe.processChunk(ft);ae instanceof Promise?(Be=!0,ae.then(Se=>{var ce;let Fe=typeof Se=="string"?Se:(ce=Se==null?void 0:Se.text)!=null?ce:null;if(Fe!==null){let Qe=m;Qe&&Qe.id===C.id&&(Qe.content=Fe,Qe.streaming=!1,B.delete(Qe.id),N.delete(Qe.id),p(Qe))}})):Ee=typeof ae=="string"?ae:(yn=ae==null?void 0:ae.text)!=null?yn:null}if(!Be){Ee!==null&&Ee.trim()!==""?C.content=Ee:N.has(C.id)||(C.content=we(He));let ae=B.get(C.id);if(ae){let Se=(rn=ae.close)==null?void 0:rn.call(ae);Se instanceof Promise&&Se.catch(()=>{}),B.delete(C.id)}N.delete(C.id),C.streaming=!1,p(C)}}}}else if(It==="step_complete"){let ee=F.stepType,H=F.executionType;if(ee==="tool"||H==="context")continue;let C=(Me=F.result)==null?void 0:Me.response,Y=O();if(C!=null){let He=B.get(Y.id),Ie=!1,ft=!1;if(He){let pe=He.getExtractedText(),Ee=N.get(Y.id),Be=Ee!=null?Ee:we(C);if(Y.rawContent=Be,pe!==null&&pe.trim()!=="")Y.content=pe,Ie=!0;else{let ae=Jn(Be);if(ae!==null)Y.content=ae,Ie=!0;else{let Se=He.processChunk(Be);if(Se instanceof Promise)ft=!0,Se.then(Fe=>{var Qe;let ce=typeof Fe=="string"?Fe:(Qe=Fe==null?void 0:Fe.text)!=null?Qe:null;if(ce!==null&&ce.trim()!==""){let wt=m;wt&&wt.id===Y.id&&(wt.content=ce,wt.streaming=!1,B.delete(wt.id),N.delete(wt.id),p(wt))}else{let wt=He.getExtractedText(),Bt=m;Bt&&Bt.id===Y.id&&(wt!==null&&wt.trim()!==""?Bt.content=wt:N.has(Bt.id)||(Bt.content=we(C)),Bt.streaming=!1,B.delete(Bt.id),N.delete(Bt.id),p(Bt))}});else{let Fe=typeof Se=="string"?Se:(vn=Se==null?void 0:Se.text)!=null?vn:null;if(Fe!==null&&Fe.trim()!=="")Y.content=Fe,Ie=!0;else{let ce=He.getExtractedText();ce!==null&&ce.trim()!==""&&(Y.content=ce,Ie=!0)}}}}}if(!ft){if(!Y.rawContent){let pe=N.get(Y.id);Y.rawContent=pe!=null?pe:we(C)}if(!Ie&&!N.has(Y.id)&&(Y.content=we(C)),He){let pe=(bn=He.close)==null?void 0:bn.call(He);pe instanceof Promise&&pe.catch(()=>{})}B.delete(Y.id),N.delete(Y.id),Y.streaming=!1,p(Y)}}else B.delete(Y.id),N.delete(Y.id),Y.streaming=!1,p(Y)}else if(It==="flow_complete"){let ee=(qt=F.result)==null?void 0:qt.response;if(ee!=null){let H=O(),C=N.get(H.id),Y=C!=null?C:we(ee);H.rawContent=Y;let He=we(ee),Ie=B.get(H.id);if(Ie){let Ee=Jn(Y);if(Ee!==null)He=Ee;else{let Be=Ie.processChunk(Y);Be instanceof Promise&&Be.then(Se=>{var ce;let Fe=typeof Se=="string"?Se:(ce=Se==null?void 0:Se.text)!=null?ce:null;if(Fe!==null){let Qe=m;Qe&&Qe.id===H.id&&(Qe.content=Fe,Qe.streaming=!1,p(Qe))}});let ae=Ie.getExtractedText();ae!==null&&(He=ae)}}B.delete(H.id),N.delete(H.id);let ft=He!==H.content,pe=H.streaming!==!1;ft&&(H.content=He),H.streaming=!1,(ft||pe)&&p(H)}else if(m!==null){let H=m;B.delete(H.id),N.delete(H.id),H.streaming!==!1&&(H.streaming=!1,p(H))}o({type:"status",status:"idle"})}else It==="error"&&F.error&&o({type:"error",error:F.error instanceof Error?F.error:new Error(String(F.error))})}}}};function Vr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Pn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function ln(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var cn=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 en(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 en(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:c,streaming:u=!1}=n,p={id:i!=null?i:o==="user"?Pn():o==="assistant"?ln():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:c!=null?c: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=Pn(),s=ln(),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 c=[...this.messages];try{await this.client.dispatch({messages:c,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(y){let M=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!M){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(y instanceof Error?(p=(f=this.callbacks).onError)==null||p.call(f,y):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(y))))}}async continueConversation(){var r,s,i,a,c;if(this.streaming)return;(r=this.abortController)==null||r.abort();let n=ln();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):(c=(a=this.callbacks).onError)==null||c.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 c,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=(c=o.sequence)!=null?c: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 Vi=ji(require("lucide"),1),ne=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Vi[r];return s?Xi(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 Xi(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 c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([u,f])=>{u!=="stroke"&&c.setAttribute(u,String(f))}),r.appendChild(c)}}}),r}function Xr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Gr(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Qr(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Zr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Gn(e){return{type:"text",text:e}}function ei(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 ti(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 ni(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 si=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Gi=["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"],Kt=[...si,...Gi];function Qi(e){return si.includes(e)||e.startsWith("image/")}function Qn(e){return Qi(e.type)}async function oi(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Qn(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 ri(e,n=Kt,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 ii(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 Zn={allowedTypes:Kt,maxFileSize:10*1024*1024,maxFiles:4};function ea(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ta(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 tn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var o,t,r;this.config={allowedTypes:(o=n.allowedTypes)!=null?o:Zn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Zn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Zn.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:Zn.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,c,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=ri(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 oi(f),w=Qn(f)?URL.createObjectURL(f):null,y={id:ea(),file:f,previewUrl:w,contentPart:m};this.attachments.push(y),this.renderPreview(y)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(u=(c=this.config).onAttachmentsChange)==null||u.call(c,this.getAttachments())}removeAttachment(n){var s,i,a;let o=this.attachments.findIndex(c=>c.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=Qn(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=ta(n.file.type),c=ne(a,20,"var(--cw-muted, #6b7280)",1.5);c&&i.appendChild(c);let u=g("span");u.textContent=ii(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=ne("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 vs=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},na=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"||vs()==="dark"?t:o},ai=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(vs())});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(vs());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())}},es=(e,n)=>{let o=na(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 li=require("idiomorph"),ci=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;li.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 ut={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Ft={"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 Hn=(e,n)=>{let o=g("button");o.type="button",o.innerHTML=`
|
|
6
|
+
`);i=(oe=Me.pop())!=null?oe:"";for(let He of Me){let Be=He.split(`
|
|
7
|
+
`),rt="message",De="";for(let ne of Be)ne.startsWith("event:")?rt=ne.replace("event:","").trim():ne.startsWith("data:")&&(De+=ne.replace("data:","").trim());if(!De)continue;let F;try{F=JSON.parse(De)}catch(ne){r({type:"error",error:ne instanceof Error?ne:new Error("Failed to parse chat stream payload")});continue}let Ht=rt!=="message"?rt:(ie=F.type)!=null?ie:"message";if(this.parseSSEEvent){w.current=m;let ne=await this.handleCustomSSEEvent(F,r,w,p,u);if(w.current&&!m&&(m=w.current),ne)continue}if(Ht==="reason_start"){let ne=(Le=W(F,!0))!=null?Le:`reason-${u()}`,P=V(ne);P.reasoning=(Ye=P.reasoning)!=null?Ye:{id:ne,status:"streaming",chunks:[]},P.reasoning.startedAt=(Q=P.reasoning.startedAt)!=null?Q:z((bt=F.startedAt)!=null?bt:F.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",p(P)}else if(Ht==="reason_chunk"){let ne=(gt=(D=W(F,!1))!=null?D:W(F,!0))!=null?gt:`reason-${u()}`,P=V(ne);P.reasoning=(Ct=P.reasoning)!=null?Ct:{id:ne,status:"streaming",chunks:[]},P.reasoning.startedAt=(Ot=P.reasoning.startedAt)!=null?Ot:z((xt=F.startedAt)!=null?xt:F.timestamp);let C=(Se=(_=(Nt=F.reasoningText)!=null?Nt:F.text)!=null?_:F.delta)!=null?Se:"";if(C&&F.hidden!==!0&&P.reasoning.chunks.push(String(C)),P.reasoning.status=F.done?"complete":"streaming",F.done){P.reasoning.completedAt=z((it=F.completedAt)!=null?it:F.timestamp);let J=(at=P.reasoning.startedAt)!=null?at:Date.now();P.reasoning.durationMs=Math.max(0,((Xe=P.reasoning.completedAt)!=null?Xe:Date.now())-J)}P.streaming=P.reasoning.status!=="complete",p(P)}else if(Ht==="reason_complete"){let ne=(zt=(lt=W(F,!1))!=null?lt:W(F,!0))!=null?zt:`reason-${u()}`,P=A.get(ne);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=z((jt=F.completedAt)!=null?jt:F.timestamp);let J=(Dt=P.reasoning.startedAt)!=null?Dt:Date.now();P.reasoning.durationMs=Math.max(0,((R=P.reasoning.completedAt)!=null?R:Date.now())-J),P.streaming=!1,p(P)}let C=U(F);C&&T.byStep.delete(C)}else if(Ht==="tool_start"){let ne=(Ke=Z(F,!0))!=null?Ke:`tool-${u()}`,P=le(ne),C=(ye=P.toolCall)!=null?ye:{id:ne,status:"pending"};C.name=(tt=F.toolName)!=null?tt:C.name,C.status="running",F.args!==void 0&&(C.args=F.args),C.startedAt=(G=C.startedAt)!=null?G:z((ve=F.startedAt)!=null?ve:F.timestamp),C.completedAt=void 0,C.durationMs=void 0,P.toolCall=C,P.streaming=!0,p(P)}else if(Ht==="tool_chunk"){let ne=(Ge=(ae=Z(F,!1))!=null?ae:Z(F,!0))!=null?Ge:`tool-${u()}`,P=le(ne),C=(dt=P.toolCall)!=null?dt:{id:ne,status:"running"};C.startedAt=(Wt=C.startedAt)!=null?Wt:z((At=F.startedAt)!=null?At:F.timestamp);let J=(nt=(Pe=(It=F.text)!=null?It:F.delta)!=null?Pe:F.message)!=null?nt:"";J&&(C.chunks=(Lt=C.chunks)!=null?Lt:[],C.chunks.push(String(J))),C.status="running",P.toolCall=C,P.streaming=!0,p(P)}else if(Ht==="tool_complete"){let ne=(ct=(Tt=Z(F,!1))!=null?Tt:Z(F,!0))!=null?ct:`tool-${u()}`,P=le(ne),C=(v=P.toolCall)!=null?v:{id:ne,status:"running"};if(C.status="complete",F.result!==void 0&&(C.result=F.result),typeof F.duration=="number"&&(C.duration=F.duration),C.completedAt=z((Te=F.completedAt)!=null?Te:F.timestamp),typeof F.duration=="number")C.durationMs=F.duration;else{let Re=(je=C.startedAt)!=null?je:Date.now();C.durationMs=Math.max(0,((mt=C.completedAt)!=null?mt:Date.now())-Re)}P.toolCall=C,P.streaming=!1,p(P);let J=h(F);J&&y.byCall.delete(J)}else if(Ht==="step_chunk"){let ne=F.stepType,P=F.executionType;if(ne==="tool"||P==="context")continue;let C=O(),J=(Pt=(ft=(ht=(st=F.text)!=null?st:F.delta)!=null?ht:F.content)!=null?ft:F.chunk)!=null?Pt:"";if(J){let Fe=((Zt=N.get(C.id))!=null?Zt:"")+J;C.rawContent=Fe,B.has(C.id)||B.set(C.id,this.createStreamParser());let wt=B.get(C.id),he=Fe.trim().startsWith("{")||Fe.trim().startsWith("[");if(he&&N.set(C.id,Fe),wt.__isPlainTextParser===!0){C.content+=J,N.delete(C.id),B.delete(C.id),C.rawContent=void 0,p(C);continue}let $e=wt.processChunk(Fe);if($e instanceof Promise)$e.then(de=>{var Ne;let Ee=typeof de=="string"?de:(Ne=de==null?void 0:de.text)!=null?Ne:null;if(Ee!==null&&Ee.trim()!==""){let ue=m;ue&&ue.id===C.id&&(ue.content=Ee,p(ue))}else if(!he&&!Fe.trim().startsWith("<")){let ue=m;ue&&ue.id===C.id&&(ue.content+=J,N.delete(ue.id),B.delete(ue.id),ue.rawContent=void 0,p(ue))}}).catch(()=>{C.content+=J,N.delete(C.id),B.delete(C.id),C.rawContent=void 0,p(C)});else{let de=typeof $e=="string"?$e:(en=$e==null?void 0:$e.text)!=null?en:null;de!==null&&de.trim()!==""?(C.content=de,p(C)):!he&&!Fe.trim().startsWith("<")&&(C.content+=J,N.delete(C.id),B.delete(C.id),C.rawContent=void 0,p(C))}}if(F.isComplete){let Re=(jn=(Nn=F.result)==null?void 0:Nn.response)!=null?jn:C.content;if(Re){let Fe=N.get(C.id),wt=Fe!=null?Fe:xe(Re);C.rawContent=wt;let he=B.get(C.id),We=null,$e=!1;if(he&&(We=he.getExtractedText(),We===null&&(We=Jn(wt)),We===null)){let de=he.processChunk(wt);de instanceof Promise?($e=!0,de.then(Ee=>{var ue;let Ne=typeof Ee=="string"?Ee:(ue=Ee==null?void 0:Ee.text)!=null?ue:null;if(Ne!==null){let et=m;et&&et.id===C.id&&(et.content=Ne,et.streaming=!1,B.delete(et.id),N.delete(et.id),p(et))}})):We=typeof de=="string"?de:(Cn=de==null?void 0:de.text)!=null?Cn:null}if(!$e){We!==null&&We.trim()!==""?C.content=We:N.has(C.id)||(C.content=xe(Re));let de=B.get(C.id);if(de){let Ee=(dn=de.close)==null?void 0:dn.call(de);Ee instanceof Promise&&Ee.catch(()=>{}),B.delete(C.id)}N.delete(C.id),C.streaming=!1,p(C)}}}}else if(Ht==="step_complete"){let ne=F.stepType,P=F.executionType;if(ne==="tool"||P==="context")continue;let C=(ke=F.result)==null?void 0:ke.response,J=O();if(C!=null){let Re=B.get(J.id),Fe=!1,wt=!1;if(Re){let he=Re.getExtractedText(),We=N.get(J.id),$e=We!=null?We:xe(C);if(J.rawContent=$e,he!==null&&he.trim()!=="")J.content=he,Fe=!0;else{let de=Jn($e);if(de!==null)J.content=de,Fe=!0;else{let Ee=Re.processChunk($e);if(Ee instanceof Promise)wt=!0,Ee.then(Ne=>{var et;let ue=typeof Ne=="string"?Ne:(et=Ne==null?void 0:Ne.text)!=null?et:null;if(ue!==null&&ue.trim()!==""){let yt=m;yt&&yt.id===J.id&&(yt.content=ue,yt.streaming=!1,B.delete(yt.id),N.delete(yt.id),p(yt))}else{let yt=Re.getExtractedText(),Bt=m;Bt&&Bt.id===J.id&&(yt!==null&&yt.trim()!==""?Bt.content=yt:N.has(Bt.id)||(Bt.content=xe(C)),Bt.streaming=!1,B.delete(Bt.id),N.delete(Bt.id),p(Bt))}});else{let Ne=typeof Ee=="string"?Ee:(xn=Ee==null?void 0:Ee.text)!=null?xn:null;if(Ne!==null&&Ne.trim()!=="")J.content=Ne,Fe=!0;else{let ue=Re.getExtractedText();ue!==null&&ue.trim()!==""&&(J.content=ue,Fe=!0)}}}}}if(!wt){if(!J.rawContent){let he=N.get(J.id);J.rawContent=he!=null?he:xe(C)}if(!Fe&&!N.has(J.id)&&(J.content=xe(C)),Re){let he=(Sn=Re.close)==null?void 0:Sn.call(Re);he instanceof Promise&&he.catch(()=>{})}B.delete(J.id),N.delete(J.id),J.streaming=!1,p(J)}}else B.delete(J.id),N.delete(J.id),J.streaming=!1,p(J)}else if(Ht==="flow_complete"){let ne=(Jt=F.result)==null?void 0:Jt.response;if(ne!=null){let P=O(),C=N.get(P.id),J=C!=null?C:xe(ne);P.rawContent=J;let Re=xe(ne),Fe=B.get(P.id);if(Fe){let We=Jn(J);if(We!==null)Re=We;else{let $e=Fe.processChunk(J);$e instanceof Promise&&$e.then(Ee=>{var ue;let Ne=typeof Ee=="string"?Ee:(ue=Ee==null?void 0:Ee.text)!=null?ue:null;if(Ne!==null){let et=m;et&&et.id===P.id&&(et.content=Ne,et.streaming=!1,p(et))}});let de=Fe.getExtractedText();de!==null&&(Re=de)}}B.delete(P.id),N.delete(P.id);let wt=Re!==P.content,he=P.streaming!==!1;wt&&(P.content=Re),P.streaming=!1,(wt||he)&&p(P)}else if(m!==null){let P=m;B.delete(P.id),N.delete(P.id),P.streaming!==!1&&(P.streaming=!1,p(P))}r({type:"status",status:"idle"})}else Ht==="error"&&F.error&&r({type:"error",error:F.error instanceof Error?F.error:new Error(String(F.error))})}}}};function Xo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Bn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function un(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var pn=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=n=>{var r,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=(r=this.callbacks).onError)==null||t.call(r,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new nn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(r=(n=this.callbacks).onError)==null||r.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){this.config={...this.config,...n},this.client=new nn(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:t,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:u=!1}=n,p={id:i!=null?i:r==="user"?Bn():r==="assistant"?un():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:u,...o!==void 0&&{llmContent:o},...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,r){var u,f,p,m,w;let t=n.trim();if(!t&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(u=this.abortController)==null||u.abort();let o=Bn(),s=un(),i={id:o,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(A){let b=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));if(!b){let T={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(T)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(A instanceof Error?(p=(f=this.callbacks).onError)==null||p.call(f,A):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(A))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=un();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n},this.handleEvent)}catch(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 r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var o;return{...t,streaming:!1,sequence:(o=t.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),t=this.messages.findIndex(o=>o.id===r.id);if(t===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===t?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((r,t)=>{var d,u;let o=new Date(r.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(u=t.sequence)!=null?u:0;return i!==a?i-a:r.id.localeCompare(t.id)})}};var g=(e,n)=>{let r=document.createElement(e);return n&&(r.className=n),r};var Xi=Di(require("lucide"),1),re=(e,n=24,r="currentColor",t=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Xi[o];return s?Gi(s,n,r,t):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Gi(e,n,r,t){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(t)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([u,f])=>{u!=="stroke"&&d.setAttribute(u,String(f))}),o.appendChild(d)}}}),o}function Go(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Qo(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Zo(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function ei(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Gn(e){return{type:"text",text:e}}function ti(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 ni(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function si(e,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var ri=["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"],Qt=[...ri,...Qi];function Zi(e){return ri.includes(e)||e.startsWith("image/")}function Qn(e){return Zi(e.type)}async function oi(e){return new Promise((n,r)=>{let t=new FileReader;t.onload=()=>{let o=t.result;Qn(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},t.onerror=()=>r(new Error("Failed to read file")),t.readAsDataURL(e)})}function ii(e,n=Qt,r=10*1024*1024){return n.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function ea(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function ai(e,n){let r=ea(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var Zn={allowedTypes:Qt,maxFileSize:10*1024*1024,maxFiles:4};function ta(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function na(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 sn=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,t,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Zn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Zn.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Zn.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:Zn.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,o,s,i,a,d,u;if(!n||n.length===0)return;let r=Array.from(n);for(let f of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,f,"count");continue}let p=ii(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 oi(f),w=Qn(f)?URL.createObjectURL(f):null,A={id:ta(),file:f,previewUrl:w,contentPart:m};this.attachments.push(A),this.renderPreview(A)}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 r=this.attachments.findIndex(d=>d.id===n);if(r===-1)return;let t=this.attachments[r];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=Qn(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",r&&n.previewUrl){let i=g("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",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=na(n.file.type),d=re(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=g("span");u.textContent=ai(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 o=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=re("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(o),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:r})}};var vs=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},sa=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",r=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||vs()==="dark"?t:r},li=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(vs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(vs());r.addEventListener?(r.addEventListener("change",t),n.push(()=>r.removeEventListener("change",t))):r.addListener&&(r.addListener(t),n.push(()=>r.removeListener(t)))}return()=>{n.forEach(r=>r())}},es=(e,n)=>{let r=sa(n);Object.entries(r).forEach(([t,o])=>{if(o==null||o==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(o))})};var di=require("idiomorph"),ci=(e,n,r={})=>{let{preserveTypingAnimation:t=!0}=r;di.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&t&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var $t={"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 Rn=(e,n)=>{let r=g("button");r.type="button",r.innerHTML=`
|
|
8
8
|
<span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
9
9
|
<img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
|
|
@@ -12,16 +12,16 @@
|
|
|
12
12
|
<span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
15
|
-
`,o.addEventListener("click",n);let t=s=>{var v,W,z,h,O,A,L,U,_,Z,ie,J;let i=(v=s.launcher)!=null?v:{},a=o.querySelector("[data-role='launcher-title']");a&&(a.textContent=(W=i.title)!=null?W:"Chat Assistant");let c=o.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(z=i.subtitle)!=null?z:"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 we=(h=i.agentIconSize)!=null?h:"40px";if(f.style.height=we,f.style.width=we,f.innerHTML="",i.agentIconName){let B=parseFloat(we)||24,N=ne(i.agentIconName,B*.6,"#ffffff",2);N?(f.appendChild(N),f.style.display=""):(f.textContent=(O=i.agentIconText)!=null?O:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(A=i.agentIconText)!=null?A:"\u{1F4AC}",f.style.display="")}let p=o.querySelector("[data-role='launcher-image']");if(p){let we=(L=i.agentIconSize)!=null?L:"40px";p.style.height=we,p.style.width=we,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 we=(U=i.callToActionIconSize)!=null?U:"32px";m.style.height=we,m.style.width=we,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 B=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,B=(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 N=parseFloat(we)||24,se=Math.max(N-B,8),oe=ne(i.callToActionIconName,se,"currentColor",2);oe?m.appendChild(oe):m.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(Z=i.callToActionIconText)!=null?Z:"\u2197"}let w=i.position&&Ft[i.position]?Ft[i.position]:Ft["bottom-right"],y="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=`${y} ${w}`;let M="1px solid #e5e7eb",E="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(ie=i.border)!=null?ie:M,o.style.boxShadow=(J=i.shadow)!=null?J:E},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var zt=e=>{var Z,ie,J,we,B,N,se,oe,Te,Ue,vt,Q,j,pt,bt,Ct,$t,Ot,D,ye,rt,it,Ve,at,_t,Nt,jt,R,ze,he,Ze,fe;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=(Z=n==null?void 0:n.launcher)!=null?Z:{},s=(ie=r.headerIconSize)!=null?ie:"48px",i=(J=r.closeButtonSize)!=null?J:"32px",a=(we=r.closeButtonPlacement)!=null?we:"inline",c=(B=r.headerIconHidden)!=null?B:!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,!c)if(u){let V=parseFloat(s)||24,re=ne(u,V*.6,"#ffffff",1);re?f.replaceChildren(re):f.textContent=(se=(N=n==null?void 0:n.launcher)==null?void 0:N.agentIconText)!=null?se:"\u{1F4AC}"}else if((oe=n==null?void 0:n.launcher)!=null&&oe.iconUrl){let V=g("img");V.src=n.launcher.iconUrl,V.alt="",V.className="tvw-rounded-xl tvw-object-cover",V.style.height=s,V.style.width=s,f.replaceChildren(V)}else f.textContent=(Ue=(Te=n==null?void 0:n.launcher)==null?void 0:Te.agentIconText)!=null?Ue:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(Q=(vt=n==null?void 0:n.launcher)==null?void 0:vt.title)!=null?Q:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(pt=(j=n==null?void 0:n.launcher)==null?void 0:j.subtitle)!=null?pt:"Here to help you get answers fast",p.append(m,w),c?t.append(p):t.append(f,p);let y=(bt=r.clearChat)!=null?bt:{},M=(Ct=y.enabled)!=null?Ct:!0,E=($t=y.placement)!=null?$t:"inline",v=null,W=null;if(M){let V=(Ot=y.size)!=null?Ot:"32px",re=(D=y.iconName)!=null?D:"refresh-cw",Xe=(ye=y.iconColor)!=null?ye:"",lt=(rt=y.backgroundColor)!=null?rt:"",St=(it=y.borderWidth)!=null?it:"",Lt=(Ve=y.borderColor)!=null?Ve:"",Pt=(at=y.borderRadius)!=null?at:"",We=(_t=y.paddingX)!=null?_t:"",et=(Nt=y.paddingY)!=null?Nt:"",kt=(jt=y.tooltipText)!=null?jt:"Clear chat",At=(R=y.showTooltip)!=null?R:!0;W=g("div",E==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),E==="top-right"&&(W.style.right="48px"),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=V,v.style.width=V,v.type="button",v.setAttribute("aria-label",kt);let ct=ne(re,"20px",Xe||"",1);if(ct&&v.appendChild(ct),Xe&&(v.style.color=Xe,v.classList.remove("tvw-text-cw-muted")),lt&&(v.style.backgroundColor=lt,v.classList.remove("hover:tvw-bg-gray-100")),St||Lt){let b=St||"0px",xe=Lt||"transparent";v.style.border=`${b} solid ${xe}`,v.classList.remove("tvw-border-none")}if(Pt&&(v.style.borderRadius=Pt,v.classList.remove("tvw-rounded-full")),We?(v.style.paddingLeft=We,v.style.paddingRight=We):(v.style.paddingLeft="",v.style.paddingRight=""),et?(v.style.paddingTop=et,v.style.paddingBottom=et):(v.style.paddingTop="",v.style.paddingBottom=""),W.appendChild(v),At&&kt&&v&&W){let b=null,xe=()=>{if(b||!v)return;b=g("div","tvw-clear-chat-tooltip"),b.textContent=kt;let gt=g("div");gt.className="tvw-clear-chat-tooltip-arrow",b.appendChild(gt);let tt=v.getBoundingClientRect();b.style.position="fixed",b.style.left=`${tt.left+tt.width/2}px`,b.style.top=`${tt.top-8}px`,b.style.transform="translate(-50%, -100%)",document.body.appendChild(b)},$e=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};W.addEventListener("mouseenter",xe),W.addEventListener("mouseleave",$e),v.addEventListener("focus",xe),v.addEventListener("blur",$e),W._cleanupTooltip=()=>{$e(),W&&(W.removeEventListener("mouseenter",xe),W.removeEventListener("mouseleave",$e)),v&&(v.removeEventListener("focus",xe),v.removeEventListener("blur",$e))}}E==="inline"&&t.appendChild(W)}let z=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":M&&E==="inline"?"":"tvw-ml-auto"),h=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");h.style.height=i,h.style.width=i,h.type="button";let O=(ze=r.closeButtonTooltipText)!=null?ze:"Close chat",A=(he=r.closeButtonShowTooltip)!=null?he:!0;h.setAttribute("aria-label",O),h.style.display=o?"":"none";let L=(Ze=r.closeButtonIconName)!=null?Ze:"x",U=(fe=r.closeButtonIconText)!=null?fe:"\xD7",_=ne(L,"20px",r.closeButtonColor||"",1);if(_?h.appendChild(_):h.textContent=U,r.closeButtonColor?(h.style.color=r.closeButtonColor,h.classList.remove("tvw-text-cw-muted")):(h.style.color="",h.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(h.style.backgroundColor=r.closeButtonBackgroundColor,h.classList.remove("hover:tvw-bg-gray-100")):(h.style.backgroundColor="",h.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let V=r.closeButtonBorderWidth||"0px",re=r.closeButtonBorderColor||"transparent";h.style.border=`${V} solid ${re}`,h.classList.remove("tvw-border-none")}else h.style.border="",h.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(h.style.borderRadius=r.closeButtonBorderRadius,h.classList.remove("tvw-rounded-full")):(h.style.borderRadius="",h.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(h.style.paddingLeft=r.closeButtonPaddingX,h.style.paddingRight=r.closeButtonPaddingX):(h.style.paddingLeft="",h.style.paddingRight=""),r.closeButtonPaddingY?(h.style.paddingTop=r.closeButtonPaddingY,h.style.paddingBottom=r.closeButtonPaddingY):(h.style.paddingTop="",h.style.paddingBottom=""),z.appendChild(h),A&&O){let V=null,re=()=>{if(V)return;V=g("div","tvw-clear-chat-tooltip"),V.textContent=O;let lt=g("div");lt.className="tvw-clear-chat-tooltip-arrow",V.appendChild(lt);let St=h.getBoundingClientRect();V.style.position="fixed",V.style.left=`${St.left+St.width/2}px`,V.style.top=`${St.top-8}px`,V.style.transform="translate(-50%, -100%)",document.body.appendChild(V)},Xe=()=>{V&&V.parentNode&&(V.parentNode.removeChild(V),V=null)};z.addEventListener("mouseenter",re),z.addEventListener("mouseleave",Xe),h.addEventListener("focus",re),h.addEventListener("blur",Xe),z._cleanupTooltip=()=>{Xe(),z.removeEventListener("mouseenter",re),z.removeEventListener("mouseleave",Xe),h.removeEventListener("focus",re),h.removeEventListener("blur",Xe)}}return a!=="top-right"&&t.appendChild(z),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:h,closeButtonWrapper:z,clearChatButton:v,clearChatButtonWrapper:W}},nn=(e,n,o)=>{var i,a,c,u;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(u=(c=t.clearChat)==null?void 0:c.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 bs=e=>zt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),Cs=e=>{var y,M,E,v;let{config:n,showClose:o=!0,onClose:t}=e,r=(y=n==null?void 0:n.launcher)!=null?y:{},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=(M=r.title)!=null?M:"Chat Assistant",s.appendChild(i);let a=(E=r.closeButtonSize)!=null?E:"32px",c=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=(v=r.closeButtonIconName)!=null?v:"x",p=ne(f,"20px",r.closeButtonColor||"",2);p?u.appendChild(p):u.textContent="\xD7",t&&u.addEventListener("click",t),c.appendChild(u),s.appendChild(c);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:c,clearChatButton:null,clearChatButtonWrapper:null}},xs=e=>{var h,O,A,L,U,_,Z,ie;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(h=n==null?void 0:n.launcher)!=null?h:{},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"),c=(O=s.headerIconSize)!=null?O:"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=c,u.style.width=c;let f=s.headerIconName;if(f){let J=parseFloat(c)||24,we=ne(f,J*.5,"#ffffff",2);we?u.replaceChildren(we):u.textContent=(A=s.agentIconText)!=null?A:"\u{1F4AC}"}else if(s.iconUrl){let J=g("img");J.src=s.iconUrl,J.alt="",J.className="tvw-rounded-xl tvw-object-cover",J.style.height=c,J.style.width=c,u.replaceChildren(J)}else u.textContent=(L=s.agentIconText)!=null?L:"\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=(U=s.title)!=null?U:"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 y=(Z=s.closeButtonSize)!=null?Z:"32px",M=g("div",""),E=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");E.style.height=y,E.style.width=y,E.type="button",E.setAttribute("aria-label","Close chat"),E.style.display=o?"":"none";let v=(ie=s.closeButtonIconName)!=null?ie:"x",W=ne(v,"20px",s.closeButtonColor||"",2);W?E.appendChild(W):E.textContent="\xD7",t&&E.addEventListener("click",t),M.appendChild(E),a.appendChild(M),i.appendChild(a);let z=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return z.textContent="Online and ready to help",i.appendChild(z),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:E,closeButtonWrapper:M,clearChatButton:null,clearChatButtonWrapper:null}},ts={default:bs,minimal:Cs,expanded:xs},Ss=e=>{var n;return(n=ts[e])!=null?n:ts.default},dn=(e,n,o)=>{var i,a,c;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 y=g("div");return y.style.display="none",{header:u,iconHolder:f,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=Ss(t)({config:e,showClose:(c=(a=n==null?void 0:n.showCloseButton)!=null?a:o==null?void 0:o.showClose)!=null?c:!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 sa=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'}},un=e=>{var bt,Ct,$t,Ot,D,ye,rt,it,Ve,at,_t,Nt,jt,R,ze,he,Ze,fe,V,re,Xe,lt,St,Lt,Pt,We,et,kt,At,ct;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=(Ct=(bt=n==null?void 0:n.copy)==null?void 0:bt.inputPlaceholder)!=null?Ct:"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=(Ot=($t=n==null?void 0:n.theme)==null?void 0:$t.inputFontFamily)!=null?Ot:"sans-serif",a=(ye=(D=n==null?void 0:n.theme)==null?void 0:D.inputFontWeight)!=null?ye:"400";s.style.fontFamily=sa(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 b=Math.min(s.scrollHeight,f);s.style.height=`${b}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=(rt=n==null?void 0:n.sendButton)!=null?rt:{},w=(it=m.useIcon)!=null?it:!1,y=(Ve=m.iconText)!=null?Ve:"\u2191",M=m.iconName,E=(at=m.tooltipText)!=null?at:"Send message",v=(_t=m.showTooltip)!=null?_t:!1,W=(Nt=m.size)!=null?Nt:"40px",z=m.backgroundColor,h=m.textColor,O=g("div","tvw-send-button-wrapper"),A=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(A.type="submit",w){if(A.style.width=W,A.style.height=W,A.style.minWidth=W,A.style.minHeight=W,A.style.fontSize="18px",A.style.lineHeight="1",A.innerHTML="",M){let b=parseFloat(W)||24,xe=h&&typeof h=="string"&&h.trim()?h.trim():"currentColor",$e=ne(M,b,xe,2);$e?(A.appendChild($e),A.style.color=xe):(A.textContent=y,h?A.style.color=h:A.classList.add("tvw-text-white"))}else A.textContent=y,h?A.style.color=h:A.classList.add("tvw-text-white");z?A.style.backgroundColor=z:A.classList.add("tvw-bg-cw-primary")}else A.textContent=(R=(jt=n==null?void 0:n.copy)==null?void 0:jt.sendButtonLabel)!=null?R:"Send",h?A.style.color=h:A.classList.add("tvw-text-white");if(m.borderWidth&&(A.style.borderWidth=m.borderWidth,A.style.borderStyle="solid"),m.borderColor&&(A.style.borderColor=m.borderColor),m.paddingX?(A.style.paddingLeft=m.paddingX,A.style.paddingRight=m.paddingX):(A.style.paddingLeft="",A.style.paddingRight=""),m.paddingY?(A.style.paddingTop=m.paddingY,A.style.paddingBottom=m.paddingY):(A.style.paddingTop="",A.style.paddingBottom=""),v&&E){let b=g("div","tvw-send-button-tooltip");b.textContent=E,O.appendChild(b)}O.appendChild(A);let L=(ze=n==null?void 0:n.voiceRecognition)!=null?ze:{},U=L.enabled===!0,_=null,Z=null,ie=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(U&&ie){Z=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 b=(he=L.iconName)!=null?he:"mic",xe=(Ze=L.iconSize)!=null?Ze:W,$e=parseFloat(xe)||24,gt=(fe=L.backgroundColor)!=null?fe:z,tt=(V=L.iconColor)!=null?V:h;_.style.width=xe,_.style.height=xe,_.style.minWidth=xe,_.style.minHeight=xe,_.style.fontSize="18px",_.style.lineHeight="1";let mt=tt||"currentColor",ht=ne(b,$e,mt,1.5);ht?(_.appendChild(ht),_.style.color=mt):(_.textContent="\u{1F3A4}",_.style.color=mt),gt?_.style.backgroundColor=gt:_.classList.add("tvw-bg-cw-primary"),tt?_.style.color=tt:!tt&&!h&&_.classList.add("tvw-text-white"),L.borderWidth&&(_.style.borderWidth=L.borderWidth,_.style.borderStyle="solid"),L.borderColor&&(_.style.borderColor=L.borderColor),L.paddingX&&(_.style.paddingLeft=L.paddingX,_.style.paddingRight=L.paddingX),L.paddingY&&(_.style.paddingTop=L.paddingY,_.style.paddingBottom=L.paddingY),Z.appendChild(_);let Ht=(re=L.tooltipText)!=null?re:"Start voice recognition";if(((Xe=L.showTooltip)!=null?Xe:!1)&&Ht){let Xt=g("div","tvw-send-button-tooltip");Xt.textContent=Ht,Z.appendChild(Xt)}}let J=(lt=n==null?void 0:n.attachments)!=null?lt:{},we=J.enabled===!0,B=null,N=null,se=null,oe=null;if(we){oe=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),oe.style.display="none",se=g("input"),se.type="file",se.accept=((St=J.allowedTypes)!=null?St:Kt).join(","),se.multiple=((Lt=J.maxFiles)!=null?Lt:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),N=g("div","tvw-send-button-wrapper"),B=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),B.type="button",B.setAttribute("aria-label",(Pt=J.buttonTooltipText)!=null?Pt:"Attach file");let b=(We=J.buttonIconName)!=null?We:"paperclip",xe=W,$e=parseFloat(xe)||40,gt=Math.round($e*.6);B.style.width=xe,B.style.height=xe,B.style.minWidth=xe,B.style.minHeight=xe,B.style.fontSize="18px",B.style.lineHeight="1",B.style.backgroundColor="transparent",B.style.color="var(--cw-primary, #111827)",B.style.border="none",B.style.borderRadius="6px",B.style.transition="background-color 0.15s ease",B.addEventListener("mouseenter",()=>{B.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),B.addEventListener("mouseleave",()=>{B.style.backgroundColor="transparent"});let tt=ne(b,gt,"currentColor",1.5);tt?B.appendChild(tt):B.textContent="\u{1F4CE}",B.addEventListener("click",Ht=>{Ht.preventDefault(),se==null||se.click()}),N.appendChild(B);let mt=(et=J.buttonTooltipText)!=null?et:"Attach file",ht=g("div","tvw-send-button-tooltip");ht.textContent=mt,N.appendChild(ht)}r.addEventListener("click",b=>{b.target!==A&&b.target!==O&&b.target!==_&&b.target!==Z&&b.target!==B&&b.target!==N&&s.focus()}),oe&&(oe.style.gap="8px",r.append(oe)),se&&r.append(se),r.append(s);let Te=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Ue=g("div","tvw-flex tvw-items-center tvw-gap-2");N&&Ue.append(N);let vt=g("div","tvw-flex tvw-items-center tvw-gap-1");Z&&vt.append(Z),vt.append(O),Te.append(Ue,vt),r.append(Te);let Q=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),j=(kt=n==null?void 0:n.statusIndicator)!=null?kt:{},pt=(At=j.visible)!=null?At:!0;return Q.style.display=pt?"":"none",Q.textContent=(ct=j.idleText)!=null?ct:"Online",o.append(t,r,Q),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:A,sendButtonWrapper:O,micButton:_,micButtonWrapper:Z,statusText:Q,attachmentButton:B,attachmentButtonWrapper:N,attachmentInput:se,attachmentPreviewsContainer:oe,actionsRow:Te,leftActions:Ue,rightActions:vt}};var di=e=>{var c,u,f,p,m,w,y;if(!((u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0)){let M=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),E=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),v=(p=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?p:"100%";return M.style.width=v,E.style.width="100%",M.appendChild(E),{wrapper:M,panel:E}}let o=(m=e==null?void 0:e.launcher)!=null?m:{},t=o.position&&Ft[o.position]?Ft[o.position]:Ft["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=(y=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?y: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}},ui=(e,n=!0)=>{var w,y,M,E,v,W,z;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=((y=e==null?void 0:e.layout)==null?void 0:y.showHeader)!==!1,s=t?dn(e,t,{showClose:n}):zt({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"),c=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");c.textContent=(E=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?E:"Hello \u{1F44B}";let u=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(W=(v=e==null?void 0:e.copy)==null?void 0:v.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",a.append(c,u);let f=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let p=un({config:e}),m=((z=e==null?void 0:e.layout)==null?void 0:z.showFooter)!==!1;return r?nn(o,s,e):(s.header.style.display="none",nn(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:c,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 In=()=>{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},oa=(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},pi=(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},ra=(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},As=(e,n,o)=>{var y,M,E,v,W,z;let t=(y=n.showCopy)!=null?y:!0,r=(M=n.showUpvote)!=null?M:!0,s=(E=n.showDownvote)!=null?E:!0,i=(v=n.visibility)!=null?v:"hover",a=(W=n.align)!=null?W:"right",c=(z=n.layout)!=null?z:"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"}[c],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=(h,O,A,L)=>{let U=document.createElement("button");U.className="tvw-message-action-btn",U.setAttribute("aria-label",O),U.setAttribute("title",O),L&&U.setAttribute("data-action",L);let _=ne(h,14,"currentColor",2);return _&&U.appendChild(_),U.addEventListener("click",Z=>{Z.preventDefault(),Z.stopPropagation(),A()}),U};if(t){let h=w("copy","Copy message",()=>{let O=e.content||"";navigator.clipboard.writeText(O).then(()=>{h.classList.add("tvw-message-action-success");let A=ne("check",14,"currentColor",2);A&&(h.innerHTML="",h.appendChild(A)),setTimeout(()=>{h.classList.remove("tvw-message-action-success");let L=ne("copy",14,"currentColor",2);L&&(h.innerHTML="",h.appendChild(L))},2e3)}).catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",A)}),o!=null&&o.onCopy&&o.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");p.appendChild(h)}if(r){let h=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,h.classList.remove("tvw-message-action-active");else{let A=p.querySelector('[data-action="downvote"]');A&&A.classList.remove("tvw-message-action-active"),m="upvote",h.classList.add("tvw-message-action-active");let L={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(L),n.onFeedback&&n.onFeedback(L)}},"upvote");p.appendChild(h)}if(s){let h=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,h.classList.remove("tvw-message-action-active");else{let A=p.querySelector('[data-action="upvote"]');A&&A.classList.remove("tvw-message-action-active"),m="downvote",h.classList.add("tvw-message-action-active");let L={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(L),n.onFeedback&&n.onFeedback(L)}},"downvote");p.appendChild(h)}return p},pn=(e,n,o,t,r)=>{var z,h,O,A,L;let s=o!=null?o:{},i=(z=s.layout)!=null?z:"bubble",a=s.avatar,c=s.timestamp,u=(h=a==null?void 0:a.show)!=null?h:!1,f=(O=c==null?void 0:c.show)!=null?O:!1,p=(A=a==null?void 0:a.position)!=null?A:"left",m=(L=c==null?void 0:c.position)!=null?L:"below",w=ra(e.role,i),y=g("div",w.join(" "));y.id=`bubble-${e.id}`,y.setAttribute("data-message-id",e.id);let M=document.createElement("div");if(M.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),f&&m==="inline"&&e.createdAt){let U=pi(e,c);U.classList.add("tvw-ml-2","tvw-inline"),M.appendChild(U)}if(y.appendChild(M),f&&m==="below"&&e.createdAt){let U=pi(e,c);U.classList.add("tvw-mt-1"),y.appendChild(U)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let U=In();y.appendChild(U)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let U=As(e,t,r);y.appendChild(U)}if(!u||e.role==="system")return y;let v=g("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),W=oa(a,e.role);return p==="right"||p==="left"&&e.role==="user"?v.append(y,W):v.append(W,y),y.classList.remove("tvw-max-w-[85%]"),y.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),v},gi=(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}):pn(e,n,o,t,r)};var gn=new Set,mi=(e,n)=>{let o=gn.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 c=ne(o?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},Ts=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=gn.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=Ur(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let c=g("div","tvw-flex tvw-items-center"),f=ne(t?"chevron-up":"chevron-down",16,"currentColor",2);f?c.appendChild(f):c.textContent=t?"Hide":"Show";let p=g("div","tvw-flex tvw-items-center tvw-ml-auto");p.append(c),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(""),y=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return y.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(y),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),c.innerHTML="";let v=ne(t?"chevron-up":"chevron-down",16,"currentColor",2);v?c.appendChild(v):c.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),o.append(r,m),o};var mn=new Set,hi=(e,n,o)=>{var u;let t=mn.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"),c=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(c){c.innerHTML="";let f=r.toggleTextColor||r.headerTextColor||"currentColor",p=ne(t?"chevron-up":"chevron-down",16,f,2);p?c.appendChild(p):c.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Ms=(e,n)=>{var M;let o=e.toolCall,t=(M=n==null?void 0:n.toolCall)!=null?M:{},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=mn.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"),c=g("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(c.style.color=t.headerTextColor),c.textContent=zr(o),a.appendChild(c);let u=g("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",p=ne(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 E=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?E.style.color=t.contentTextColor:t.headerTextColor&&(E.style.color=t.headerTextColor),E.textContent=o.name,w.appendChild(E)}if(o.args!==void 0){let E=g("div","tvw-space-y-1"),v=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(v.style.color=t.labelTextColor),v.textContent="Arguments";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=ys(o.args),E.append(v,W),w.appendChild(E)}if(o.chunks&&o.chunks.length){let E=g("div","tvw-space-y-1"),v=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(v.style.color=t.labelTextColor),v.textContent="Activity";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=o.chunks.join(`
|
|
16
|
-
`),E.append(v,W),w.appendChild(E)}if(o.status==="complete"&&o.result!==void 0){let E=g("div","tvw-space-y-1"),v=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(v.style.color=t.labelTextColor),v.textContent="Result";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(W.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(W.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(W.style.color=t.codeBlockTextColor),W.textContent=ys(o.result),E.append(v,W),w.appendChild(E)}if(o.status==="complete"&&typeof o.duration=="number"){let E=g("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(E.style.color=t.contentTextColor),E.textContent=`Duration: ${o.duration}ms`,w.appendChild(E)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let E=t.toggleTextColor||t.headerTextColor||"currentColor",v=ne(s?"chevron-up":"chevron-down",16,E,2);v?u.appendChild(v):u.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var fi=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 y=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");y.type="button",y.textContent=w,y.disabled=p,a!=null&&a.fontFamily&&(y.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(y.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(y.style.paddingLeft=a.paddingX,y.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(y.style.paddingTop=a.paddingY,y.style.paddingBottom=a.paddingY),y.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(w))}),f.appendChild(y),n.push(y)}),e.appendChild(f)}}};var wi={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"}},Es=(e,n,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var y,M,E;if(s.dataset.enhanced==="true")return;let i=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let a=(M=wi[i])!=null?M:wi.init;s.classList.add("tvw-form-card","tvw-space-y-4");let c=g("div","tvw-space-y-1"),u=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=a.title,c.appendChild(u),a.description){let v=g("p","tvw-text-sm tvw-text-cw-muted");v.textContent=a.description,c.appendChild(v)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(v=>{var A,L;let W=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");W.htmlFor=`${n.id}-${i}-${v.name}`;let z=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");z.textContent=v.label,W.appendChild(z);let h=(A=v.type)!=null?A:"text",O;h==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=h),O.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",O.id=`${n.id}-${i}-${v.name}`,O.name=v.name,O.placeholder=(L=v.placeholder)!=null?L:"",v.required&&(O.required=!0),W.appendChild(O),f.appendChild(W)});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=(E=a.submitLabel)!=null?E:"Submit",p.appendChild(m),p.appendChild(w),f.appendChild(p),s.replaceChildren(c,f),f.addEventListener("submit",async v=>{var O,A;v.preventDefault();let W=(O=o.formEndpoint)!=null?O:"/form",z=new FormData(f),h={};z.forEach((L,U)=>{h[U]=L}),h.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let L=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let U=await L.json();m.textContent=(A=U.message)!=null?A:"Thanks! We'll be in touch soon.",U.success&&U.nextPrompt&&await t.sendMessage(String(U.nextPrompt))}catch(L){m.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var ks=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,c;return((a=i.priority)!=null?a:0)-((c=s.priority)!=null?c:0)})}clear(){this.plugins.forEach(n=>{var o;return(o=n.onUnregister)==null?void 0:o.call(n)}),this.plugins.clear()}},Bn=new ks;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"},Ls={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"},Re={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ws,darkTheme:Ls,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ns(e){var n,o,t,r,s,i,a,c,u,f,p,m,w,y,M,E,v,W,z;return e?{...Re,...e,theme:{...Re.theme,...e.theme},darkTheme:{...Re.darkTheme,...e.darkTheme},launcher:{...Re.launcher,...e.launcher,clearChat:{...(n=Re.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Re.copy,...e.copy},sendButton:{...Re.sendButton,...e.sendButton},statusIndicator:{...Re.statusIndicator,...e.statusIndicator},voiceRecognition:{...Re.voiceRecognition,...e.voiceRecognition},features:{...Re.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Re.suggestionChips,suggestionChipsConfig:{...Re.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Re.layout,...e.layout,header:{...(r=Re.layout)==null?void 0:r.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Re.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(u=(c=Re.layout)==null?void 0:c.messages)==null?void 0:u.avatar,...(p=(f=e.layout)==null?void 0:f.messages)==null?void 0:p.avatar},timestamp:{...(w=(m=Re.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(M=(y=e.layout)==null?void 0:y.messages)==null?void 0:M.timestamp}},slots:{...(E=Re.layout)==null?void 0:E.slots,...(v=e.layout)==null?void 0:v.slots}},markdown:{...Re.markdown,...e.markdown,options:{...(W=Re.markdown)==null?void 0:W.options,...(z=e.markdown)==null?void 0:z.options}},messageActions:{...Re.messageActions,...e.messageActions}}:Re}var yi=()=>{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(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var ia=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},aa=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},Rn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=ia(e),o=aa(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}},Ps=e=>typeof e=="string"?e:e==null?"":String(e),sn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ps(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Ps(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:Ps(o.text)}}},vi=e=>Array.isArray(e)?e.map(n=>String(n)):[],Fn=e=>{let n=new Set(vi(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(vi(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 c={action:a,message:s.message};e.emit("action:detected",c);for(let u of e.handlers)if(u)try{let f=()=>{e.emit("action:resubmit",c)},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 la=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}},ca=e=>e.map(n=>({...n,streaming:!1})),ss=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?la(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?ca(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 Hs=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)})}},hn=new Hs;var fn=require("partial-json");function da(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function ua(e,n){if(!da(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 os(){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,fn.parse)(o,fn.STR|fn.OBJ),s=ua(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function bi(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function rs(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=hn.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 Ci(){let e=os();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function is(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 as(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 pa=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ls(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:c=!0,ratingLabels:u=pa}=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 y=document.createElement("h3");y.className="tvw-feedback-title",y.textContent=t,w.appendChild(y);let M=document.createElement("p");M.className="tvw-feedback-subtitle",M.textContent=r,w.appendChild(M),m.appendChild(w);let E=document.createElement("div");E.className="tvw-feedback-rating tvw-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let v=[];for(let A=1;A<=5;A++){let L=document.createElement("button");L.type="button",L.className="tvw-feedback-rating-btn tvw-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${u[A-1]}`),L.title=u[A-1],L.dataset.rating=String(A),L.innerHTML=`
|
|
15
|
+
`,r.addEventListener("click",n);let t=s=>{var y,L,U,h,O,M,W,V,$,Z,le,z;let i=(y=s.launcher)!=null?y:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(L=i.title)!=null?L:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(U=i.subtitle)!=null?U:"Get answers fast");let u=r.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let f=r.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let xe=(h=i.agentIconSize)!=null?h:"40px";if(f.style.height=xe,f.style.width=xe,f.innerHTML="",i.agentIconName){let B=parseFloat(xe)||24,N=re(i.agentIconName,B*.6,"#ffffff",2);N?(f.appendChild(N),f.style.display=""):(f.textContent=(O=i.agentIconText)!=null?O:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(M=i.agentIconText)!=null?M:"\u{1F4AC}",f.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let xe=(W=i.agentIconSize)!=null?W:"40px";p.style.height=xe,p.style.width=xe,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(p.src=i.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let xe=(V=i.callToActionIconSize)!=null?V:"32px";m.style.height=xe,m.style.width=xe,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 B=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,B=(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 N=parseFloat(xe)||24,oe=Math.max(N-B,8),ie=re(i.callToActionIconName,oe,"currentColor",2);ie?m.appendChild(ie):m.textContent=($=i.callToActionIconText)!=null?$:"\u2197"}else m.textContent=(Z=i.callToActionIconText)!=null?Z:"\u2197"}let w=i.position&&$t[i.position]?$t[i.position]:$t["bottom-right"],A="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${A} ${w}`;let b="1px solid #e5e7eb",T="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(le=i.border)!=null?le:b,r.style.boxShadow=(z=i.shadow)!=null?z:T},o=()=>{r.removeEventListener("click",n),r.remove()};return e&&t(e),{element:r,update:t,destroy:o}};var Kt=e=>{var Z,le,z,xe,B,N,oe,ie,Le,Ye,bt,Q,D,gt,Ct,xt,Ot,Nt,_,Se,it,at,Xe,lt,zt,jt,Dt,R,Ke,ye,tt,ve;let{config:n,showClose:r=!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"),o=(Z=n==null?void 0:n.launcher)!=null?Z:{},s=(le=o.headerIconSize)!=null?le:"48px",i=(z=o.closeButtonSize)!=null?z:"32px",a=(xe=o.closeButtonPlacement)!=null?xe:"inline",d=(B=o.headerIconHidden)!=null?B:!1,u=o.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 G=parseFloat(s)||24,ae=re(u,G*.6,"#ffffff",1);ae?f.replaceChildren(ae):f.textContent=(oe=(N=n==null?void 0:n.launcher)==null?void 0:N.agentIconText)!=null?oe:"\u{1F4AC}"}else if((ie=n==null?void 0:n.launcher)!=null&&ie.iconUrl){let G=g("img");G.src=n.launcher.iconUrl,G.alt="",G.className="tvw-rounded-xl tvw-object-cover",G.style.height=s,G.style.width=s,f.replaceChildren(G)}else f.textContent=(Ye=(Le=n==null?void 0:n.launcher)==null?void 0:Le.agentIconText)!=null?Ye:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(Q=(bt=n==null?void 0:n.launcher)==null?void 0:bt.title)!=null?Q:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(gt=(D=n==null?void 0:n.launcher)==null?void 0:D.subtitle)!=null?gt:"Here to help you get answers fast",p.append(m,w),d?t.append(p):t.append(f,p);let A=(Ct=o.clearChat)!=null?Ct:{},b=(xt=A.enabled)!=null?xt:!0,T=(Ot=A.placement)!=null?Ot:"inline",y=null,L=null;if(b){let G=(Nt=A.size)!=null?Nt:"32px",ae=(_=A.iconName)!=null?_:"refresh-cw",Ge=(Se=A.iconColor)!=null?Se:"",dt=(it=A.backgroundColor)!=null?it:"",At=(at=A.borderWidth)!=null?at:"",Wt=(Xe=A.borderColor)!=null?Xe:"",It=(lt=A.borderRadius)!=null?lt:"",Pe=(zt=A.paddingX)!=null?zt:"",nt=(jt=A.paddingY)!=null?jt:"",Lt=(Dt=A.tooltipText)!=null?Dt:"Clear chat",Tt=(R=A.showTooltip)!=null?R:!0;L=g("div",T==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),T==="top-right"&&(L.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=G,y.style.width=G,y.type="button",y.setAttribute("aria-label",Lt);let ct=re(ae,"20px",Ge||"",1);if(ct&&y.appendChild(ct),Ge&&(y.style.color=Ge,y.classList.remove("tvw-text-cw-muted")),dt&&(y.style.backgroundColor=dt,y.classList.remove("hover:tvw-bg-gray-100")),At||Wt){let v=At||"0px",Te=Wt||"transparent";y.style.border=`${v} solid ${Te}`,y.classList.remove("tvw-border-none")}if(It&&(y.style.borderRadius=It,y.classList.remove("tvw-rounded-full")),Pe?(y.style.paddingLeft=Pe,y.style.paddingRight=Pe):(y.style.paddingLeft="",y.style.paddingRight=""),nt?(y.style.paddingTop=nt,y.style.paddingBottom=nt):(y.style.paddingTop="",y.style.paddingBottom=""),L.appendChild(y),Tt&&Lt&&y&&L){let v=null,Te=()=>{if(v||!y)return;v=g("div","tvw-clear-chat-tooltip"),v.textContent=Lt;let mt=g("div");mt.className="tvw-clear-chat-tooltip-arrow",v.appendChild(mt);let st=y.getBoundingClientRect();v.style.position="fixed",v.style.left=`${st.left+st.width/2}px`,v.style.top=`${st.top-8}px`,v.style.transform="translate(-50%, -100%)",document.body.appendChild(v)},je=()=>{v&&v.parentNode&&(v.parentNode.removeChild(v),v=null)};L.addEventListener("mouseenter",Te),L.addEventListener("mouseleave",je),y.addEventListener("focus",Te),y.addEventListener("blur",je),L._cleanupTooltip=()=>{je(),L&&(L.removeEventListener("mouseenter",Te),L.removeEventListener("mouseleave",je)),y&&(y.removeEventListener("focus",Te),y.removeEventListener("blur",je))}}T==="inline"&&t.appendChild(L)}let U=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":b&&T==="inline"?"":"tvw-ml-auto"),h=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");h.style.height=i,h.style.width=i,h.type="button";let O=(Ke=o.closeButtonTooltipText)!=null?Ke:"Close chat",M=(ye=o.closeButtonShowTooltip)!=null?ye:!0;h.setAttribute("aria-label",O),h.style.display=r?"":"none";let W=(tt=o.closeButtonIconName)!=null?tt:"x",V=(ve=o.closeButtonIconText)!=null?ve:"\xD7",$=re(W,"20px",o.closeButtonColor||"",1);if($?h.appendChild($):h.textContent=V,o.closeButtonColor?(h.style.color=o.closeButtonColor,h.classList.remove("tvw-text-cw-muted")):(h.style.color="",h.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(h.style.backgroundColor=o.closeButtonBackgroundColor,h.classList.remove("hover:tvw-bg-gray-100")):(h.style.backgroundColor="",h.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let G=o.closeButtonBorderWidth||"0px",ae=o.closeButtonBorderColor||"transparent";h.style.border=`${G} solid ${ae}`,h.classList.remove("tvw-border-none")}else h.style.border="",h.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(h.style.borderRadius=o.closeButtonBorderRadius,h.classList.remove("tvw-rounded-full")):(h.style.borderRadius="",h.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(h.style.paddingLeft=o.closeButtonPaddingX,h.style.paddingRight=o.closeButtonPaddingX):(h.style.paddingLeft="",h.style.paddingRight=""),o.closeButtonPaddingY?(h.style.paddingTop=o.closeButtonPaddingY,h.style.paddingBottom=o.closeButtonPaddingY):(h.style.paddingTop="",h.style.paddingBottom=""),U.appendChild(h),M&&O){let G=null,ae=()=>{if(G)return;G=g("div","tvw-clear-chat-tooltip"),G.textContent=O;let dt=g("div");dt.className="tvw-clear-chat-tooltip-arrow",G.appendChild(dt);let At=h.getBoundingClientRect();G.style.position="fixed",G.style.left=`${At.left+At.width/2}px`,G.style.top=`${At.top-8}px`,G.style.transform="translate(-50%, -100%)",document.body.appendChild(G)},Ge=()=>{G&&G.parentNode&&(G.parentNode.removeChild(G),G=null)};U.addEventListener("mouseenter",ae),U.addEventListener("mouseleave",Ge),h.addEventListener("focus",ae),h.addEventListener("blur",Ge),U._cleanupTooltip=()=>{Ge(),U.removeEventListener("mouseenter",ae),U.removeEventListener("mouseleave",Ge),h.removeEventListener("focus",ae),h.removeEventListener("blur",Ge)}}return a!=="top-right"&&t.appendChild(U),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:h,closeButtonWrapper:U,clearChatButton:y,clearChatButtonWrapper:L}},rn=(e,n,r)=>{var i,a,d,u;let t=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=t.closeButtonPlacement)!=null?a:"inline",s=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var bs=e=>Kt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),Cs=e=>{var A,b,T,y;let{config:n,showClose:r=!0,onClose:t}=e,o=(A=n==null?void 0:n.launcher)!=null?A:{},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=(b=o.title)!=null?b:"Chat Assistant",s.appendChild(i);let a=(T=o.closeButtonSize)!=null?T:"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=r?"":"none";let f=(y=o.closeButtonIconName)!=null?y:"x",p=re(f,"20px",o.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}},xs=e=>{var h,O,M,W,V,$,Z,le;let{config:n,showClose:r=!0,onClose:t,onClearChat:o}=e,s=(h=n==null?void 0:n.launcher)!=null?h:{},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=(O=s.headerIconSize)!=null?O:"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 z=parseFloat(d)||24,xe=re(f,z*.5,"#ffffff",2);xe?u.replaceChildren(xe):u.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}"}else if(s.iconUrl){let z=g("img");z.src=s.iconUrl,z.alt="",z.className="tvw-rounded-xl tvw-object-cover",z.style.height=d,z.style.width=d,u.replaceChildren(z)}else u.textContent=(W=s.agentIconText)!=null?W:"\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=(V=s.title)!=null?V:"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 A=(Z=s.closeButtonSize)!=null?Z:"32px",b=g("div",""),T=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");T.style.height=A,T.style.width=A,T.type="button",T.setAttribute("aria-label","Close chat"),T.style.display=r?"":"none";let y=(le=s.closeButtonIconName)!=null?le:"x",L=re(y,"20px",s.closeButtonColor||"",2);L?T.appendChild(L):T.textContent="\xD7",t&&T.addEventListener("click",t),b.appendChild(T),a.appendChild(b),i.appendChild(a);let U=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return U.textContent="Online and ready to help",i.appendChild(U),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:T,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},ts={default:bs,minimal:Cs,expanded:xs},Ss=e=>{var n;return(n=ts[e])!=null?n:ts.default},gn=(e,n,r)=>{var i,a,d;if(n!=null&&n.render){let u=n.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),f=g("div");f.style.display="none";let p=g("span"),m=g("span"),w=g("button");w.style.display="none";let A=g("div");return A.style.display="none",{header:u,iconHolder:f,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:A,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=Ss(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ra=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'}},mn=e=>{var Ct,xt,Ot,Nt,_,Se,it,at,Xe,lt,zt,jt,Dt,R,Ke,ye,tt,ve,G,ae,Ge,dt,At,Wt,It,Pe,nt,Lt,Tt,ct;let{config:n}=e,r=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"),o=g("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=g("textarea");s.placeholder=(xt=(Ct=n==null?void 0:n.copy)==null?void 0:Ct.inputPlaceholder)!=null?xt:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none tvw-composer-textarea",s.rows=1;let i=(Nt=(Ot=n==null?void 0:n.theme)==null?void 0:Ot.inputFontFamily)!=null?Nt:"sans-serif",a=(Se=(_=n==null?void 0:n.theme)==null?void 0:_.inputFontWeight)!=null?Se:"400";s.style.fontFamily=ra(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 v=Math.min(s.scrollHeight,f);s.style.height=`${v}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=(it=n==null?void 0:n.sendButton)!=null?it:{},w=(at=m.useIcon)!=null?at:!1,A=(Xe=m.iconText)!=null?Xe:"\u2191",b=m.iconName,T=(lt=m.tooltipText)!=null?lt:"Send message",y=(zt=m.showTooltip)!=null?zt:!1,L=(jt=m.size)!=null?jt:"40px",U=m.backgroundColor,h=m.textColor,O=g("div","tvw-send-button-wrapper"),M=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(M.type="submit",w){if(M.style.width=L,M.style.height=L,M.style.minWidth=L,M.style.minHeight=L,M.style.fontSize="18px",M.style.lineHeight="1",M.innerHTML="",b){let v=parseFloat(L)||24,Te=h&&typeof h=="string"&&h.trim()?h.trim():"currentColor",je=re(b,v,Te,2);je?(M.appendChild(je),M.style.color=Te):(M.textContent=A,h?M.style.color=h:M.classList.add("tvw-text-white"))}else M.textContent=A,h?M.style.color=h:M.classList.add("tvw-text-white");U?M.style.backgroundColor=U:M.classList.add("tvw-bg-cw-primary")}else M.textContent=(R=(Dt=n==null?void 0:n.copy)==null?void 0:Dt.sendButtonLabel)!=null?R:"Send",h?M.style.color=h:M.classList.add("tvw-text-white");if(m.borderWidth&&(M.style.borderWidth=m.borderWidth,M.style.borderStyle="solid"),m.borderColor&&(M.style.borderColor=m.borderColor),m.paddingX?(M.style.paddingLeft=m.paddingX,M.style.paddingRight=m.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),m.paddingY?(M.style.paddingTop=m.paddingY,M.style.paddingBottom=m.paddingY):(M.style.paddingTop="",M.style.paddingBottom=""),y&&T){let v=g("div","tvw-send-button-tooltip");v.textContent=T,O.appendChild(v)}O.appendChild(M);let W=(Ke=n==null?void 0:n.voiceRecognition)!=null?Ke:{},V=W.enabled===!0,$=null,Z=null,le=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(V&&le){Z=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 v=(ye=W.iconName)!=null?ye:"mic",Te=(tt=W.iconSize)!=null?tt:L,je=parseFloat(Te)||24,mt=(ve=W.backgroundColor)!=null?ve:U,st=(G=W.iconColor)!=null?G:h;$.style.width=Te,$.style.height=Te,$.style.minWidth=Te,$.style.minHeight=Te,$.style.fontSize="18px",$.style.lineHeight="1";let ht=st||"currentColor",ft=re(v,je,ht,1.5);ft?($.appendChild(ft),$.style.color=ht):($.textContent="\u{1F3A4}",$.style.color=ht),mt?$.style.backgroundColor=mt:$.classList.add("tvw-bg-cw-primary"),st?$.style.color=st:!st&&!h&&$.classList.add("tvw-text-white"),W.borderWidth&&($.style.borderWidth=W.borderWidth,$.style.borderStyle="solid"),W.borderColor&&($.style.borderColor=W.borderColor),W.paddingX&&($.style.paddingLeft=W.paddingX,$.style.paddingRight=W.paddingX),W.paddingY&&($.style.paddingTop=W.paddingY,$.style.paddingBottom=W.paddingY),Z.appendChild($);let Pt=(ae=W.tooltipText)!=null?ae:"Start voice recognition";if(((Ge=W.showTooltip)!=null?Ge:!1)&&Pt){let en=g("div","tvw-send-button-tooltip");en.textContent=Pt,Z.appendChild(en)}}let z=(dt=n==null?void 0:n.attachments)!=null?dt:{},xe=z.enabled===!0,B=null,N=null,oe=null,ie=null;if(xe){ie=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ie.style.display="none",oe=g("input"),oe.type="file",oe.accept=((At=z.allowedTypes)!=null?At:Qt).join(","),oe.multiple=((Wt=z.maxFiles)!=null?Wt:4)>1,oe.style.display="none",oe.setAttribute("aria-label","Attach files"),N=g("div","tvw-send-button-wrapper"),B=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),B.type="button",B.setAttribute("aria-label",(It=z.buttonTooltipText)!=null?It:"Attach file");let v=(Pe=z.buttonIconName)!=null?Pe:"paperclip",Te=L,je=parseFloat(Te)||40,mt=Math.round(je*.6);B.style.width=Te,B.style.height=Te,B.style.minWidth=Te,B.style.minHeight=Te,B.style.fontSize="18px",B.style.lineHeight="1",B.style.backgroundColor="transparent",B.style.color="var(--cw-primary, #111827)",B.style.border="none",B.style.borderRadius="6px",B.style.transition="background-color 0.15s ease",B.addEventListener("mouseenter",()=>{B.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),B.addEventListener("mouseleave",()=>{B.style.backgroundColor="transparent"});let st=re(v,mt,"currentColor",1.5);st?B.appendChild(st):B.textContent="\u{1F4CE}",B.addEventListener("click",Pt=>{Pt.preventDefault(),oe==null||oe.click()}),N.appendChild(B);let ht=(nt=z.buttonTooltipText)!=null?nt:"Attach file",ft=g("div","tvw-send-button-tooltip");ft.textContent=ht,N.appendChild(ft)}o.addEventListener("click",v=>{v.target!==M&&v.target!==O&&v.target!==$&&v.target!==Z&&v.target!==B&&v.target!==N&&s.focus()}),ie&&(ie.style.gap="8px",o.append(ie)),oe&&o.append(oe),o.append(s);let Le=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Ye=g("div","tvw-flex tvw-items-center tvw-gap-2");N&&Ye.append(N);let bt=g("div","tvw-flex tvw-items-center tvw-gap-1");Z&&bt.append(Z),bt.append(O),Le.append(Ye,bt),o.append(Le);let Q=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),D=(Lt=n==null?void 0:n.statusIndicator)!=null?Lt:{},gt=(Tt=D.visible)!=null?Tt:!0;return Q.style.display=gt?"":"none",Q.textContent=(ct=D.idleText)!=null?ct:"Online",r.append(t,o,Q),{footer:r,suggestions:t,composerForm:o,textarea:s,sendButton:M,sendButtonWrapper:O,micButton:$,micButtonWrapper:Z,statusText:Q,attachmentButton:B,attachmentButtonWrapper:N,attachmentInput:oe,attachmentPreviewsContainer:ie,actionsRow:Le,leftActions:Ye,rightActions:bt}};var ui=e=>{var d,u,f,p,m,w,A;if(!((u=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?u:!0)){let b=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),T=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 b.style.width=y,T.style.width="100%",b.appendChild(T),{wrapper:b,panel:T}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},t=r.position&&$t[r.position]?$t[r.position]:$t["bottom-right"],o=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=(A=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?A:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},pi=(e,n=!0)=>{var w,A,b,T,y,L,U;let r=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=e==null?void 0:e.layout)==null?void 0:w.header,o=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,s=t?gn(e,t,{showClose:n}):Kt({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=(T=(b=e==null?void 0:e.copy)==null?void 0:b.welcomeTitle)!=null?T:"Hello \u{1F44B}";let u=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(L=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?L:"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=mn({config:e}),m=((U=e==null?void 0:e.layout)==null?void 0:U.showFooter)!==!1;return o?rn(r,s,e):(s.header.style.display="none",rn(r,s,e)),r.append(i),m||(p.footer.style.display="none"),r.append(p.footer),{container:r,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 on=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(r),e.appendChild(t),e.appendChild(o),e},As=(e,n,r)=>{let t={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:on};if(n){let o=n(t);if(o!==null)return o}return on()},oa=(e,n)=>{let r=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let o=g("img");o.src=t,o.alt=n==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=t,r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=n==="user"?"U":"A",r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},gi=(e,n)=>{let r=g("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?r.textContent=n.format(t):r.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},ia=(e,n="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},Ts=(e,n,r)=>{var A,b,T,y,L,U;let t=(A=n.showCopy)!=null?A:!0,o=(b=n.showUpvote)!=null?b:!0,s=(T=n.showDownvote)!=null?T:!0,i=(y=n.visibility)!=null?y:"hover",a=(L=n.align)!=null?L:"right",d=(U=n.layout)!=null?U:"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=(h,O,M,W)=>{let V=document.createElement("button");V.className="tvw-message-action-btn",V.setAttribute("aria-label",O),V.setAttribute("title",O),W&&V.setAttribute("data-action",W);let $=re(h,14,"currentColor",2);return $&&V.appendChild($),V.addEventListener("click",Z=>{Z.preventDefault(),Z.stopPropagation(),M()}),V};if(t){let h=w("copy","Copy message",()=>{let O=e.content||"";navigator.clipboard.writeText(O).then(()=>{h.classList.add("tvw-message-action-success");let M=re("check",14,"currentColor",2);M&&(h.innerHTML="",h.appendChild(M)),setTimeout(()=>{h.classList.remove("tvw-message-action-success");let W=re("copy",14,"currentColor",2);W&&(h.innerHTML="",h.appendChild(W))},2e3)}).catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",M)}),r!=null&&r.onCopy&&r.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");p.appendChild(h)}if(o){let h=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,h.classList.remove("tvw-message-action-active");else{let M=p.querySelector('[data-action="downvote"]');M&&M.classList.remove("tvw-message-action-active"),m="upvote",h.classList.add("tvw-message-action-active");let W={type:"upvote",messageId:e.id,message:e};r!=null&&r.onFeedback&&r.onFeedback(W),n.onFeedback&&n.onFeedback(W)}},"upvote");p.appendChild(h)}if(s){let h=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,h.classList.remove("tvw-message-action-active");else{let M=p.querySelector('[data-action="upvote"]');M&&M.classList.remove("tvw-message-action-active"),m="downvote",h.classList.add("tvw-message-action-active");let W={type:"downvote",messageId:e.id,message:e};r!=null&&r.onFeedback&&r.onFeedback(W),n.onFeedback&&n.onFeedback(W)}},"downvote");p.appendChild(h)}return p},hn=(e,n,r,t,o,s)=>{var h,O,M,W,V;let i=r!=null?r:{},a=(h=i.layout)!=null?h:"bubble",d=i.avatar,u=i.timestamp,f=(O=d==null?void 0:d.show)!=null?O:!1,p=(M=u==null?void 0:u.show)!=null?M:!1,m=(W=d==null?void 0:d.position)!=null?W:"left",w=(V=u==null?void 0:u.position)!=null?V:"below",A=ia(e.role,a),b=g("div",A.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id);let T=document.createElement("div");if(T.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),p&&w==="inline"&&e.createdAt){let $=gi(e,u);$.classList.add("tvw-ml-2","tvw-inline"),T.appendChild($)}if(b.appendChild(T),p&&w==="below"&&e.createdAt){let $=gi(e,u);$.classList.add("tvw-mt-1"),b.appendChild($)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let $=As("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);$&&b.appendChild($)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let $=Ts(e,t,o);b.appendChild($)}if(!f||e.role==="system")return b;let L=g("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),U=oa(d,e.role);return m==="right"||m==="left"&&e.role==="user"?L.append(b,U):L.append(U,b),b.classList.remove("tvw-max-w-[85%]"),b.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),L},mi=(e,n,r,t,o,s)=>{let i=r!=null?r:{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):hn(e,n,r,t,o,s)};var fn=new Set,hi=(e,n)=>{let r=fn.has(e),t=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".tvw-border-t");if(!t||!o)return;t.setAttribute("aria-expanded",r?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=re(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},Ms=e=>{let n=e.reasoning,r=g("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let t=fn.has(e.id),o=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",t?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=zo(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),f=re(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),o.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(""),A=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return A.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(A),(()=>{o.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=re(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),r.append(o,m),r};var wn=new Set,fi=(e,n,r)=>{var u;let t=wn.has(e),o=(u=r==null?void 0:r.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=o.toggleTextColor||o.headerTextColor||"currentColor",p=re(t?"chevron-up":"chevron-down",16,f,2);p?d.appendChild(p):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Es=(e,n)=>{var b;let r=e.toolCall,t=(b=n==null?void 0:n.toolCall)!=null?b:{},o=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),t.backgroundColor&&(o.style.backgroundColor=t.backgroundColor),t.borderColor&&(o.style.borderColor=t.borderColor),t.borderWidth&&(o.style.borderWidth=t.borderWidth),t.borderRadius&&(o.style.borderRadius=t.borderRadius),!r)return o;let s=wn.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=Jo(r),a.appendChild(d);let u=g("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",p=re(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),r.name){let T=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?T.style.color=t.contentTextColor:t.headerTextColor&&(T.style.color=t.headerTextColor),T.textContent=r.name,w.appendChild(T)}if(r.args!==void 0){let T=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 L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(L.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(L.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(L.style.color=t.codeBlockTextColor),L.textContent=ys(r.args),T.append(y,L),w.appendChild(T)}if(r.chunks&&r.chunks.length){let T=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 L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(L.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(L.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(L.style.color=t.codeBlockTextColor),L.textContent=r.chunks.join(`
|
|
16
|
+
`),T.append(y,L),w.appendChild(T)}if(r.status==="complete"&&r.result!==void 0){let T=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 L=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");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(L.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(L.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(L.style.color=t.codeBlockTextColor),L.textContent=ys(r.result),T.append(y,L),w.appendChild(T)}if(r.status==="complete"&&typeof r.duration=="number"){let T=g("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(T.style.color=t.contentTextColor),T.textContent=`Duration: ${r.duration}ms`,w.appendChild(T)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let T=t.toggleTextColor||t.headerTextColor||"currentColor",y=re(s?"chevron-up":"chevron-down",16,T,2);y?u.appendChild(y):u.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var wi=e=>{let n=[];return{buttons:n,render:(t,o,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:o?o.getMessages():[]).some(w=>w.role==="user"))return;let f=document.createDocumentFragment(),p=o?o.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 A=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");A.type="button",A.textContent=w,A.disabled=p,a!=null&&a.fontFamily&&(A.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(A.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(A.style.paddingLeft=a.paddingX,A.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(A.style.paddingTop=a.paddingY,A.style.paddingBottom=a.paddingY),A.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),f.appendChild(A),n.push(A)}),e.appendChild(f)}}};var yi={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"}},Ls=(e,n,r,t)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var A,b,T;if(s.dataset.enhanced==="true")return;let i=(A=s.dataset.tvForm)!=null?A:"init";s.dataset.enhanced="true";let a=(b=yi[i])!=null?b:yi.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 M,W;let L=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");L.htmlFor=`${n.id}-${i}-${y.name}`;let U=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");U.textContent=y.label,L.appendChild(U);let h=(M=y.type)!=null?M:"text",O;h==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=h),O.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",O.id=`${n.id}-${i}-${y.name}`,O.name=y.name,O.placeholder=(W=y.placeholder)!=null?W:"",y.required&&(O.required=!0),L.appendChild(O),f.appendChild(L)});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=(T=a.submitLabel)!=null?T:"Submit",p.appendChild(m),p.appendChild(w),f.appendChild(p),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var O,M;y.preventDefault();let L=(O=r.formEndpoint)!=null?O:"/form",U=new FormData(f),h={};U.forEach((W,V)=>{h[V]=W}),h.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let W=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let V=await W.json();m.textContent=(M=V.message)!=null?M:"Thanks! We'll be in touch soon.",V.success&&V.nextPrompt&&await t.sendMessage(String(V.nextPrompt))}catch(W){m.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var ks=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var t;let r=this.plugins.get(n);r&&((t=r.onUnregister)==null||t.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var t,o;return((t=r.priority)!=null?t:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let t=new Set(n.map(s=>s.id));return[...r.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},Fn=new ks;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"},Is={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"},Oe={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ws,darkTheme:Is,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ns(e){var n,r,t,o,s,i,a,d,u,f,p,m,w,A,b,T,y,L,U;return e?{...Oe,...e,theme:{...Oe.theme,...e.theme},darkTheme:{...Oe.darkTheme,...e.darkTheme},launcher:{...Oe.launcher,...e.launcher,clearChat:{...(n=Oe.launcher)==null?void 0:n.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Oe.copy,...e.copy},sendButton:{...Oe.sendButton,...e.sendButton},statusIndicator:{...Oe.statusIndicator,...e.statusIndicator},voiceRecognition:{...Oe.voiceRecognition,...e.voiceRecognition},features:{...Oe.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Oe.suggestionChips,suggestionChipsConfig:{...Oe.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Oe.layout,...e.layout,header:{...(o=Oe.layout)==null?void 0:o.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Oe.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(u=(d=Oe.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=Oe.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(b=(A=e.layout)==null?void 0:A.messages)==null?void 0:b.timestamp}},slots:{...(T=Oe.layout)==null?void 0:T.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Oe.markdown,...e.markdown,options:{...(L=Oe.markdown)==null?void 0:L.options,...(U=e.markdown)==null?void 0:U.options}},messageActions:{...Oe.messageActions,...e.messageActions}}:Oe}var vi=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=e.get(o))==null||i.delete(s)};return{on:n,off:r,emit:(o,s)=>{var i;(i=e.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var aa=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},la=e=>{let n=e.trim(),r=n.indexOf("{");if(r===-1)return null;let t=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(r,o+1)}return null},$n=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=aa(e),r=la(n);if(!r)return null;let t=JSON.parse(r);if(!t||typeof t!="object"||!t.action)return null;let{action:o,...s}=t;return{type:String(o),payload:s,raw:t}}catch{return null}},Ps=e=>typeof e=="string"?e:e==null?"":String(e),an={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ps(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let r=e.payload,t=Ps(r.element);if(t&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Ps(r.text)}}},bi=e=>Array.isArray(e)?e.map(n=>String(n)):[],On=e=>{let n=new Set(bi(e.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(bi(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:r}};var da=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}},ca=e=>e.map(n=>({...n,streaming:!1})),ss=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?da(r.getItem(e)):null},save:r=>{let t=n();if(t)try{let o={...r,messages:r.messages?ca(r.messages):void 0};t.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Hs=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([r,t])=>{this.register(r,t)})}},yn=new Hs;var vn=require("partial-json");function ua(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function pa(e,n){if(!ua(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:n}}function rs(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:r=>{let t=r.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(r.length<=n)return e;try{let o=(0,vn.parse)(r,vn.STR|vn.OBJ),s=pa(o,r);s&&(e=s)}catch{}return n=r.length,e},reset:()=>{e=null,n=0}}}function Ci(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:r,message:t,onPropsUpdate:o}=n,s=yn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:r,updateProps:a=>{o&&o(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function xi(){let e=rs();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function is(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 as(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 ga=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ls(e){let{onSubmit:n,onDismiss:r,title:t="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:u=ga}=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 A=document.createElement("h3");A.className="tvw-feedback-title",A.textContent=t,w.appendChild(A);let b=document.createElement("p");b.className="tvw-feedback-subtitle",b.textContent=o,w.appendChild(b),m.appendChild(w);let T=document.createElement("div");T.className="tvw-feedback-rating tvw-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let M=1;M<=5;M++){let W=document.createElement("button");W.type="button",W.className="tvw-feedback-rating-btn tvw-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${M} star${M>1?"s":""}: ${u[M-1]}`),W.title=u[M-1],W.dataset.rating=String(M),W.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
|
-
`,L.addEventListener("click",()=>{p=A,v.forEach((U,_)=>{let Z=_<A;U.classList.toggle("selected",Z),U.setAttribute("aria-checked",_===A-1?"true":"false")})}),v.push(L),E.appendChild(L)}m.appendChild(E);let W=null;if(c){let A=document.createElement("div");A.className="tvw-feedback-comment-container",W=document.createElement("textarea"),W.className="tvw-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),A.appendChild(W),m.appendChild(A)}let z=document.createElement("div");z.className="tvw-feedback-actions";let h=document.createElement("button");h.type="button",h.className="tvw-feedback-btn tvw-feedback-btn-skip",h.textContent=a,h.addEventListener("click",()=>{o==null||o(),f.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(p===null){E.classList.add("tvw-feedback-shake"),setTimeout(()=>E.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let A=(W==null?void 0:W.value.trim())||void 0;await n(p,A),f.remove()}catch(A){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",A)}}),z.appendChild(h),z.appendChild(O),m.appendChild(z),f.appendChild(m),f}function cs(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:c=!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 y=document.createElement("div");y.className="tvw-feedback-header";let M=document.createElement("h3");M.className="tvw-feedback-title",M.textContent=t,y.appendChild(M);let E=document.createElement("p");E.className="tvw-feedback-subtitle",E.textContent=r,y.appendChild(E),w.appendChild(y);let v=document.createElement("div");v.className="tvw-feedback-rating tvw-feedback-rating-nps",v.setAttribute("role","radiogroup"),v.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="tvw-feedback-labels";let z=document.createElement("span");z.className="tvw-feedback-label-low",z.textContent=u;let h=document.createElement("span");h.className="tvw-feedback-label-high",h.textContent=f,W.appendChild(z),W.appendChild(h);let O=document.createElement("div");O.className="tvw-feedback-numbers";let A=[];for(let ie=0;ie<=10;ie++){let J=document.createElement("button");J.type="button",J.className="tvw-feedback-rating-btn tvw-feedback-number-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`Rating ${ie} out of 10`),J.textContent=String(ie),J.dataset.rating=String(ie),ie<=6?J.classList.add("tvw-feedback-detractor"):ie<=8?J.classList.add("tvw-feedback-passive"):J.classList.add("tvw-feedback-promoter"),J.addEventListener("click",()=>{m=ie,A.forEach((we,B)=>{we.classList.toggle("selected",B===ie),we.setAttribute("aria-checked",B===ie?"true":"false")})}),A.push(J),O.appendChild(J)}v.appendChild(W),v.appendChild(O),w.appendChild(v);let L=null;if(c){let ie=document.createElement("div");ie.className="tvw-feedback-comment-container",L=document.createElement("textarea"),L.className="tvw-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),ie.appendChild(L),w.appendChild(ie)}let U=document.createElement("div");U.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 Z=document.createElement("button");return Z.type="button",Z.className="tvw-feedback-btn tvw-feedback-btn-submit",Z.textContent=i,Z.addEventListener("click",async()=>{if(m===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}Z.disabled=!0,Z.textContent="Submitting...";try{let ie=(L==null?void 0:L.value.trim())||void 0;await n(m,ie),p.remove()}catch(ie){Z.disabled=!1,Z.textContent=i,console.error("[NPS Feedback] Failed to submit:",ie)}}),U.appendChild(_),U.appendChild(Z),w.appendChild(U),p.appendChild(w),p}var wn="persona-chat-history",ga=30*1e3;function ma(e){var n,o,t,r,s,i,a,c,u;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(o=e.keyPrefix)!=null?o:"persona-",persist:{openState:(r=(t=e.persist)==null?void 0:t.openState)!=null?r:!0,voiceState:(i=(s=e.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(c=(a=e.persist)==null?void 0:a.focusInput)!=null?c:!0},clearOnChatClear:(u=e.clearOnChatClear)!=null?u:!0}:null}function ha(e){try{let n=e==="local"?localStorage:sessionStorage,o="__persist_test__";return n.setItem(o,"1"),n.removeItem(o),n}catch{return null}}var Is=e=>!e||typeof e!="object"?{}:{...e},xi=e=>e.map(n=>({...n,streaming:!1})),Si=(e,n,o)=>{let t=e!=null&&e.markdown?Ln(e.markdown):null;return r=>{var a,c,u;let s=(a=r.text)!=null?a:"",i=(c=r.message.rawContent)!=null?c: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):Un(s)}},ds=(e,n,o)=>{var Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs,Gs,Qs,Zs,eo,to,no,so,oo,ro,io,ao;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=ns(n),r=Bn.getForInstance(t.plugins);t.components&&hn.registerAll(t.components);let s=yi(),i=(Ns=t.storageAdapter)!=null?Ns:ss(),a={},c=null,u=l=>{if(t.onStateLoaded)try{return t.onStateLoaded(l)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",d)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(d=>{let S=d!=null?d:{messages:[],metadata:{}};return u(S)});else{let d=l!=null?l:{messages:[],metadata:{}},S=u(d);S.metadata&&(a=Is(S.metadata)),(js=S.messages)!=null&&js.length&&(t={...t,initialMessages:S.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(t.onStateLoaded)try{let l=u({messages:[],metadata:{}});(Ds=l.messages)!=null&&Ds.length&&(t={...t,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let f=()=>a,p=l=>{var S;a=(S=l({...a}))!=null?S:{},Ce()},m=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Rn],w=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[sn.message,sn.messageAndClick],y=Fn({parsers:m,handlers:w,getSessionMetadata:f,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});y.syncFromMetadata();let M=(qs=(_s=t.launcher)==null?void 0:_s.enabled)!=null?qs:!0,E=(zs=(Us=t.launcher)==null?void 0:Us.autoExpand)!=null?zs:!1,v=E,W=M,z=(Ys=(Js=t.layout)==null?void 0:Js.header)==null?void 0:Ys.layout,h=M?E:!0,O=!1,A=null,L=()=>{O=!0,A&&clearTimeout(A),A=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},U=Si(t,y,L),_=(Vs=(Ks=t.features)==null?void 0:Ks.showReasoning)!=null?Vs:!0,Z=(Gs=(Xs=t.features)==null?void 0:Xs.showToolCalls)!=null?Gs:!0,ie={onCopy:l=>{var d,S;s.emit("message:copy",l),b!=null&&b.isClientTokenMode()&&b.submitMessageFeedback(l.id,"copy").catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",P)}),(S=(d=t.messageActions)==null?void 0:d.onCopy)==null||S.call(d,l)},onFeedback:l=>{var d,S;s.emit("message:feedback",l),b!=null&&b.isClientTokenMode()&&b.submitMessageFeedback(l.messageId,l.type).catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",P)}),(S=(d=t.messageActions)==null?void 0:d.onFeedback)==null||S.call(d,l)}},J=(Qs=t.statusIndicator)!=null?Qs:{},we=l=>{var d,S,P,x;return l==="idle"?(d=J.idleText)!=null?d:ut.idle:l==="connecting"?(S=J.connectingText)!=null?S:ut.connecting:l==="connected"?(P=J.connectedText)!=null?P:ut.connected:l==="error"?(x=J.errorText)!=null?x:ut.error:ut[l]},{wrapper:B,panel:N}=di(t),se=ui(t,M),{container:oe,body:Te,messagesWrapper:Ue,suggestions:vt,textarea:Q,sendButton:j,sendButtonWrapper:pt,composerForm:bt,statusText:Ct,introTitle:$t,introSubtitle:Ot,closeButton:D,iconHolder:ye,headerTitle:rt,headerSubtitle:it,header:Ve,footer:at,actionsRow:_t,leftActions:Nt,rightActions:jt}=se,R=se.micButton,ze=se.micButtonWrapper,he=se.attachmentButton,Ze=se.attachmentButtonWrapper,fe=se.attachmentInput,V=se.attachmentPreviewsContainer,re=null;(Zs=t.attachments)!=null&&Zs.enabled&&fe&&V&&(re=tn.fromConfig(t.attachments),re.setPreviewsContainer(V),fe.addEventListener("change",l=>{let d=l.target;re==null||re.handleFileSelect(d.files),d.value=""}));let Xe=r.find(l=>l.renderHeader);if(Xe!=null&&Xe.renderHeader){let l=Xe.renderHeader({config:t,defaultRenderer:()=>{let d=zt({config:t,showClose:M});return nn(oe,d,t),d.header},onClose:()=>C(!1,"user")});if(l){let d=oe.querySelector(".tvw-border-b-cw-divider");d&&(d.replaceWith(l),Ve=l)}}let lt=r.find(l=>l.renderComposer);if(lt!=null&<.renderComposer){let l=lt.renderComposer({config:t,defaultRenderer:()=>un({config:t}).footer,onSubmit:d=>{b&&!b.isStreaming()&&b.sendMessage(d)},disabled:!1});l&&(at.replaceWith(l),at=l)}(()=>{var P,x;let l=(x=(P=t.layout)==null?void 0:P.slots)!=null?x:{},d=K=>{switch(K){case"body-top":return oe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Ue;case"footer-top":return vt;case"composer":return bt;case"footer-bottom":return Ct;default:return null}},S=(K,de)=>{var T;switch(K){case"header-left":case"header-center":case"header-right":if(K==="header-left")Ve.insertBefore(de,Ve.firstChild);else if(K==="header-right")Ve.appendChild(de);else{let q=Ve.querySelector(".tvw-flex-col");q?(T=q.parentNode)==null||T.insertBefore(de,q.nextSibling):Ve.appendChild(de)}break;case"body-top":{let q=Te.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");q?q.replaceWith(de):Te.insertBefore(de,Te.firstChild);break}case"body-bottom":Te.appendChild(de);break;case"footer-top":vt.replaceWith(de);break;case"footer-bottom":Ct.replaceWith(de);break;default:break}};for(let[K,de]of Object.entries(l))if(de)try{let T=de({config:t,defaultContent:()=>d(K)});T&&S(K,T)}catch(T){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${K}":`,T)}})();let Lt=l=>{let S=l.target.closest('button[data-expand-header="true"]');if(!S)return;let P=S.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!P)return;let x=P.getAttribute("data-message-id");if(!x)return;let K=S.getAttribute("data-bubble-type");K==="reasoning"?(gn.has(x)?gn.delete(x):gn.add(x),mi(x,P)):K==="tool"&&(mn.has(x)?mn.delete(x):mn.add(x),hi(x,P,t))};Ue.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Lt(l))}),Ue.addEventListener("keydown",l=>{let d=l.target;(l.key==="Enter"||l.key===" ")&&d.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Lt(l))}),N.appendChild(oe),e.appendChild(B);let Pt=()=>{var ge,Je,Ye,st,Tt,G,ke,Gt,Qt,Nn,jn,fs,Ke,Dn,xn,Sn;let l=(Je=(ge=t.launcher)==null?void 0:ge.sidebarMode)!=null?Je:!1,d=l||((st=(Ye=t.launcher)==null?void 0:Ye.fullHeight)!=null?st:!1),S=(Tt=t.theme)!=null?Tt:{},P=(ke=(G=t.launcher)==null?void 0:G.position)!=null?ke:"bottom-left",x=P==="bottom-left"||P==="top-left",K=l?"none":"1px solid var(--tvw-cw-border)",de=l?x?"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)",T=l?"0":"16px",q=(Gt=S.panelBorder)!=null?Gt:K,X=(Qt=S.panelShadow)!=null?Qt:de,ve=(Nn=S.panelBorderRadius)!=null?Nn:T;e.style.cssText="",B.style.cssText="",N.style.cssText="",oe.style.cssText="",Te.style.cssText="",at.style.cssText="";let $=(fs=(jn=t==null?void 0:t.launcher)==null?void 0:jn.width)!=null?fs:t==null?void 0:t.launcherWidth,De=$!=null?$:"min(400px, calc(100vw - 24px))";l||(N.style.width=De,N.style.maxWidth=De),N.style.boxShadow=X,N.style.borderRadius=ve,oe.style.border=q,oe.style.borderRadius=ve;let Ae=((Ke=t.launcher)==null?void 0:Ke.enabled)===!1;if(d&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",B.style.display="flex",B.style.flexDirection="column",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.maxHeight="100%",B.style.height="100%",Ae&&(B.style.overflow="hidden"),N.style.display="flex",N.style.flexDirection="column",N.style.flex="1 1 0%",N.style.minHeight="0",N.style.maxHeight="100%",N.style.height="100%",N.style.overflow="hidden",oe.style.display="flex",oe.style.flexDirection="column",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.maxHeight="100%",oe.style.overflow="hidden",Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.overflowY="auto",at.style.flexShrink="0"),B.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&&!Ae&&((Dn=Ft[P])!=null?Dn:Ft["bottom-right"]).split(" ").forEach(An=>B.classList.add(An)),l){let Yt=(Sn=(xn=t.launcher)==null?void 0:xn.sidebarWidth)!=null?Sn:"420px";B.style.cssText=`
|
|
20
|
+
`,W.addEventListener("click",()=>{p=M,y.forEach((V,$)=>{let Z=$<M;V.classList.toggle("selected",Z),V.setAttribute("aria-checked",$===M-1?"true":"false")})}),y.push(W),T.appendChild(W)}m.appendChild(T);let L=null;if(d){let M=document.createElement("div");M.className="tvw-feedback-comment-container",L=document.createElement("textarea"),L.className="tvw-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),M.appendChild(L),m.appendChild(M)}let U=document.createElement("div");U.className="tvw-feedback-actions";let h=document.createElement("button");h.type="button",h.className="tvw-feedback-btn tvw-feedback-btn-skip",h.textContent=a,h.addEventListener("click",()=>{r==null||r(),f.remove()});let O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(p===null){T.classList.add("tvw-feedback-shake"),setTimeout(()=>T.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let M=(L==null?void 0:L.value.trim())||void 0;await n(p,M),f.remove()}catch(M){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",M)}}),U.appendChild(h),U.appendChild(O),m.appendChild(U),f.appendChild(m),f}function ds(e){let{onSubmit:n,onDismiss:r,title:t="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel: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 A=document.createElement("div");A.className="tvw-feedback-header";let b=document.createElement("h3");b.className="tvw-feedback-title",b.textContent=t,A.appendChild(b);let T=document.createElement("p");T.className="tvw-feedback-subtitle",T.textContent=o,A.appendChild(T),w.appendChild(A);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 L=document.createElement("div");L.className="tvw-feedback-labels";let U=document.createElement("span");U.className="tvw-feedback-label-low",U.textContent=u;let h=document.createElement("span");h.className="tvw-feedback-label-high",h.textContent=f,L.appendChild(U),L.appendChild(h);let O=document.createElement("div");O.className="tvw-feedback-numbers";let M=[];for(let le=0;le<=10;le++){let z=document.createElement("button");z.type="button",z.className="tvw-feedback-rating-btn tvw-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${le} out of 10`),z.textContent=String(le),z.dataset.rating=String(le),le<=6?z.classList.add("tvw-feedback-detractor"):le<=8?z.classList.add("tvw-feedback-passive"):z.classList.add("tvw-feedback-promoter"),z.addEventListener("click",()=>{m=le,M.forEach((xe,B)=>{xe.classList.toggle("selected",B===le),xe.setAttribute("aria-checked",B===le?"true":"false")})}),M.push(z),O.appendChild(z)}y.appendChild(L),y.appendChild(O),w.appendChild(y);let W=null;if(d){let le=document.createElement("div");le.className="tvw-feedback-comment-container",W=document.createElement("textarea"),W.className="tvw-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),le.appendChild(W),w.appendChild(le)}let V=document.createElement("div");V.className="tvw-feedback-actions";let $=document.createElement("button");$.type="button",$.className="tvw-feedback-btn tvw-feedback-btn-skip",$.textContent=a,$.addEventListener("click",()=>{r==null||r(),p.remove()});let Z=document.createElement("button");return Z.type="button",Z.className="tvw-feedback-btn tvw-feedback-btn-submit",Z.textContent=i,Z.addEventListener("click",async()=>{if(m===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}Z.disabled=!0,Z.textContent="Submitting...";try{let le=(W==null?void 0:W.value.trim())||void 0;await n(m,le),p.remove()}catch(le){Z.disabled=!1,Z.textContent=i,console.error("[NPS Feedback] Failed to submit:",le)}}),V.appendChild($),V.appendChild(Z),w.appendChild(V),p.appendChild(w),p}var bn="persona-chat-history",ma=30*1e3;function ha(e){var n,r,t,o,s,i,a,d,u;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(t=e.persist)==null?void 0:t.openState)!=null?o:!0,voiceState:(i=(s=e.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=e.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(u=e.clearOnChatClear)!=null?u:!0}:null}function fa(e){try{let n=e==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var Bs=e=>!e||typeof e!="object"?{}:{...e},Si=e=>e.map(n=>({...n,streaming:!1})),Ai=(e,n,r)=>{let t=e!=null&&e.markdown?Hn(e.markdown):null;return o=>{var a,d,u;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(n){let f=n.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});f!==null&&(s=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&r&&r())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(u=i!=null?i:o.text)!=null?u:""}):t?t(s):Un(s)}},cs=(e,n,r)=>{var js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs,Gs,Qs,Zs,er,tr,nr,sr,rr,or,ir,ar,lr;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=ns(n),o=Fn.getForInstance(t.plugins);t.components&&yn.registerAll(t.components);let s=vi(),i=(js=t.storageAdapter)!=null?js:ss(),a={},d=null,u=l=>{if(t.onStateLoaded)try{return t.onStateLoaded(l)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(c=>{let S=c!=null?c:{messages:[],metadata:{}};return u(S)});else{let c=l!=null?l:{messages:[],metadata:{}},S=u(c);S.metadata&&(a=Bs(S.metadata)),(Ds=S.messages)!=null&&Ds.length&&(t={...t,initialMessages:S.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(t.onStateLoaded)try{let l=u({messages:[],metadata:{}});(_s=l.messages)!=null&&_s.length&&(t={...t,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let f=()=>a,p=l=>{var S;a=(S=l({...a}))!=null?S:{},Me()},m=t.actionParsers&&t.actionParsers.length?t.actionParsers:[$n],w=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[an.message,an.messageAndClick],A=On({parsers:m,handlers:w,getSessionMetadata:f,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let b=(Us=(qs=t.launcher)==null?void 0:qs.enabled)!=null?Us:!0,T=(Js=(zs=t.launcher)==null?void 0:zs.autoExpand)!=null?Js:!1,y=T,L=b,U=(Ks=(Ys=t.layout)==null?void 0:Ys.header)==null?void 0:Ks.layout,h=b?T:!0,O=!1,M=null,W=()=>{O=!0,M&&clearTimeout(M),M=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},V=Ai(t,A,W),$=(Xs=(Vs=t.features)==null?void 0:Vs.showReasoning)!=null?Xs:!0,Z=(Qs=(Gs=t.features)==null?void 0:Gs.showToolCalls)!=null?Qs:!0,le={onCopy:l=>{var c,S;s.emit("message:copy",l),v!=null&&v.isClientTokenMode()&&v.submitMessageFeedback(l.id,"copy").catch(I=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",I)}),(S=(c=t.messageActions)==null?void 0:c.onCopy)==null||S.call(c,l)},onFeedback:l=>{var c,S;s.emit("message:feedback",l),v!=null&&v.isClientTokenMode()&&v.submitMessageFeedback(l.messageId,l.type).catch(I=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",I)}),(S=(c=t.messageActions)==null?void 0:c.onFeedback)==null||S.call(c,l)}},z=(Zs=t.statusIndicator)!=null?Zs:{},xe=l=>{var c,S,I,x;return l==="idle"?(c=z.idleText)!=null?c:pt.idle:l==="connecting"?(S=z.connectingText)!=null?S:pt.connecting:l==="connected"?(I=z.connectedText)!=null?I:pt.connected:l==="error"?(x=z.errorText)!=null?x:pt.error:pt[l]},{wrapper:B,panel:N}=ui(t),oe=pi(t,b),{container:ie,body:Le,messagesWrapper:Ye,suggestions:bt,textarea:Q,sendButton:D,sendButtonWrapper:gt,composerForm:Ct,statusText:xt,introTitle:Ot,introSubtitle:Nt,closeButton:_,iconHolder:Se,headerTitle:it,headerSubtitle:at,header:Xe,footer:lt,actionsRow:zt,leftActions:jt,rightActions:Dt}=oe,R=oe.micButton,Ke=oe.micButtonWrapper,ye=oe.attachmentButton,tt=oe.attachmentButtonWrapper,ve=oe.attachmentInput,G=oe.attachmentPreviewsContainer,ae=null;(er=t.attachments)!=null&&er.enabled&&ve&&G&&(ae=sn.fromConfig(t.attachments),ae.setPreviewsContainer(G),ve.addEventListener("change",l=>{let c=l.target;ae==null||ae.handleFileSelect(c.files),c.value=""}));let Ge=o.find(l=>l.renderHeader);if(Ge!=null&&Ge.renderHeader){let l=Ge.renderHeader({config:t,defaultRenderer:()=>{let c=Kt({config:t,showClose:b});return rn(ie,c,t),c.header},onClose:()=>C(!1,"user")});if(l){let c=ie.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),Xe=l)}}let dt=o.find(l=>l.renderComposer);if(dt!=null&&dt.renderComposer){let l=dt.renderComposer({config:t,defaultRenderer:()=>mn({config:t}).footer,onSubmit:c=>{v&&!v.isStreaming()&&v.sendMessage(c)},disabled:!1});l&&(lt.replaceWith(l),lt=l)}(()=>{var I,x;let l=(x=(I=t.layout)==null?void 0:I.slots)!=null?x:{},c=X=>{switch(X){case"body-top":return ie.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Ye;case"footer-top":return bt;case"composer":return Ct;case"footer-bottom":return xt;default:return null}},S=(X,pe)=>{var Y;switch(X){case"header-left":case"header-center":case"header-right":if(X==="header-left")Xe.insertBefore(pe,Xe.firstChild);else if(X==="header-right")Xe.appendChild(pe);else{let me=Xe.querySelector(".tvw-flex-col");me?(Y=me.parentNode)==null||Y.insertBefore(pe,me.nextSibling):Xe.appendChild(pe)}break;case"body-top":{let me=Le.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");me?me.replaceWith(pe):Le.insertBefore(pe,Le.firstChild);break}case"body-bottom":Le.appendChild(pe);break;case"footer-top":bt.replaceWith(pe);break;case"footer-bottom":xt.replaceWith(pe);break;default:break}};for(let[X,pe]of Object.entries(l))if(pe)try{let Y=pe({config:t,defaultContent:()=>c(X)});Y&&S(X,Y)}catch(Y){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${X}":`,Y)}})();let Wt=l=>{let S=l.target.closest('button[data-expand-header="true"]');if(!S)return;let I=S.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!I)return;let x=I.getAttribute("data-message-id");if(!x)return;let X=S.getAttribute("data-bubble-type");X==="reasoning"?(fn.has(x)?fn.delete(x):fn.add(x),hi(x,I)):X==="tool"&&(wn.has(x)?wn.delete(x):wn.add(x),fi(x,I,t))};Ye.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Wt(l))}),Ye.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Wt(l))}),N.appendChild(ie),e.appendChild(B);let It=()=>{var ee,te,fe,Ie,Qe,q,K,_t,qt,Ft,Xt,fs,Ve,Dn,Tn,Mn;let l=(te=(ee=t.launcher)==null?void 0:ee.sidebarMode)!=null?te:!1,c=l||((Ie=(fe=t.launcher)==null?void 0:fe.fullHeight)!=null?Ie:!1),S=(Qe=t.theme)!=null?Qe:{},I=(K=(q=t.launcher)==null?void 0:q.position)!=null?K:"bottom-left",x=I==="bottom-left"||I==="top-left",X=l?"none":"1px solid var(--tvw-cw-border)",pe=l?x?"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)",Y=l?"0":"16px",me=(_t=S.panelBorder)!=null?_t:X,be=(qt=S.panelShadow)!=null?qt:pe,Ce=(Ft=S.panelBorderRadius)!=null?Ft:Y;e.style.cssText="",B.style.cssText="",N.style.cssText="",ie.style.cssText="",Le.style.cssText="",lt.style.cssText="";let j=(fs=(Xt=t==null?void 0:t.launcher)==null?void 0:Xt.width)!=null?fs:t==null?void 0:t.launcherWidth,Ue=j!=null?j:"min(400px, calc(100vw - 24px))";l||(N.style.width=Ue,N.style.maxWidth=Ue),N.style.boxShadow=be,N.style.borderRadius=Ce,ie.style.border=me,ie.style.borderRadius=Ce;let k=((Ve=t.launcher)==null?void 0:Ve.enabled)===!1;if(c&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",B.style.display="flex",B.style.flexDirection="column",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.maxHeight="100%",B.style.height="100%",k&&(B.style.overflow="hidden"),N.style.display="flex",N.style.flexDirection="column",N.style.flex="1 1 0%",N.style.minHeight="0",N.style.maxHeight="100%",N.style.height="100%",N.style.overflow="hidden",ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.overflow="hidden",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.overflowY="auto",lt.style.flexShrink="0"),B.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&&!k&&((Dn=$t[I])!=null?Dn:$t["bottom-right"]).split(" ").forEach(En=>B.classList.add(En)),l){let Gt=(Mn=(Tn=t.launcher)==null?void 0:Tn.sidebarWidth)!=null?Mn:"420px";B.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
top: 0 !important;
|
|
23
23
|
bottom: 0 !important;
|
|
24
|
-
width: ${
|
|
24
|
+
width: ${Gt} !important;
|
|
25
25
|
height: 100vh !important;
|
|
26
26
|
max-height: 100vh !important;
|
|
27
27
|
margin: 0 !important;
|
|
@@ -40,9 +40,9 @@
|
|
|
40
40
|
min-height: 0 !important;
|
|
41
41
|
margin: 0 !important;
|
|
42
42
|
padding: 0 !important;
|
|
43
|
-
box-shadow: ${
|
|
44
|
-
border-radius: ${
|
|
45
|
-
`,N.style.setProperty("width","100%","important"),N.style.setProperty("max-width","100%","important"),
|
|
43
|
+
box-shadow: ${be} !important;
|
|
44
|
+
border-radius: ${Ce} !important;
|
|
45
|
+
`,N.style.setProperty("width","100%","important"),N.style.setProperty("max-width","100%","important"),ie.style.cssText=`
|
|
46
46
|
display: flex !important;
|
|
47
47
|
flex-direction: column !important;
|
|
48
48
|
flex: 1 1 0% !important;
|
|
@@ -51,13 +51,13 @@
|
|
|
51
51
|
min-height: 0 !important;
|
|
52
52
|
max-height: 100% !important;
|
|
53
53
|
overflow: hidden !important;
|
|
54
|
-
border-radius: ${
|
|
55
|
-
border: ${
|
|
56
|
-
`,
|
|
54
|
+
border-radius: ${Ce} !important;
|
|
55
|
+
border: ${me} !important;
|
|
56
|
+
`,lt.style.cssText=`
|
|
57
57
|
flex-shrink: 0 !important;
|
|
58
58
|
border-top: none !important;
|
|
59
59
|
padding: 8px 16px 12px 16px !important;
|
|
60
|
-
`}if(!Ae){let Yt="max-height: -moz-available !important; max-height: stretch !important;",An=l?"":"padding-top: 1.25em !important;";B.style.cssText+=Yt+An}};Pt(),es(e,t);let We=[],et=null,kt=()=>{et&&(et(),et=null),t.colorScheme==="auto"&&(et=ai(()=>{es(e,t)}))};kt(),We.push(()=>{et&&(et(),et=null)});let At=fi(vt),ct=null,b,xe=!1,$e=!0,gt=0,tt=0,mt=null,ht=!1,Ht=0,Vt=!1,Xt=125,$n=2e3,On=5,yn=50,rn=new Map,Me={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},vn=(to=(eo=t.voiceRecognition)==null?void 0:eo.autoResume)!=null?to:!1,bn=l=>{s.emit("voice:state",{active:Me.active,source:l,timestamp:Date.now()})},qt=()=>{p(l=>({...l,voiceState:{active:Me.active,timestamp:Date.now(),manuallyDeactivated:Me.manuallyDeactivated}}))},I=()=>{var P,x;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let l=Is(a.voiceState),d=!!l.active,S=Number((x=l.timestamp)!=null?x:0);Me.manuallyDeactivated=!!l.manuallyDeactivated,d&&Date.now()-S<ga&&setTimeout(()=>{Me.active||(Me.manuallyDeactivated=!1,Fe("restore"))},1e3)},ue=()=>b?xi(b.getMessages()).filter(l=>!l.__skipPersist):[];function Ce(l){if(!(i!=null&&i.save))return;let S={messages:l?xi(l):b?ue():[],metadata:a};try{let P=i.save(S);P instanceof Promise&&P.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)})}catch(P){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)}}let Le=(l=!1)=>{if(!$e)return;let d=Date.now();ht&&d<Ht&&!l||(ht&&d>=Ht&&(ht=!1),!(!l&&!xe)&&(d-tt<Xt||(tt=d,mt&&cancelAnimationFrame(mt),mt=requestAnimationFrame(()=>{ht||!$e||(Vt=!0,Te.scrollTop=Te.scrollHeight,gt=Te.scrollTop,requestAnimationFrame(()=>{Vt=!1}),mt=null)}))))},Pe=null,nt=()=>B.querySelector("#persona-scroll-container")||Te,Oe=(l,d=500)=>{let S=l.scrollTop,P=l.clientHeight,x=l.scrollHeight,K=x-S;if(S+P>=x-2||Math.abs(K)<5)return;Pe!==null&&(cancelAnimationFrame(Pe),Pe=null);let T=performance.now(),q=ve=>1-Math.pow(1-ve,3),X=ve=>{let $=l.scrollHeight;$!==x&&(x=$,K=x-S);let De=ve-T,Ae=Math.min(De/d,1),ge=q(Ae),Je=S+K*ge;l.scrollTop=Je,Ae<1?Pe=requestAnimationFrame(X):(l.scrollTop=l.scrollHeight,Pe=null)};Pe=requestAnimationFrame(X)},F=l=>{let d=new Map;l.forEach(S=>{let P=rn.get(S.id);d.set(S.id,{streaming:S.streaming,role:S.role}),!P&&S.role==="assistant"&&s.emit("assistant:message",S),S.role==="assistant"&&(P!=null&&P.streaming)&&S.streaming===!1&&s.emit("assistant:complete",S)}),rn.clear(),d.forEach((S,P)=>{rn.set(P,S)})},ee=(l,d,S)=>{let P=document.createElement("div");d.forEach(T=>{var De,Ae;let q=null,X=r.find(ge=>!!(T.variant==="reasoning"&&ge.renderReasoning||T.variant==="tool"&&ge.renderToolCall||!T.variant&&ge.renderMessage)),ve=(De=t.layout)==null?void 0:De.messages;if(X)if(T.variant==="reasoning"&&T.reasoning&&X.renderReasoning){if(!_)return;q=X.renderReasoning({message:T,defaultRenderer:()=>Ts(T),config:t})}else if(T.variant==="tool"&&T.toolCall&&X.renderToolCall){if(!Z)return;q=X.renderToolCall({message:T,defaultRenderer:()=>Ms(T,t),config:t})}else X.renderMessage&&(q=X.renderMessage({message:T,defaultRenderer:()=>{let ge=pn(T,S,ve,t.messageActions,ie);return T.role!=="user"&&Es(ge,T,t,b),ge},config:t}));if(!q&&T.role==="assistant"&&!T.variant&&t.enableComponentStreaming!==!1&&is(T)){let Je=as(T);if(Je){let Ye=rs(Je,{config:t,message:T,transform:S});if(Ye){let st=document.createElement("div");if(st.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(" "),st.id=`bubble-${T.id}`,st.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=S({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),st.appendChild(Tt)}st.appendChild(Ye),q=st}}}if(!q)if(T.variant==="reasoning"&&T.reasoning){if(!_)return;q=Ts(T)}else if(T.variant==="tool"&&T.toolCall){if(!Z)return;q=Ms(T,t)}else{let ge=(Ae=t.layout)==null?void 0:Ae.messages;ge!=null&&ge.renderUserMessage&&T.role==="user"?q=ge.renderUserMessage({message:T,config:t,streaming:!!T.streaming}):ge!=null&&ge.renderAssistantMessage&&T.role==="assistant"?q=ge.renderAssistantMessage({message:T,config:t,streaming:!!T.streaming}):q=pn(T,S,ge,t.messageActions,ie),T.role!=="user"&&q&&Es(q,T,t,b)}let $=document.createElement("div");$.className="tvw-flex",$.id=`wrapper-${T.id}`,$.setAttribute("data-wrapper-id",T.id),T.role==="user"&&$.classList.add("tvw-justify-end"),$.appendChild(q),P.appendChild($)});let x=d.some(T=>T.role==="assistant"&&T.streaming),K=d[d.length-1],de=(K==null?void 0:K.role)==="assistant"&&!K.streaming;if(xe&&d.some(T=>T.role==="user")&&!x&&!de){let T=In(),q=document.createElement("div");q.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(" "),q.setAttribute("data-typing-indicator","true"),q.appendChild(T);let X=document.createElement("div");X.className="tvw-flex",X.id="wrapper-typing-indicator",X.setAttribute("data-wrapper-id","typing-indicator"),X.appendChild(q),P.appendChild(X)}ci(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let T=nt();Oe(T)})})},H=()=>{M&&(h?(B.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),N.classList.remove("tvw-scale-95","tvw-opacity-0"),N.classList.add("tvw-scale-100","tvw-opacity-100"),Ne?Ne.element.style.display="none":je&&(je.style.display="none")):(B.classList.add("tvw-pointer-events-none","tvw-opacity-0"),N.classList.remove("tvw-scale-100","tvw-opacity-100"),N.classList.add("tvw-scale-95","tvw-opacity-0"),Ne?Ne.element.style.display="":je&&(je.style.display="")))},C=(l,d="user")=>{if(!M||h===l)return;let S=h;h=l,H(),h&&(Cn(),Le(!0));let P={open:h,source:d,timestamp:Date.now()};h&&!S?s.emit("widget:opened",P):!h&&S&&s.emit("widget:closed",P),s.emit("widget:state",{open:h,launcherEnabled:M,voiceActive:Me.active,streaming:b.isStreaming()})},Y=l=>{j.disabled=l,R&&(R.disabled=l),At.buttons.forEach(d=>{d.disabled=l})},He=()=>{var x,K,de,T,q,X,ve,$,De,Ae,ge,Je,Ye,st;$t.textContent=(K=(x=t.copy)==null?void 0:x.welcomeTitle)!=null?K:"Hello \u{1F44B}",Ot.textContent=(T=(de=t.copy)==null?void 0:de.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",Q.placeholder=(X=(q=t.copy)==null?void 0:q.inputPlaceholder)!=null?X:"How can I help...",(($=(ve=t.sendButton)==null?void 0:ve.useIcon)!=null?$:!1)||(j.textContent=(Ae=(De=t.copy)==null?void 0:De.sendButtonLabel)!=null?Ae:"Send");let d=(Je=(ge=t.theme)==null?void 0:ge.inputFontFamily)!=null?Je:"sans-serif",S=(st=(Ye=t.theme)==null?void 0:Ye.inputFontWeight)!=null?st:"400",P=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'}};Q.style.fontFamily=P(d),Q.style.fontWeight=S};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(d=>({...d,session_id:l}))}}),b=new cn(t,{onMessagesChanged(l){ee(Ue,l,U),b&&(l.some(x=>x.role==="user")?At.render([],b,Q,l):At.render(t.suggestionChips,b,Q,l,t.suggestionChipsConfig)),Le(!xe),F(l);let d=[...l].reverse().find(P=>P.role==="user"),S=Me.lastUserMessageId;d&&d.id!==S&&(Me.lastUserMessageId=d.id,s.emit("user:message",d)),Me.lastUserMessageWasVoice=!!(d!=null&&d.viaVoice),Ce(l)},onStatusChanged(l){var P;let d=(P=t.statusIndicator)!=null?P:{},S=x=>{var K,de,T,q;return x==="idle"?(K=d.idleText)!=null?K:ut.idle:x==="connecting"?(de=d.connectingText)!=null?de:ut.connecting:x==="connected"?(T=d.connectedText)!=null?T:ut.connected:x==="error"?(q=d.errorText)!=null?q:ut.error:ut[x]};Ct.textContent=S(l)},onStreamingChanged(l){xe=l,Y(l),b&&ee(Ue,b.getMessages(),U),l||Le(!0)}}),c&&c.then(l=>{var d;l&&(l.metadata&&(a=Is(l.metadata),y.syncFromMetadata()),(d=l.messages)!=null&&d.length&&b.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Ie=l=>{var x;l.preventDefault();let d=Q.value.trim(),S=(x=re==null?void 0:re.hasAttachments())!=null?x:!1;if(!d&&!S)return;let P;S&&(P=[],P.push(...re.getContentParts()),d&&P.push(Gn(d))),Q.value="",Q.style.height="auto",b.sendMessage(d,{contentParts:P}),S&&re.clearAttachments()},ft=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),j.click())},pe=null,Ee=!1,Be=null,ae=null,Se=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fe=(l="user")=>{var K,de,T,q;if(Ee||b.isStreaming())return;let d=Se();if(!d)return;pe=new d;let P=(de=((K=t.voiceRecognition)!=null?K:{}).pauseDuration)!=null?de:2e3;pe.continuous=!0,pe.interimResults=!0,pe.lang="en-US";let x=Q.value;pe.onresult=X=>{let ve="",$="";for(let Ae=0;Ae<X.results.length;Ae++){let ge=X.results[Ae],Je=ge[0].transcript;ge.isFinal?ve+=Je+" ":$=Je}let De=x+ve+$;Q.value=De,Be&&clearTimeout(Be),(ve||$)&&(Be=window.setTimeout(()=>{let Ae=Q.value.trim();Ae&&pe&&Ee&&(ce(),Q.value="",Q.style.height="auto",b.sendMessage(Ae,{viaVoice:!0}))},P))},pe.onerror=X=>{X.error!=="no-speech"&&ce()},pe.onend=()=>{if(Ee){let X=Q.value.trim();X&&X!==x.trim()&&(Q.value="",Q.style.height="auto",b.sendMessage(X,{viaVoice:!0})),ce()}};try{if(pe.start(),Ee=!0,Me.active=!0,l!=="system"&&(Me.manuallyDeactivated=!1),bn(l),qt(),R){ae={backgroundColor:R.style.backgroundColor,color:R.style.color,borderColor:R.style.borderColor};let X=(T=t.voiceRecognition)!=null?T:{},ve=(q=X.recordingBackgroundColor)!=null?q:"#ef4444",$=X.recordingIconColor,De=X.recordingBorderColor;if(R.classList.add("tvw-voice-recording"),R.style.backgroundColor=ve,$){R.style.color=$;let Ae=R.querySelector("svg");Ae&&Ae.setAttribute("stroke",$)}De&&(R.style.borderColor=De),R.setAttribute("aria-label","Stop voice recognition")}}catch{ce("system")}},ce=(l="user")=>{if(Ee){if(Ee=!1,Be&&(clearTimeout(Be),Be=null),pe){try{pe.stop()}catch{}pe=null}if(Me.active=!1,bn(l),qt(),R){if(R.classList.remove("tvw-voice-recording"),ae){R.style.backgroundColor=ae.backgroundColor,R.style.color=ae.color,R.style.borderColor=ae.borderColor;let d=R.querySelector("svg");d&&d.setAttribute("stroke",ae.color||"currentColor"),ae=null}R.setAttribute("aria-label","Start voice recognition")}}},Qe=(l,d)=>{var Je,Ye,st,Tt,G,ke,Gt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=g("div","tvw-send-button-wrapper"),x=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");x.type="button",x.setAttribute("aria-label","Start voice recognition");let K=(Je=l==null?void 0:l.iconName)!=null?Je:"mic",de=(Ye=d==null?void 0:d.size)!=null?Ye:"40px",T=(st=l==null?void 0:l.iconSize)!=null?st:de,q=parseFloat(T)||24,X=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:d==null?void 0:d.backgroundColor,ve=(G=l==null?void 0:l.iconColor)!=null?G:d==null?void 0:d.textColor;x.style.width=T,x.style.height=T,x.style.minWidth=T,x.style.minHeight=T,x.style.fontSize="18px",x.style.lineHeight="1";let $=ve||"currentColor",De=ne(K,q,$,1.5);De?(x.appendChild(De),x.style.color=$):(x.textContent="\u{1F3A4}",x.style.color=$),X?x.style.backgroundColor=X:x.classList.add("tvw-bg-cw-primary"),ve?x.style.color=ve:!ve&&!(d!=null&&d.textColor)&&x.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(x.style.borderWidth=l.borderWidth,x.style.borderStyle="solid"),l!=null&&l.borderColor&&(x.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(x.style.paddingLeft=l.paddingX,x.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(x.style.paddingTop=l.paddingY,x.style.paddingBottom=l.paddingY),P.appendChild(x);let Ae=(ke=l==null?void 0:l.tooltipText)!=null?ke:"Start voice recognition";if(((Gt=l==null?void 0:l.showTooltip)!=null?Gt:!1)&&Ae){let Qt=g("div","tvw-send-button-tooltip");Qt.textContent=Ae,P.appendChild(Qt)}return{micButton:x,micButtonWrapper:P}},wt=()=>{if(Ee){let l=Q.value.trim();Me.manuallyDeactivated=!0,qt(),ce("user"),l&&(Q.value="",Q.style.height="auto",b.sendMessage(l))}else Me.manuallyDeactivated=!1,qt(),Fe("user")};R&&(R.addEventListener("click",wt),We.push(()=>{ce("system"),R&&R.removeEventListener("click",wt)}));let Bt=s.on("assistant:complete",()=>{vn&&(Me.active||Me.manuallyDeactivated||vn==="assistant"&&!Me.lastUserMessageWasVoice||setTimeout(()=>{!Me.active&&!Me.manuallyDeactivated&&Fe("auto")},600))});We.push(Bt);let Hi=s.on("action:resubmit",()=>{setTimeout(()=>{b&&!b.isStreaming()&&b.continueConversation()},100)});We.push(Hi);let an=()=>{C(!h,"user")},Ne=null,je=null;if(M){let l=r.find(d=>d.renderLauncher);if(l!=null&&l.renderLauncher){let d=l.renderLauncher({config:t,defaultRenderer:()=>Hn(t,an).element,onToggle:an});d&&(je=d)}je||(Ne=Hn(t,an))}Ne?e.appendChild(Ne.element):je&&e.appendChild(je),H(),At.render(t.suggestionChips,b,Q,void 0,t.suggestionChipsConfig),He(),Y(b.isStreaming()),Le(!0),I();let Cn=()=>{var S,P,x,K,de,T,q,X;let l=(P=(S=t.launcher)==null?void 0:S.sidebarMode)!=null?P:!1,d=l||((K=(x=t.launcher)==null?void 0:x.fullHeight)!=null?K:!1);if(!M){N.style.height="",N.style.width="";return}if(!l){let ve=(T=(de=t==null?void 0:t.launcher)==null?void 0:de.width)!=null?T:t==null?void 0:t.launcherWidth,$=ve!=null?ve:"min(400px, calc(100vw - 24px))";N.style.width=$,N.style.maxWidth=$}if(!d){let ve=window.innerHeight,$=64,De=(X=(q=t.launcher)==null?void 0:q.heightOffset)!=null?X:0,Ae=Math.max(200,ve-$),ge=Math.min(640,Ae),Je=Math.max(200,ge-De);N.style.height=`${Je}px`}};Cn(),window.addEventListener("resize",Cn),We.push(()=>window.removeEventListener("resize",Cn)),gt=Te.scrollTop;let $s=()=>{let l=Te.scrollTop,d=Te.scrollHeight,S=Te.clientHeight,P=d-l-S,x=Math.abs(l-gt);if(gt=l,!Vt&&!(x<=On)){if(!$e&&P<yn){ht=!1,$e=!0;return}$e&&P>yn&&(ht=!0,Ht=Date.now()+$n,$e=!1)}};Te.addEventListener("scroll",$s,{passive:!0}),We.push(()=>Te.removeEventListener("scroll",$s)),We.push(()=>{mt&&cancelAnimationFrame(mt)});let Os=()=>{D&&(ct&&(D.removeEventListener("click",ct),ct=null),M?(D.style.display="",ct=()=>{h=!1,H()},D.addEventListener("click",ct)):D.style.display="none")};Os(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{b.clearMessages();try{localStorage.removeItem(wn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${wn}`)}catch(S){console.error("[AgentWidget] Failed to clear default localStorage:",S)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==wn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(S){console.error("[AgentWidget] Failed to clear custom localStorage:",S)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(d),i!=null&&i.clear)try{let S=i.clear();S instanceof Promise&&S.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",P)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)}a={},y.syncFromMetadata()})})(),bt.addEventListener("submit",Ie),Q.addEventListener("keydown",ft),We.push(()=>{bt.removeEventListener("submit",Ie),Q.removeEventListener("keydown",ft)}),We.push(()=>{b.cancel()}),Ne?We.push(()=>{Ne==null||Ne.destroy()}):je&&We.push(()=>{je==null||je.remove()});let Rt={update(l){var lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Mo,Eo,ko,Wo,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,cr,dr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar,Tr,Mr,Er,kr,Wr,Lr,Pr,Hr,Ir,Br,Rr,Fr;let d=t.toolCall,S=t.colorScheme;t={...t,...l},Pt(),es(e,t),t.colorScheme!==S&&kt();let P=Bn.getForInstance(t.plugins);if(r.length=0,r.push(...P),M=(co=(lo=t.launcher)==null?void 0:lo.enabled)!=null?co:!0,E=(po=(uo=t.launcher)==null?void 0:uo.autoExpand)!=null?po:!1,_=(mo=(go=t.features)==null?void 0:go.showReasoning)!=null?mo:!0,Z=(fo=(ho=t.features)==null?void 0:ho.showToolCalls)!=null?fo:!0,((wo=t.launcher)==null?void 0:wo.enabled)===!1&&Ne&&(Ne.destroy(),Ne=null),((yo=t.launcher)==null?void 0:yo.enabled)===!1&&je&&(je.remove(),je=null),((vo=t.launcher)==null?void 0:vo.enabled)!==!1&&!Ne&&!je){let k=r.find(me=>me.renderLauncher);if(k!=null&&k.renderLauncher){let me=k.renderLauncher({config:t,defaultRenderer:()=>Hn(t,an).element,onToggle:an});me&&(je=me,e.appendChild(je))}je||(Ne=Hn(t,an),e.appendChild(Ne.element))}Ne&&Ne.update(t),rt&&((bo=t.launcher)==null?void 0:bo.title)!==void 0&&(rt.textContent=t.launcher.title),it&&((Co=t.launcher)==null?void 0:Co.subtitle)!==void 0&&(it.textContent=t.launcher.subtitle);let x=(xo=t.layout)==null?void 0:xo.header;if((x==null?void 0:x.layout)!==z&&Ve){let k=x?dn(t,x,{showClose:M,onClose:()=>C(!1,"user")}):zt({config:t,showClose:M,onClose:()=>C(!1,"user")});Ve.replaceWith(k.header),Ve=k.header,ye=k.iconHolder,rt=k.headerTitle,it=k.headerSubtitle,D=k.closeButton,z=x==null?void 0:x.layout}else if(x&&(ye&&(ye.style.display=x.showIcon===!1?"none":""),rt&&(rt.style.display=x.showTitle===!1?"none":""),it&&(it.style.display=x.showSubtitle===!1?"none":""),D&&(D.style.display=x.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let k=x.showClearChat;if(k!==void 0){se.clearChatButtonWrapper.style.display=k?"":"none";let{closeButtonWrapper:me}=se;me&&!me.classList.contains("tvw-absolute")&&(k?me.classList.remove("tvw-ml-auto"):me.classList.add("tvw-ml-auto"))}}let de=((So=t.layout)==null?void 0:So.showHeader)!==!1;Ve&&(Ve.style.display=de?"":"none");let T=((Ao=t.layout)==null?void 0:Ao.showFooter)!==!1;at&&(at.style.display=T?"":"none"),M!==W?M?C(E,"auto"):(h=!0,H()):E!==v&&C(E,"auto"),v=E,W=M,Cn(),Os(),JSON.stringify(l.toolCall)!==JSON.stringify(d)&&b&&ee(Ue,b.getMessages(),U);let $=(To=t.launcher)!=null?To:{},De=(Mo=$.headerIconHidden)!=null?Mo:!1,Ae=(ko=(Eo=t.layout)==null?void 0:Eo.header)==null?void 0:ko.showIcon,ge=De||Ae===!1,Je=$.headerIconName,Ye=(Wo=$.headerIconSize)!=null?Wo:"48px";if(ye){let k=oe.querySelector(".tvw-border-b-cw-divider"),me=k==null?void 0:k.querySelector(".tvw-flex-col");if(ge)ye.style.display="none",k&&me&&!k.contains(me)&&k.insertBefore(me,k.firstChild);else{if(ye.style.display="",ye.style.height=Ye,ye.style.width=Ye,k&&me&&(k.contains(ye)?ye.nextSibling!==me&&(ye.remove(),k.insertBefore(ye,me)):k.insertBefore(ye,me)),Je){let te=parseFloat(Ye)||24,be=ne(Je,te*.6,"#ffffff",2);be?ye.replaceChildren(be):ye.textContent=(Lo=$.agentIconText)!=null?Lo:"\u{1F4AC}"}else if($.iconUrl){let te=ye.querySelector("img");if(te)te.src=$.iconUrl,te.style.height=Ye,te.style.width=Ye;else{let be=document.createElement("img");be.src=$.iconUrl,be.alt="",be.className="tvw-rounded-xl tvw-object-cover",be.style.height=Ye,be.style.width=Ye,ye.replaceChildren(be)}}else{let te=ye.querySelector("svg"),be=ye.querySelector("img");(te||be)&&ye.replaceChildren(),ye.textContent=(Po=$.agentIconText)!=null?Po:"\u{1F4AC}"}let _e=ye.querySelector("img");_e&&(_e.style.height=Ye,_e.style.width=Ye)}}let st=(Io=(Ho=t.layout)==null?void 0:Ho.header)==null?void 0:Io.showTitle,Tt=(Ro=(Bo=t.layout)==null?void 0:Bo.header)==null?void 0:Ro.showSubtitle;if(rt&&(rt.style.display=st===!1?"none":""),it&&(it.style.display=Tt===!1?"none":""),D){(($o=(Fo=t.layout)==null?void 0:Fo.header)==null?void 0:$o.showCloseButton)===!1?D.style.display="none":D.style.display="";let me=(Oo=$.closeButtonSize)!=null?Oo:"32px",_e=(No=$.closeButtonPlacement)!=null?No:"inline";D.style.height=me,D.style.width=me;let{closeButtonWrapper:te}=se,be=_e==="top-right",dt=te==null?void 0:te.classList.contains("tvw-absolute");if(te&&be!==dt)if(te.remove(),be)te.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",oe.style.position="relative",oe.appendChild(te);else{let le=(Do=(jo=$.clearChat)==null?void 0:jo.placement)!=null?Do:"inline",Ge=(qo=(_o=$.clearChat)==null?void 0:_o.enabled)!=null?qo:!0;te.className=Ge&&le==="inline"?"":"tvw-ml-auto";let xt=oe.querySelector(".tvw-border-b-cw-divider");xt&&xt.appendChild(te)}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 le=$.closeButtonBorderWidth||"0px",Ge=$.closeButtonBorderColor||"transparent";D.style.border=`${le} solid ${Ge}`,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 ot=(Uo=$.closeButtonIconName)!=null?Uo:"x",Mt=(zo=$.closeButtonIconText)!=null?zo:"\xD7";D.innerHTML="";let yt=ne(ot,"20px",$.closeButtonColor||"",2);yt?D.appendChild(yt):D.textContent=Mt;let qe=(Jo=$.closeButtonTooltipText)!=null?Jo:"Close chat",Et=(Yo=$.closeButtonShowTooltip)!=null?Yo:!0;if(D.setAttribute("aria-label",qe),te&&(te._cleanupTooltip&&(te._cleanupTooltip(),delete te._cleanupTooltip),Et&&qe)){let le=null,Ge=()=>{if(le||!D)return;le=g("div","tvw-clear-chat-tooltip"),le.textContent=qe;let kn=g("div");kn.className="tvw-clear-chat-tooltip-arrow",le.appendChild(kn);let Zt=D.getBoundingClientRect();le.style.position="fixed",le.style.left=`${Zt.left+Zt.width/2}px`,le.style.top=`${Zt.top-8}px`,le.style.transform="translate(-50%, -100%)",document.body.appendChild(le)},xt=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};te.addEventListener("mouseenter",Ge),te.addEventListener("mouseleave",xt),D.addEventListener("focus",Ge),D.addEventListener("blur",xt),te._cleanupTooltip=()=>{xt(),te&&(te.removeEventListener("mouseenter",Ge),te.removeEventListener("mouseleave",xt)),D&&(D.removeEventListener("focus",Ge),D.removeEventListener("blur",xt))}}}let{clearChatButton:G,clearChatButtonWrapper:ke}=se;if(G){let k=(Ko=$.clearChat)!=null?Ko:{},me=(Vo=k.enabled)!=null?Vo:!0,_e=(Go=(Xo=t.layout)==null?void 0:Xo.header)==null?void 0:Go.showClearChat,te=_e!==void 0?_e:me,be=(Qo=k.placement)!=null?Qo:"inline";if(ke){ke.style.display=te?"":"none";let{closeButtonWrapper:dt}=se;dt&&!dt.classList.contains("tvw-absolute")&&(te?dt.classList.remove("tvw-ml-auto"):dt.classList.add("tvw-ml-auto"));let ot=be==="top-right",Mt=ke.classList.contains("tvw-absolute");if(ot!==Mt&&te){if(ke.remove(),ot)ke.className="tvw-absolute tvw-top-4 tvw-z-50",ke.style.right="48px",oe.style.position="relative",oe.appendChild(ke);else{ke.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",ke.style.right="";let qe=oe.querySelector(".tvw-border-b-cw-divider"),Et=se.closeButtonWrapper;qe&&Et&&Et.parentElement===qe?qe.insertBefore(ke,Et):qe&&qe.appendChild(ke)}let yt=se.closeButtonWrapper;yt&&!yt.classList.contains("tvw-absolute")&&(ot?yt.classList.add("tvw-ml-auto"):yt.classList.remove("tvw-ml-auto"))}}if(te){let dt=(Zo=k.size)!=null?Zo:"32px";G.style.height=dt,G.style.width=dt;let ot=(er=k.iconName)!=null?er:"refresh-cw",Mt=(tr=k.iconColor)!=null?tr:"";G.innerHTML="";let yt=ne(ot,"20px",Mt||"",2);if(yt&&G.appendChild(yt),Mt?(G.style.color=Mt,G.classList.remove("tvw-text-cw-muted")):(G.style.color="",G.classList.add("tvw-text-cw-muted")),k.backgroundColor?(G.style.backgroundColor=k.backgroundColor,G.classList.remove("hover:tvw-bg-gray-100")):(G.style.backgroundColor="",G.classList.add("hover:tvw-bg-gray-100")),k.borderWidth||k.borderColor){let le=k.borderWidth||"0px",Ge=k.borderColor||"transparent";G.style.border=`${le} solid ${Ge}`,G.classList.remove("tvw-border-none")}else G.style.border="",G.classList.add("tvw-border-none");k.borderRadius?(G.style.borderRadius=k.borderRadius,G.classList.remove("tvw-rounded-full")):(G.style.borderRadius="",G.classList.add("tvw-rounded-full")),k.paddingX?(G.style.paddingLeft=k.paddingX,G.style.paddingRight=k.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),k.paddingY?(G.style.paddingTop=k.paddingY,G.style.paddingBottom=k.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let qe=(nr=k.tooltipText)!=null?nr:"Clear chat",Et=(sr=k.showTooltip)!=null?sr:!0;if(G.setAttribute("aria-label",qe),ke&&(ke._cleanupTooltip&&(ke._cleanupTooltip(),delete ke._cleanupTooltip),Et&&qe)){let le=null,Ge=()=>{if(le||!G)return;le=g("div","tvw-clear-chat-tooltip"),le.textContent=qe;let kn=g("div");kn.className="tvw-clear-chat-tooltip-arrow",le.appendChild(kn);let Zt=G.getBoundingClientRect();le.style.position="fixed",le.style.left=`${Zt.left+Zt.width/2}px`,le.style.top=`${Zt.top-8}px`,le.style.transform="translate(-50%, -100%)",document.body.appendChild(le)},xt=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};ke.addEventListener("mouseenter",Ge),ke.addEventListener("mouseleave",xt),G.addEventListener("focus",Ge),G.addEventListener("blur",xt),ke._cleanupTooltip=()=>{xt(),ke&&(ke.removeEventListener("mouseenter",Ge),ke.removeEventListener("mouseleave",xt)),G&&(G.removeEventListener("focus",Ge),G.removeEventListener("blur",xt))}}}}let Gt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Rn],Qt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[sn.message,sn.messageAndClick];y=Fn({parsers:Gt,handlers:Qt,getSessionMetadata:f,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),U=Si(t,y,L),b.updateConfig(t),ee(Ue,b.getMessages(),U),At.render(t.suggestionChips,b,Q,void 0,t.suggestionChipsConfig),He(),Y(b.isStreaming());let Nn=((or=t.voiceRecognition)==null?void 0:or.enabled)===!0,jn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Nn&&jn)if(!R||!ze){let k=Qe(t.voiceRecognition,t.sendButton);k&&(R=k.micButton,ze=k.micButtonWrapper,jt.insertBefore(ze,pt),R.addEventListener("click",wt),R.disabled=b.isStreaming())}else{let k=(rr=t.voiceRecognition)!=null?rr:{},me=(ir=t.sendButton)!=null?ir:{},_e=(ar=k.iconName)!=null?ar:"mic",te=(lr=me.size)!=null?lr:"40px",be=(cr=k.iconSize)!=null?cr:te,dt=parseFloat(be)||24;R.style.width=be,R.style.height=be,R.style.minWidth=be,R.style.minHeight=be;let ot=(ur=(dr=k.iconColor)!=null?dr:me.textColor)!=null?ur:"currentColor";R.innerHTML="";let Mt=ne(_e,dt,ot,2);Mt?R.appendChild(Mt):R.textContent="\u{1F3A4}";let yt=(pr=k.backgroundColor)!=null?pr:me.backgroundColor;yt?(R.style.backgroundColor=yt,R.classList.remove("tvw-bg-cw-primary")):(R.style.backgroundColor="",R.classList.add("tvw-bg-cw-primary")),ot?(R.style.color=ot,R.classList.remove("tvw-text-white")):!ot&&!me.textColor&&(R.style.color="",R.classList.add("tvw-text-white")),k.borderWidth?(R.style.borderWidth=k.borderWidth,R.style.borderStyle="solid"):(R.style.borderWidth="",R.style.borderStyle=""),k.borderColor?R.style.borderColor=k.borderColor:R.style.borderColor="",k.paddingX?(R.style.paddingLeft=k.paddingX,R.style.paddingRight=k.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),k.paddingY?(R.style.paddingTop=k.paddingY,R.style.paddingBottom=k.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let qe=ze==null?void 0:ze.querySelector(".tvw-send-button-tooltip"),Et=(gr=k.tooltipText)!=null?gr:"Start voice recognition";if(((mr=k.showTooltip)!=null?mr:!1)&&Et)if(qe)qe.textContent=Et,qe.style.display="";else{let Ge=document.createElement("div");Ge.className="tvw-send-button-tooltip",Ge.textContent=Et,ze==null||ze.insertBefore(Ge,R)}else qe&&(qe.style.display="none");ze.style.display="",R.disabled=b.isStreaming()}else R&&ze&&(ze.style.display="none",Ee&&ce());if(((hr=t.attachments)==null?void 0:hr.enabled)===!0)if(!Ze||!he){let k=(fr=t.attachments)!=null?fr:{},_e=(yr=((wr=t.sendButton)!=null?wr:{}).size)!=null?yr:"40px";V||(V=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),V.style.display="none",bt.insertBefore(V,Q)),fe||(fe=document.createElement("input"),fe.type="file",fe.accept=((vr=k.allowedTypes)!=null?vr:Kt).join(","),fe.multiple=((br=k.maxFiles)!=null?br:4)>1,fe.style.display="none",fe.setAttribute("aria-label","Attach files"),bt.insertBefore(fe,Q)),Ze=g("div","tvw-send-button-wrapper"),he=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),he.type="button",he.setAttribute("aria-label",(Cr=k.buttonTooltipText)!=null?Cr:"Attach file");let te=(xr=k.buttonIconName)!=null?xr:"paperclip",be=_e,dt=parseFloat(be)||40,ot=Math.round(dt*.6);he.style.width=be,he.style.height=be,he.style.minWidth=be,he.style.minHeight=be,he.style.fontSize="18px",he.style.lineHeight="1",he.style.backgroundColor="transparent",he.style.color="var(--cw-primary, #111827)",he.style.border="none",he.style.borderRadius="6px",he.style.transition="background-color 0.15s ease",he.addEventListener("mouseenter",()=>{he.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),he.addEventListener("mouseleave",()=>{he.style.backgroundColor="transparent"});let Mt=ne(te,ot,"currentColor",1.5);Mt?he.appendChild(Mt):he.textContent="\u{1F4CE}",he.addEventListener("click",Et=>{Et.preventDefault(),fe==null||fe.click()}),Ze.appendChild(he);let yt=(Sr=k.buttonTooltipText)!=null?Sr:"Attach file",qe=g("div","tvw-send-button-tooltip");qe.textContent=yt,Ze.appendChild(qe),Nt.append(Ze),!re&&fe&&V&&(re=tn.fromConfig(k),re.setPreviewsContainer(V),fe.addEventListener("change",async()=>{re&&(fe!=null&&fe.files)&&(await re.handleFileSelect(fe.files),fe.value="")}))}else{Ze.style.display="";let k=(Ar=t.attachments)!=null?Ar:{};fe&&(fe.accept=((Tr=k.allowedTypes)!=null?Tr:Kt).join(","),fe.multiple=((Mr=k.maxFiles)!=null?Mr:4)>1),re&&re.updateConfig({allowedTypes:k.allowedTypes,maxFileSize:k.maxFileSize,maxFiles:k.maxFiles})}else Ze&&(Ze.style.display="none"),re&&re.clearAttachments();let Ke=(Er=t.sendButton)!=null?Er:{},Dn=(kr=Ke.useIcon)!=null?kr:!1,xn=(Wr=Ke.iconText)!=null?Wr:"\u2191",Sn=Ke.iconName,Yt=(Lr=Ke.tooltipText)!=null?Lr:"Send message",An=(Pr=Ke.showTooltip)!=null?Pr:!1,Tn=(Hr=Ke.size)!=null?Hr:"40px",_n=Ke.backgroundColor,Dt=Ke.textColor;if(Dn){if(j.style.width=Tn,j.style.height=Tn,j.style.minWidth=Tn,j.style.minHeight=Tn,j.style.fontSize="18px",j.style.lineHeight="1",j.innerHTML="",Sn){let k=parseFloat(Tn)||24,me=Dt&&typeof Dt=="string"&&Dt.trim()?Dt.trim():"currentColor",_e=ne(Sn,k,me,2);_e?(j.appendChild(_e),j.style.color=me):(j.textContent=xn,Dt?j.style.color=Dt:j.classList.add("tvw-text-white"))}else j.textContent=xn,Dt?j.style.color=Dt: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",_n?(j.style.backgroundColor=_n,j.classList.remove("tvw-bg-cw-primary")):j.classList.add("tvw-bg-cw-primary")}else j.textContent=(Br=(Ir=t.copy)==null?void 0:Ir.sendButtonLabel)!=null?Br:"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",_n?(j.style.backgroundColor=_n,j.classList.remove("tvw-bg-cw-accent")):j.classList.add("tvw-bg-cw-accent"),Dt?j.style.color=Dt: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 Mn=pt==null?void 0:pt.querySelector(".tvw-send-button-tooltip");if(An&&Yt)if(Mn)Mn.textContent=Yt,Mn.style.display="";else{let k=document.createElement("div");k.className="tvw-send-button-tooltip",k.textContent=Yt,pt==null||pt.insertBefore(k,j)}else Mn&&(Mn.style.display="none");let En=(Rr=t.statusIndicator)!=null?Rr:{},Ii=(Fr=En.visible)!=null?Fr:!0;if(Ct.style.display=Ii?"":"none",b){let k=b.getStatus(),me=_e=>{var te,be,dt,ot;return _e==="idle"?(te=En.idleText)!=null?te:ut.idle:_e==="connecting"?(be=En.connectingText)!=null?be:ut.connecting:_e==="connected"?(dt=En.connectedText)!=null?dt:ut.connected:_e==="error"?(ot=En.errorText)!=null?ot:ut.error:ut[_e]};Ct.textContent=me(k)}},open(){M&&C(!0,"api")},close(){M&&C(!1,"api")},toggle(){M&&C(!h,"api")},clearChat(){b.clearMessages();try{localStorage.removeItem(wn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${wn}`)}catch(d){console.error("[AgentWidget] Failed to clear default localStorage:",d)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==wn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(d){console.error("[AgentWidget] Failed to clear custom localStorage:",d)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let d=i.clear();d instanceof Promise&&d.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",d)}a={},y.syncFromMetadata()},setMessage(l){return!Q||b.isStreaming()?!1:(!h&&M&&C(!0,"system"),Q.value=l,Q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(b.isStreaming())return!1;let d=(l==null?void 0:l.trim())||Q.value.trim();return d?(!h&&M&&C(!0,"system"),Q.value="",Q.style.height="auto",b.sendMessage(d),!0):!1},startVoiceRecognition(){return Ee||b.isStreaming()||!Se()?!1:(!h&&M&&C(!0,"system"),Me.manuallyDeactivated=!1,qt(),Fe("user"),!0)},stopVoiceRecognition(){return Ee?(Me.manuallyDeactivated=!0,qt(),ce("user"),!0):!1},injectMessage(l){return!h&&M&&C(!0,"system"),b.injectMessage(l)},injectAssistantMessage(l){!h&&M&&C(!0,"system");let d=b.injectAssistantMessage(l);return O&&(O=!1,A&&(clearTimeout(A),A=null),setTimeout(()=>{b&&!b.isStreaming()&&b.continueConversation()},100)),d},injectUserMessage(l){return!h&&M&&C(!0,"system"),b.injectUserMessage(l)},injectSystemMessage(l){return!h&&M&&C(!0,"system"),b.injectSystemMessage(l)},injectTestMessage(l){!h&&M&&C(!0,"system"),b.injectTestEvent(l)},getMessages(){return b.getMessages()},getStatus(){return b.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){p(l)},on(l,d){return s.on(l,d)},off(l,d){s.off(l,d)},isOpen(){return M&&h},isVoiceActive(){return Me.active},getState(){return{open:M&&h,launcherEnabled:M,voiceActive:Me.active,streaming:b.isStreaming()}},showCSATFeedback(l){!h&&M&&C(!0,"system");let d=Ue.querySelector(".tvw-feedback-container");d&&d.remove();let S=ls({onSubmit:async(P,x)=>{var K;b.isClientTokenMode()&&await b.submitCSATFeedback(P,x),(K=l==null?void 0:l.onSubmit)==null||K.call(l,P,x)},onDismiss:l==null?void 0:l.onDismiss,...l});Ue.appendChild(S),S.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!h&&M&&C(!0,"system");let d=Ue.querySelector(".tvw-feedback-container");d&&d.remove();let S=cs({onSubmit:async(P,x)=>{var K;b.isClientTokenMode()&&await b.submitNPSFeedback(P,x),(K=l==null?void 0:l.onSubmit)==null||K.call(l,P,x)},onDismiss:l==null?void 0:l.onDismiss,...l});Ue.appendChild(S),S.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,d){return b.submitCSATFeedback(l,d)},async submitNPSFeedback(l,d){return b.submitNPSFeedback(l,d)},destroy(){We.forEach(l=>l()),B.remove(),Ne==null||Ne.destroy(),je==null||je.remove(),ct&&D.removeEventListener("click",ct)}};if((((no=o==null?void 0:o.debugTools)!=null?no:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,d={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:S=>S?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=d,We.push(()=>{window.AgentWidgetBrowser===d&&(window.AgentWidgetBrowser=l)})}let Wt=ma(t.persistState);if(Wt&&M){let l=ha(Wt.storage),d=`${Wt.keyPrefix}widget-open`,S=`${Wt.keyPrefix}widget-voice`,P=`${Wt.keyPrefix}widget-voice-mode`;if(l){let x=((so=Wt.persist)==null?void 0:so.openState)&&l.getItem(d)==="true",K=((oo=Wt.persist)==null?void 0:oo.voiceState)&&l.getItem(S)==="true",de=((ro=Wt.persist)==null?void 0:ro.voiceState)&&l.getItem(P)==="true";if(x&&setTimeout(()=>{Rt.open(),setTimeout(()=>{var T;if(K||de)Rt.startVoiceRecognition();else if((T=Wt.persist)!=null&&T.focusInput){let q=e.querySelector("textarea");q&&q.focus()}},100)},0),(io=Wt.persist)!=null&&io.openState&&(s.on("widget:opened",()=>{l.setItem(d,"true")}),s.on("widget:closed",()=>{l.setItem(d,"false")})),(ao=Wt.persist)!=null&&ao.voiceState&&(s.on("voice:state",T=>{l.setItem(S,T.active?"true":"false")}),s.on("user:message",T=>{l.setItem(P,T.viaVoice?"true":"false")})),Wt.clearOnChatClear){let T=()=>{l.removeItem(d),l.removeItem(S),l.removeItem(P)},q=()=>T();window.addEventListener("vanilla-agent:clear-chat",q),We.push(()=>{window.removeEventListener("vanilla-agent:clear-chat",q)})}}}return Rt};var Bs={},fa=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},wa=()=>{try{if(typeof Bs!="undefined"&&Bs.url)return new URL("../widget.css",Bs.url).href}catch{}return null},Ai=e=>{let n=wa(),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)}},Rs=e=>{var u,f,p,m;let n=fa(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),Ai(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),Ai(o);let a=ds(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let c={...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]=c),c};var Ti={name:"@runtypelabs/persona",version:"1.40.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 on=Ti.version;function Jt(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function va(e){if(e)return{getHeaders:Jt(e.getHeaders),onFeedback:Jt(e.onFeedback),onCopy:Jt(e.onCopy),requestMiddleware:Jt(e.requestMiddleware),actionHandlers:Jt(e.actionHandlers),actionParsers:Jt(e.actionParsers),postprocessMessage:Jt(e.postprocessMessage),contextProviders:Jt(e.contextProviders),streamParser:Jt(e.streamParser)}}var Mi=`({ text, message }: any) => {
|
|
60
|
+
`}if(!k){let Gt="max-height: -moz-available !important; max-height: stretch !important;",En=l?"":"padding-top: 1.25em !important;";B.style.cssText+=Gt+En}};It(),es(e,t);let Pe=[],nt=null,Lt=()=>{nt&&(nt(),nt=null),t.colorScheme==="auto"&&(nt=li(()=>{es(e,t)}))};Lt(),Pe.push(()=>{nt&&(nt(),nt=null)});let Tt=wi(bt),ct=null,v,Te=!1,je=!0,mt=0,st=0,ht=null,ft=!1,Pt=0,Zt=!1,en=125,Nn=2e3,jn=5,Cn=50,dn=new Map,ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},xn=(nr=(tr=t.voiceRecognition)==null?void 0:tr.autoResume)!=null?nr:!1,Sn=l=>{s.emit("voice:state",{active:ke.active,source:l,timestamp:Date.now()})},Jt=()=>{p(l=>({...l,voiceState:{active:ke.active,timestamp:Date.now(),manuallyDeactivated:ke.manuallyDeactivated}}))},H=()=>{var I,x;if(((I=t.voiceRecognition)==null?void 0:I.enabled)===!1)return;let l=Bs(a.voiceState),c=!!l.active,S=Number((x=l.timestamp)!=null?x:0);ke.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-S<ma&&setTimeout(()=>{ke.active||(ke.manuallyDeactivated=!1,Ne("restore"))},1e3)},ge=()=>v?Si(v.getMessages()).filter(l=>!l.__skipPersist):[];function Me(l){if(!(i!=null&&i.save))return;let S={messages:l?Si(l):v?ge():[],metadata:a};try{let I=i.save(S);I instanceof Promise&&I.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)})}catch(I){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)}}let He=(l=!1)=>{if(!je)return;let c=Date.now();ft&&c<Pt&&!l||(ft&&c>=Pt&&(ft=!1),!(!l&&!Te)&&(c-st<en||(st=c,ht&&cancelAnimationFrame(ht),ht=requestAnimationFrame(()=>{ft||!je||(Zt=!0,Le.scrollTop=Le.scrollHeight,mt=Le.scrollTop,requestAnimationFrame(()=>{Zt=!1}),ht=null)}))))},Be=null,rt=()=>B.querySelector("#persona-scroll-container")||Le,De=(l,c=500)=>{let S=l.scrollTop,I=l.clientHeight,x=l.scrollHeight,X=x-S;if(S+I>=x-2||Math.abs(X)<5)return;Be!==null&&(cancelAnimationFrame(Be),Be=null);let Y=performance.now(),me=Ce=>1-Math.pow(1-Ce,3),be=Ce=>{let j=l.scrollHeight;j!==x&&(x=j,X=x-S);let Ue=Ce-Y,k=Math.min(Ue/c,1),ee=me(k),te=S+X*ee;l.scrollTop=te,k<1?Be=requestAnimationFrame(be):(l.scrollTop=l.scrollHeight,Be=null)};Be=requestAnimationFrame(be)},F=l=>{let c=new Map;l.forEach(S=>{let I=dn.get(S.id);c.set(S.id,{streaming:S.streaming,role:S.role}),!I&&S.role==="assistant"&&s.emit("assistant:message",S),S.role==="assistant"&&(I!=null&&I.streaming)&&S.streaming===!1&&s.emit("assistant:complete",S)}),dn.clear(),c.forEach((S,I)=>{dn.set(I,S)})},ne=(l,c,S)=>{var be,Ce,j,Ue;let I=document.createElement("div"),X=(()=>{var ee;let k=o.find(te=>te.renderLoadingIndicator);if(k!=null&&k.renderLoadingIndicator)return k.renderLoadingIndicator;if((ee=t.loadingIndicator)!=null&&ee.render)return t.loadingIndicator.render})();c.forEach(k=>{var Qe,q;let ee=null,te=o.find(K=>!!(k.variant==="reasoning"&&K.renderReasoning||k.variant==="tool"&&K.renderToolCall||!k.variant&&K.renderMessage)),fe=(Qe=t.layout)==null?void 0:Qe.messages;if(te)if(k.variant==="reasoning"&&k.reasoning&&te.renderReasoning){if(!$)return;ee=te.renderReasoning({message:k,defaultRenderer:()=>Ms(k),config:t})}else if(k.variant==="tool"&&k.toolCall&&te.renderToolCall){if(!Z)return;ee=te.renderToolCall({message:k,defaultRenderer:()=>Es(k,t),config:t})}else te.renderMessage&&(ee=te.renderMessage({message:k,defaultRenderer:()=>{let K=hn(k,S,fe,t.messageActions,le,{loadingIndicatorRenderer:X,widgetConfig:t});return k.role!=="user"&&Ls(K,k,t,v),K},config:t}));if(!ee&&k.role==="assistant"&&!k.variant&&t.enableComponentStreaming!==!1&&is(k)){let _t=as(k);if(_t){let qt=os(_t,{config:t,message:k,transform:S});if(qt){let Ft=document.createElement("div");if(Ft.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(" "),Ft.id=`bubble-${k.id}`,Ft.setAttribute("data-message-id",k.id),k.content&&k.content.trim()){let Xt=document.createElement("div");Xt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Xt.innerHTML=S({text:k.content,message:k,streaming:!!k.streaming,raw:k.rawContent}),Ft.appendChild(Xt)}Ft.appendChild(qt),ee=Ft}}}if(!ee)if(k.variant==="reasoning"&&k.reasoning){if(!$)return;ee=Ms(k)}else if(k.variant==="tool"&&k.toolCall){if(!Z)return;ee=Es(k,t)}else{let K=(q=t.layout)==null?void 0:q.messages;K!=null&&K.renderUserMessage&&k.role==="user"?ee=K.renderUserMessage({message:k,config:t,streaming:!!k.streaming}):K!=null&&K.renderAssistantMessage&&k.role==="assistant"?ee=K.renderAssistantMessage({message:k,config:t,streaming:!!k.streaming}):ee=hn(k,S,K,t.messageActions,le,{loadingIndicatorRenderer:X,widgetConfig:t}),k.role!=="user"&&ee&&Ls(ee,k,t,v)}let Ie=document.createElement("div");Ie.className="tvw-flex",Ie.id=`wrapper-${k.id}`,Ie.setAttribute("data-wrapper-id",k.id),k.role==="user"&&Ie.classList.add("tvw-justify-end"),Ie.appendChild(ee),I.appendChild(Ie)});let pe=c.some(k=>k.role==="assistant"&&k.streaming),Y=c[c.length-1],me=(Y==null?void 0:Y.role)==="assistant"&&!Y.streaming;if(Te&&c.some(k=>k.role==="user")&&!pe&&!me){let k={config:t,streaming:!0,location:"standalone",defaultRenderer:on},ee=o.find(fe=>fe.renderLoadingIndicator),te=null;if(ee!=null&&ee.renderLoadingIndicator&&(te=ee.renderLoadingIndicator(k)),te===null&&((be=t.loadingIndicator)!=null&&be.render)&&(te=t.loadingIndicator.render(k)),te===null&&(te=on()),te){let fe=document.createElement("div"),Ie=((Ce=t.loadingIndicator)==null?void 0:Ce.showBubble)!==!1;fe.className=Ie?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),fe.setAttribute("data-typing-indicator","true"),fe.appendChild(te);let Qe=document.createElement("div");Qe.className="tvw-flex",Qe.id="wrapper-typing-indicator",Qe.setAttribute("data-wrapper-id","typing-indicator"),Qe.appendChild(fe),I.appendChild(Qe)}}if(!Te&&c.length>0){let k=c[c.length-1],ee={config:t,lastMessage:k,messageCount:c.length},te=o.find(Ie=>Ie.renderIdleIndicator),fe=null;if(te!=null&&te.renderIdleIndicator&&(fe=te.renderIdleIndicator(ee)),fe===null&&((j=t.loadingIndicator)!=null&&j.renderIdle)&&(fe=t.loadingIndicator.renderIdle(ee)),fe){let Ie=document.createElement("div"),Qe=((Ue=t.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;Ie.className=Qe?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Ie.setAttribute("data-idle-indicator","true"),Ie.appendChild(fe);let q=document.createElement("div");q.className="tvw-flex",q.id="wrapper-idle-indicator",q.setAttribute("data-wrapper-id","idle-indicator"),q.appendChild(Ie),I.appendChild(q)}}ci(l,I),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let k=rt();De(k)})})},P=()=>{b&&(h?(B.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),N.classList.remove("tvw-scale-95","tvw-opacity-0"),N.classList.add("tvw-scale-100","tvw-opacity-100"),_e?_e.element.style.display="none":qe&&(qe.style.display="none")):(B.classList.add("tvw-pointer-events-none","tvw-opacity-0"),N.classList.remove("tvw-scale-100","tvw-opacity-100"),N.classList.add("tvw-scale-95","tvw-opacity-0"),_e?_e.element.style.display="":qe&&(qe.style.display="")))},C=(l,c="user")=>{if(!b||h===l)return;let S=h;h=l,P(),h&&(An(),He(!0));let I={open:h,source:c,timestamp:Date.now()};h&&!S?s.emit("widget:opened",I):!h&&S&&s.emit("widget:closed",I),s.emit("widget:state",{open:h,launcherEnabled:b,voiceActive:ke.active,streaming:v.isStreaming()})},J=l=>{D.disabled=l,R&&(R.disabled=l),Tt.buttons.forEach(c=>{c.disabled=l})},Re=()=>{var x,X,pe,Y,me,be,Ce,j,Ue,k,ee,te,fe,Ie;Ot.textContent=(X=(x=t.copy)==null?void 0:x.welcomeTitle)!=null?X:"Hello \u{1F44B}",Nt.textContent=(Y=(pe=t.copy)==null?void 0:pe.welcomeSubtitle)!=null?Y:"Ask anything about your account or products.",Q.placeholder=(be=(me=t.copy)==null?void 0:me.inputPlaceholder)!=null?be:"How can I help...",((j=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?j:!1)||(D.textContent=(k=(Ue=t.copy)==null?void 0:Ue.sendButtonLabel)!=null?k:"Send");let c=(te=(ee=t.theme)==null?void 0:ee.inputFontFamily)!=null?te:"sans-serif",S=(Ie=(fe=t.theme)==null?void 0:fe.inputFontWeight)!=null?Ie:"400",I=Qe=>{switch(Qe){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'}};Q.style.fontFamily=I(c),Q.style.fontWeight=S};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(c=>({...c,sessionId:l}))}}),v=new pn(t,{onMessagesChanged(l){ne(Ye,l,V),v&&(l.some(x=>x.role==="user")?Tt.render([],v,Q,l):Tt.render(t.suggestionChips,v,Q,l,t.suggestionChipsConfig)),He(!Te),F(l);let c=[...l].reverse().find(I=>I.role==="user"),S=ke.lastUserMessageId;c&&c.id!==S&&(ke.lastUserMessageId=c.id,s.emit("user:message",c)),ke.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),Me(l)},onStatusChanged(l){var I;let c=(I=t.statusIndicator)!=null?I:{},S=x=>{var X,pe,Y,me;return x==="idle"?(X=c.idleText)!=null?X:pt.idle:x==="connecting"?(pe=c.connectingText)!=null?pe:pt.connecting:x==="connected"?(Y=c.connectedText)!=null?Y:pt.connected:x==="error"?(me=c.errorText)!=null?me:pt.error:pt[x]};xt.textContent=S(l)},onStreamingChanged(l){Te=l,J(l),v&&ne(Ye,v.getMessages(),V),l||He(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=Bs(l.metadata),A.syncFromMetadata()),(c=l.messages)!=null&&c.length&&v.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Fe=l=>{var x;l.preventDefault();let c=Q.value.trim(),S=(x=ae==null?void 0:ae.hasAttachments())!=null?x:!1;if(!c&&!S)return;let I;S&&(I=[],I.push(...ae.getContentParts()),c&&I.push(Gn(c))),Q.value="",Q.style.height="auto",v.sendMessage(c,{contentParts:I}),S&&ae.clearAttachments()},wt=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),D.click())},he=null,We=!1,$e=null,de=null,Ee=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ne=(l="user")=>{var X,pe,Y,me;if(We||v.isStreaming())return;let c=Ee();if(!c)return;he=new c;let I=(pe=((X=t.voiceRecognition)!=null?X:{}).pauseDuration)!=null?pe:2e3;he.continuous=!0,he.interimResults=!0,he.lang="en-US";let x=Q.value;he.onresult=be=>{let Ce="",j="";for(let k=0;k<be.results.length;k++){let ee=be.results[k],te=ee[0].transcript;ee.isFinal?Ce+=te+" ":j=te}let Ue=x+Ce+j;Q.value=Ue,$e&&clearTimeout($e),(Ce||j)&&($e=window.setTimeout(()=>{let k=Q.value.trim();k&&he&&We&&(ue(),Q.value="",Q.style.height="auto",v.sendMessage(k,{viaVoice:!0}))},I))},he.onerror=be=>{be.error!=="no-speech"&&ue()},he.onend=()=>{if(We){let be=Q.value.trim();be&&be!==x.trim()&&(Q.value="",Q.style.height="auto",v.sendMessage(be,{viaVoice:!0})),ue()}};try{if(he.start(),We=!0,ke.active=!0,l!=="system"&&(ke.manuallyDeactivated=!1),Sn(l),Jt(),R){de={backgroundColor:R.style.backgroundColor,color:R.style.color,borderColor:R.style.borderColor};let be=(Y=t.voiceRecognition)!=null?Y:{},Ce=(me=be.recordingBackgroundColor)!=null?me:"#ef4444",j=be.recordingIconColor,Ue=be.recordingBorderColor;if(R.classList.add("tvw-voice-recording"),R.style.backgroundColor=Ce,j){R.style.color=j;let k=R.querySelector("svg");k&&k.setAttribute("stroke",j)}Ue&&(R.style.borderColor=Ue),R.setAttribute("aria-label","Stop voice recognition")}}catch{ue("system")}},ue=(l="user")=>{if(We){if(We=!1,$e&&(clearTimeout($e),$e=null),he){try{he.stop()}catch{}he=null}if(ke.active=!1,Sn(l),Jt(),R){if(R.classList.remove("tvw-voice-recording"),de){R.style.backgroundColor=de.backgroundColor,R.style.color=de.color,R.style.borderColor=de.borderColor;let c=R.querySelector("svg");c&&c.setAttribute("stroke",de.color||"currentColor"),de=null}R.setAttribute("aria-label","Start voice recognition")}}},et=(l,c)=>{var te,fe,Ie,Qe,q,K,_t;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let I=g("div","tvw-send-button-wrapper"),x=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");x.type="button",x.setAttribute("aria-label","Start voice recognition");let X=(te=l==null?void 0:l.iconName)!=null?te:"mic",pe=(fe=c==null?void 0:c.size)!=null?fe:"40px",Y=(Ie=l==null?void 0:l.iconSize)!=null?Ie:pe,me=parseFloat(Y)||24,be=(Qe=l==null?void 0:l.backgroundColor)!=null?Qe:c==null?void 0:c.backgroundColor,Ce=(q=l==null?void 0:l.iconColor)!=null?q:c==null?void 0:c.textColor;x.style.width=Y,x.style.height=Y,x.style.minWidth=Y,x.style.minHeight=Y,x.style.fontSize="18px",x.style.lineHeight="1";let j=Ce||"currentColor",Ue=re(X,me,j,1.5);Ue?(x.appendChild(Ue),x.style.color=j):(x.textContent="\u{1F3A4}",x.style.color=j),be?x.style.backgroundColor=be:x.classList.add("tvw-bg-cw-primary"),Ce?x.style.color=Ce:!Ce&&!(c!=null&&c.textColor)&&x.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(x.style.borderWidth=l.borderWidth,x.style.borderStyle="solid"),l!=null&&l.borderColor&&(x.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(x.style.paddingLeft=l.paddingX,x.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(x.style.paddingTop=l.paddingY,x.style.paddingBottom=l.paddingY),I.appendChild(x);let k=(K=l==null?void 0:l.tooltipText)!=null?K:"Start voice recognition";if(((_t=l==null?void 0:l.showTooltip)!=null?_t:!1)&&k){let qt=g("div","tvw-send-button-tooltip");qt.textContent=k,I.appendChild(qt)}return{micButton:x,micButtonWrapper:I}},yt=()=>{if(We){let l=Q.value.trim();ke.manuallyDeactivated=!0,Jt(),ue("user"),l&&(Q.value="",Q.style.height="auto",v.sendMessage(l))}else ke.manuallyDeactivated=!1,Jt(),Ne("user")};R&&(R.addEventListener("click",yt),Pe.push(()=>{ue("system"),R&&R.removeEventListener("click",yt)}));let Bt=s.on("assistant:complete",()=>{xn&&(ke.active||ke.manuallyDeactivated||xn==="assistant"&&!ke.lastUserMessageWasVoice||setTimeout(()=>{!ke.active&&!ke.manuallyDeactivated&&Ne("auto")},600))});Pe.push(Bt);let Hi=s.on("action:resubmit",()=>{setTimeout(()=>{v&&!v.isStreaming()&&v.continueConversation()},100)});Pe.push(Hi);let cn=()=>{C(!h,"user")},_e=null,qe=null;if(b){let l=o.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>Rn(t,cn).element,onToggle:cn});c&&(qe=c)}qe||(_e=Rn(t,cn))}_e?e.appendChild(_e.element):qe&&e.appendChild(qe),P(),Tt.render(t.suggestionChips,v,Q,void 0,t.suggestionChipsConfig),Re(),J(v.isStreaming()),He(!0),H();let An=()=>{var S,I,x,X,pe,Y,me,be;let l=(I=(S=t.launcher)==null?void 0:S.sidebarMode)!=null?I:!1,c=l||((X=(x=t.launcher)==null?void 0:x.fullHeight)!=null?X:!1);if(!b){N.style.height="",N.style.width="";return}if(!l){let Ce=(Y=(pe=t==null?void 0:t.launcher)==null?void 0:pe.width)!=null?Y:t==null?void 0:t.launcherWidth,j=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";N.style.width=j,N.style.maxWidth=j}if(!c){let Ce=window.innerHeight,j=64,Ue=(be=(me=t.launcher)==null?void 0:me.heightOffset)!=null?be:0,k=Math.max(200,Ce-j),ee=Math.min(640,k),te=Math.max(200,ee-Ue);N.style.height=`${te}px`}};An(),window.addEventListener("resize",An),Pe.push(()=>window.removeEventListener("resize",An)),mt=Le.scrollTop;let Os=()=>{let l=Le.scrollTop,c=Le.scrollHeight,S=Le.clientHeight,I=c-l-S,x=Math.abs(l-mt);if(mt=l,!Zt&&!(x<=jn)){if(!je&&I<Cn){ft=!1,je=!0;return}je&&I>Cn&&(ft=!0,Pt=Date.now()+Nn,je=!1)}};Le.addEventListener("scroll",Os,{passive:!0}),Pe.push(()=>Le.removeEventListener("scroll",Os)),Pe.push(()=>{ht&&cancelAnimationFrame(ht)});let Ns=()=>{_&&(ct&&(_.removeEventListener("click",ct),ct=null),b?(_.style.display="",ct=()=>{h=!1,P()},_.addEventListener("click",ct)):_.style.display="none")};Ns(),(()=>{let{clearChatButton:l}=oe;l&&l.addEventListener("click",()=>{v.clearMessages();try{localStorage.removeItem(bn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bn}`)}catch(S){console.error("[AgentWidget] Failed to clear default localStorage:",S)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==bn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(S){console.error("[AgentWidget] Failed to clear custom localStorage:",S)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let S=i.clear();S instanceof Promise&&S.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",I)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)}a={},A.syncFromMetadata()})})(),Ct.addEventListener("submit",Fe),Q.addEventListener("keydown",wt),Pe.push(()=>{Ct.removeEventListener("submit",Fe),Q.removeEventListener("keydown",wt)}),Pe.push(()=>{v.cancel()}),_e?Pe.push(()=>{_e==null||_e.destroy()}):qe&&Pe.push(()=>{qe==null||qe.remove()});let Rt={update(l){var dr,cr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar,Tr,Mr,Er,Lr,kr,Wr,Ir,Pr,Hr,Br,Rr,Fr,$r,Or,Nr,jr,Dr,_r,qr,Ur,zr,Jr,Yr,Kr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Mo,Eo,Lo,ko,Wo,Io,Po,Ho,Bo,Ro,Fo,$o;let c=t.toolCall,S=t.colorScheme;t={...t,...l},It(),es(e,t),t.colorScheme!==S&&Lt();let I=Fn.getForInstance(t.plugins);if(o.length=0,o.push(...I),b=(cr=(dr=t.launcher)==null?void 0:dr.enabled)!=null?cr:!0,T=(pr=(ur=t.launcher)==null?void 0:ur.autoExpand)!=null?pr:!1,$=(mr=(gr=t.features)==null?void 0:gr.showReasoning)!=null?mr:!0,Z=(fr=(hr=t.features)==null?void 0:hr.showToolCalls)!=null?fr:!0,((wr=t.launcher)==null?void 0:wr.enabled)===!1&&_e&&(_e.destroy(),_e=null),((yr=t.launcher)==null?void 0:yr.enabled)===!1&&qe&&(qe.remove(),qe=null),((vr=t.launcher)==null?void 0:vr.enabled)!==!1&&!_e&&!qe){let E=o.find(we=>we.renderLauncher);if(E!=null&&E.renderLauncher){let we=E.renderLauncher({config:t,defaultRenderer:()=>Rn(t,cn).element,onToggle:cn});we&&(qe=we,e.appendChild(qe))}qe||(_e=Rn(t,cn),e.appendChild(_e.element))}_e&&_e.update(t),it&&((br=t.launcher)==null?void 0:br.title)!==void 0&&(it.textContent=t.launcher.title),at&&((Cr=t.launcher)==null?void 0:Cr.subtitle)!==void 0&&(at.textContent=t.launcher.subtitle);let x=(xr=t.layout)==null?void 0:xr.header;if((x==null?void 0:x.layout)!==U&&Xe){let E=x?gn(t,x,{showClose:b,onClose:()=>C(!1,"user")}):Kt({config:t,showClose:b,onClose:()=>C(!1,"user")});Xe.replaceWith(E.header),Xe=E.header,Se=E.iconHolder,it=E.headerTitle,at=E.headerSubtitle,_=E.closeButton,U=x==null?void 0:x.layout}else if(x&&(Se&&(Se.style.display=x.showIcon===!1?"none":""),it&&(it.style.display=x.showTitle===!1?"none":""),at&&(at.style.display=x.showSubtitle===!1?"none":""),_&&(_.style.display=x.showCloseButton===!1?"none":""),oe.clearChatButtonWrapper)){let E=x.showClearChat;if(E!==void 0){oe.clearChatButtonWrapper.style.display=E?"":"none";let{closeButtonWrapper:we}=oe;we&&!we.classList.contains("tvw-absolute")&&(E?we.classList.remove("tvw-ml-auto"):we.classList.add("tvw-ml-auto"))}}let pe=((Sr=t.layout)==null?void 0:Sr.showHeader)!==!1;Xe&&(Xe.style.display=pe?"":"none");let Y=((Ar=t.layout)==null?void 0:Ar.showFooter)!==!1;lt&&(lt.style.display=Y?"":"none"),b!==L?b?C(T,"auto"):(h=!0,P()):T!==y&&C(T,"auto"),y=T,L=b,An(),Ns(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&v&&ne(Ye,v.getMessages(),V);let j=(Tr=t.launcher)!=null?Tr:{},Ue=(Mr=j.headerIconHidden)!=null?Mr:!1,k=(Lr=(Er=t.layout)==null?void 0:Er.header)==null?void 0:Lr.showIcon,ee=Ue||k===!1,te=j.headerIconName,fe=(kr=j.headerIconSize)!=null?kr:"48px";if(Se){let E=ie.querySelector(".tvw-border-b-cw-divider"),we=E==null?void 0:E.querySelector(".tvw-flex-col");if(ee)Se.style.display="none",E&&we&&!E.contains(we)&&E.insertBefore(we,E.firstChild);else{if(Se.style.display="",Se.style.height=fe,Se.style.width=fe,E&&we&&(E.contains(Se)?Se.nextSibling!==we&&(Se.remove(),E.insertBefore(Se,we)):E.insertBefore(Se,we)),te){let se=parseFloat(fe)||24,Ae=re(te,se*.6,"#ffffff",2);Ae?Se.replaceChildren(Ae):Se.textContent=(Wr=j.agentIconText)!=null?Wr:"\u{1F4AC}"}else if(j.iconUrl){let se=Se.querySelector("img");if(se)se.src=j.iconUrl,se.style.height=fe,se.style.width=fe;else{let Ae=document.createElement("img");Ae.src=j.iconUrl,Ae.alt="",Ae.className="tvw-rounded-xl tvw-object-cover",Ae.style.height=fe,Ae.style.width=fe,Se.replaceChildren(Ae)}}else{let se=Se.querySelector("svg"),Ae=Se.querySelector("img");(se||Ae)&&Se.replaceChildren(),Se.textContent=(Ir=j.agentIconText)!=null?Ir:"\u{1F4AC}"}let ze=Se.querySelector("img");ze&&(ze.style.height=fe,ze.style.width=fe)}}let Ie=(Hr=(Pr=t.layout)==null?void 0:Pr.header)==null?void 0:Hr.showTitle,Qe=(Rr=(Br=t.layout)==null?void 0:Br.header)==null?void 0:Rr.showSubtitle;if(it&&(it.style.display=Ie===!1?"none":""),at&&(at.style.display=Qe===!1?"none":""),_){(($r=(Fr=t.layout)==null?void 0:Fr.header)==null?void 0:$r.showCloseButton)===!1?_.style.display="none":_.style.display="";let we=(Or=j.closeButtonSize)!=null?Or:"32px",ze=(Nr=j.closeButtonPlacement)!=null?Nr:"inline";_.style.height=we,_.style.width=we;let{closeButtonWrapper:se}=oe,Ae=ze==="top-right",ut=se==null?void 0:se.classList.contains("tvw-absolute");if(se&&Ae!==ut)if(se.remove(),Ae)se.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",ie.style.position="relative",ie.appendChild(se);else{let ce=(Dr=(jr=j.clearChat)==null?void 0:jr.placement)!=null?Dr:"inline",Ze=(qr=(_r=j.clearChat)==null?void 0:_r.enabled)!=null?qr:!0;se.className=Ze&&ce==="inline"?"":"tvw-ml-auto";let St=ie.querySelector(".tvw-border-b-cw-divider");St&&St.appendChild(se)}if(j.closeButtonColor?(_.style.color=j.closeButtonColor,_.classList.remove("tvw-text-cw-muted")):(_.style.color="",_.classList.add("tvw-text-cw-muted")),j.closeButtonBackgroundColor?(_.style.backgroundColor=j.closeButtonBackgroundColor,_.classList.remove("hover:tvw-bg-gray-100")):(_.style.backgroundColor="",_.classList.add("hover:tvw-bg-gray-100")),j.closeButtonBorderWidth||j.closeButtonBorderColor){let ce=j.closeButtonBorderWidth||"0px",Ze=j.closeButtonBorderColor||"transparent";_.style.border=`${ce} solid ${Ze}`,_.classList.remove("tvw-border-none")}else _.style.border="",_.classList.add("tvw-border-none");j.closeButtonBorderRadius?(_.style.borderRadius=j.closeButtonBorderRadius,_.classList.remove("tvw-rounded-full")):(_.style.borderRadius="",_.classList.add("tvw-rounded-full")),j.closeButtonPaddingX?(_.style.paddingLeft=j.closeButtonPaddingX,_.style.paddingRight=j.closeButtonPaddingX):(_.style.paddingLeft="",_.style.paddingRight=""),j.closeButtonPaddingY?(_.style.paddingTop=j.closeButtonPaddingY,_.style.paddingBottom=j.closeButtonPaddingY):(_.style.paddingTop="",_.style.paddingBottom="");let ot=(Ur=j.closeButtonIconName)!=null?Ur:"x",Mt=(zr=j.closeButtonIconText)!=null?zr:"\xD7";_.innerHTML="";let vt=re(ot,"20px",j.closeButtonColor||"",2);vt?_.appendChild(vt):_.textContent=Mt;let Je=(Jr=j.closeButtonTooltipText)!=null?Jr:"Close chat",Et=(Yr=j.closeButtonShowTooltip)!=null?Yr:!0;if(_.setAttribute("aria-label",Je),se&&(se._cleanupTooltip&&(se._cleanupTooltip(),delete se._cleanupTooltip),Et&&Je)){let ce=null,Ze=()=>{if(ce||!_)return;ce=g("div","tvw-clear-chat-tooltip"),ce.textContent=Je;let In=g("div");In.className="tvw-clear-chat-tooltip-arrow",ce.appendChild(In);let tn=_.getBoundingClientRect();ce.style.position="fixed",ce.style.left=`${tn.left+tn.width/2}px`,ce.style.top=`${tn.top-8}px`,ce.style.transform="translate(-50%, -100%)",document.body.appendChild(ce)},St=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};se.addEventListener("mouseenter",Ze),se.addEventListener("mouseleave",St),_.addEventListener("focus",Ze),_.addEventListener("blur",St),se._cleanupTooltip=()=>{St(),se&&(se.removeEventListener("mouseenter",Ze),se.removeEventListener("mouseleave",St)),_&&(_.removeEventListener("focus",Ze),_.removeEventListener("blur",St))}}}let{clearChatButton:q,clearChatButtonWrapper:K}=oe;if(q){let E=(Kr=j.clearChat)!=null?Kr:{},we=(Vr=E.enabled)!=null?Vr:!0,ze=(Gr=(Xr=t.layout)==null?void 0:Xr.header)==null?void 0:Gr.showClearChat,se=ze!==void 0?ze:we,Ae=(Qr=E.placement)!=null?Qr:"inline";if(K){K.style.display=se?"":"none";let{closeButtonWrapper:ut}=oe;ut&&!ut.classList.contains("tvw-absolute")&&(se?ut.classList.remove("tvw-ml-auto"):ut.classList.add("tvw-ml-auto"));let ot=Ae==="top-right",Mt=K.classList.contains("tvw-absolute");if(ot!==Mt&&se){if(K.remove(),ot)K.className="tvw-absolute tvw-top-4 tvw-z-50",K.style.right="48px",ie.style.position="relative",ie.appendChild(K);else{K.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",K.style.right="";let Je=ie.querySelector(".tvw-border-b-cw-divider"),Et=oe.closeButtonWrapper;Je&&Et&&Et.parentElement===Je?Je.insertBefore(K,Et):Je&&Je.appendChild(K)}let vt=oe.closeButtonWrapper;vt&&!vt.classList.contains("tvw-absolute")&&(ot?vt.classList.add("tvw-ml-auto"):vt.classList.remove("tvw-ml-auto"))}}if(se){let ut=(Zr=E.size)!=null?Zr:"32px";q.style.height=ut,q.style.width=ut;let ot=(eo=E.iconName)!=null?eo:"refresh-cw",Mt=(to=E.iconColor)!=null?to:"";q.innerHTML="";let vt=re(ot,"20px",Mt||"",2);if(vt&&q.appendChild(vt),Mt?(q.style.color=Mt,q.classList.remove("tvw-text-cw-muted")):(q.style.color="",q.classList.add("tvw-text-cw-muted")),E.backgroundColor?(q.style.backgroundColor=E.backgroundColor,q.classList.remove("hover:tvw-bg-gray-100")):(q.style.backgroundColor="",q.classList.add("hover:tvw-bg-gray-100")),E.borderWidth||E.borderColor){let ce=E.borderWidth||"0px",Ze=E.borderColor||"transparent";q.style.border=`${ce} solid ${Ze}`,q.classList.remove("tvw-border-none")}else q.style.border="",q.classList.add("tvw-border-none");E.borderRadius?(q.style.borderRadius=E.borderRadius,q.classList.remove("tvw-rounded-full")):(q.style.borderRadius="",q.classList.add("tvw-rounded-full")),E.paddingX?(q.style.paddingLeft=E.paddingX,q.style.paddingRight=E.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),E.paddingY?(q.style.paddingTop=E.paddingY,q.style.paddingBottom=E.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Je=(no=E.tooltipText)!=null?no:"Clear chat",Et=(so=E.showTooltip)!=null?so:!0;if(q.setAttribute("aria-label",Je),K&&(K._cleanupTooltip&&(K._cleanupTooltip(),delete K._cleanupTooltip),Et&&Je)){let ce=null,Ze=()=>{if(ce||!q)return;ce=g("div","tvw-clear-chat-tooltip"),ce.textContent=Je;let In=g("div");In.className="tvw-clear-chat-tooltip-arrow",ce.appendChild(In);let tn=q.getBoundingClientRect();ce.style.position="fixed",ce.style.left=`${tn.left+tn.width/2}px`,ce.style.top=`${tn.top-8}px`,ce.style.transform="translate(-50%, -100%)",document.body.appendChild(ce)},St=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};K.addEventListener("mouseenter",Ze),K.addEventListener("mouseleave",St),q.addEventListener("focus",Ze),q.addEventListener("blur",St),K._cleanupTooltip=()=>{St(),K&&(K.removeEventListener("mouseenter",Ze),K.removeEventListener("mouseleave",St)),q&&(q.removeEventListener("focus",Ze),q.removeEventListener("blur",St))}}}}let _t=t.actionParsers&&t.actionParsers.length?t.actionParsers:[$n],qt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[an.message,an.messageAndClick];A=On({parsers:_t,handlers:qt,getSessionMetadata:f,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),V=Ai(t,A,W),v.updateConfig(t),ne(Ye,v.getMessages(),V),Tt.render(t.suggestionChips,v,Q,void 0,t.suggestionChipsConfig),Re(),J(v.isStreaming());let Ft=((ro=t.voiceRecognition)==null?void 0:ro.enabled)===!0,Xt=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Ft&&Xt)if(!R||!Ke){let E=et(t.voiceRecognition,t.sendButton);E&&(R=E.micButton,Ke=E.micButtonWrapper,Dt.insertBefore(Ke,gt),R.addEventListener("click",yt),R.disabled=v.isStreaming())}else{let E=(oo=t.voiceRecognition)!=null?oo:{},we=(io=t.sendButton)!=null?io:{},ze=(ao=E.iconName)!=null?ao:"mic",se=(lo=we.size)!=null?lo:"40px",Ae=(co=E.iconSize)!=null?co:se,ut=parseFloat(Ae)||24;R.style.width=Ae,R.style.height=Ae,R.style.minWidth=Ae,R.style.minHeight=Ae;let ot=(po=(uo=E.iconColor)!=null?uo:we.textColor)!=null?po:"currentColor";R.innerHTML="";let Mt=re(ze,ut,ot,2);Mt?R.appendChild(Mt):R.textContent="\u{1F3A4}";let vt=(go=E.backgroundColor)!=null?go:we.backgroundColor;vt?(R.style.backgroundColor=vt,R.classList.remove("tvw-bg-cw-primary")):(R.style.backgroundColor="",R.classList.add("tvw-bg-cw-primary")),ot?(R.style.color=ot,R.classList.remove("tvw-text-white")):!ot&&!we.textColor&&(R.style.color="",R.classList.add("tvw-text-white")),E.borderWidth?(R.style.borderWidth=E.borderWidth,R.style.borderStyle="solid"):(R.style.borderWidth="",R.style.borderStyle=""),E.borderColor?R.style.borderColor=E.borderColor:R.style.borderColor="",E.paddingX?(R.style.paddingLeft=E.paddingX,R.style.paddingRight=E.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),E.paddingY?(R.style.paddingTop=E.paddingY,R.style.paddingBottom=E.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let Je=Ke==null?void 0:Ke.querySelector(".tvw-send-button-tooltip"),Et=(mo=E.tooltipText)!=null?mo:"Start voice recognition";if(((ho=E.showTooltip)!=null?ho:!1)&&Et)if(Je)Je.textContent=Et,Je.style.display="";else{let Ze=document.createElement("div");Ze.className="tvw-send-button-tooltip",Ze.textContent=Et,Ke==null||Ke.insertBefore(Ze,R)}else Je&&(Je.style.display="none");Ke.style.display="",R.disabled=v.isStreaming()}else R&&Ke&&(Ke.style.display="none",We&&ue());if(((fo=t.attachments)==null?void 0:fo.enabled)===!0)if(!tt||!ye){let E=(wo=t.attachments)!=null?wo:{},ze=(vo=((yo=t.sendButton)!=null?yo:{}).size)!=null?vo:"40px";G||(G=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),G.style.display="none",Ct.insertBefore(G,Q)),ve||(ve=document.createElement("input"),ve.type="file",ve.accept=((bo=E.allowedTypes)!=null?bo:Qt).join(","),ve.multiple=((Co=E.maxFiles)!=null?Co:4)>1,ve.style.display="none",ve.setAttribute("aria-label","Attach files"),Ct.insertBefore(ve,Q)),tt=g("div","tvw-send-button-wrapper"),ye=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),ye.type="button",ye.setAttribute("aria-label",(xo=E.buttonTooltipText)!=null?xo:"Attach file");let se=(So=E.buttonIconName)!=null?So:"paperclip",Ae=ze,ut=parseFloat(Ae)||40,ot=Math.round(ut*.6);ye.style.width=Ae,ye.style.height=Ae,ye.style.minWidth=Ae,ye.style.minHeight=Ae,ye.style.fontSize="18px",ye.style.lineHeight="1",ye.style.backgroundColor="transparent",ye.style.color="var(--cw-primary, #111827)",ye.style.border="none",ye.style.borderRadius="6px",ye.style.transition="background-color 0.15s ease",ye.addEventListener("mouseenter",()=>{ye.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),ye.addEventListener("mouseleave",()=>{ye.style.backgroundColor="transparent"});let Mt=re(se,ot,"currentColor",1.5);Mt?ye.appendChild(Mt):ye.textContent="\u{1F4CE}",ye.addEventListener("click",Et=>{Et.preventDefault(),ve==null||ve.click()}),tt.appendChild(ye);let vt=(Ao=E.buttonTooltipText)!=null?Ao:"Attach file",Je=g("div","tvw-send-button-tooltip");Je.textContent=vt,tt.appendChild(Je),jt.append(tt),!ae&&ve&&G&&(ae=sn.fromConfig(E),ae.setPreviewsContainer(G),ve.addEventListener("change",async()=>{ae&&(ve!=null&&ve.files)&&(await ae.handleFileSelect(ve.files),ve.value="")}))}else{tt.style.display="";let E=(To=t.attachments)!=null?To:{};ve&&(ve.accept=((Mo=E.allowedTypes)!=null?Mo:Qt).join(","),ve.multiple=((Eo=E.maxFiles)!=null?Eo:4)>1),ae&&ae.updateConfig({allowedTypes:E.allowedTypes,maxFileSize:E.maxFileSize,maxFiles:E.maxFiles})}else tt&&(tt.style.display="none"),ae&&ae.clearAttachments();let Ve=(Lo=t.sendButton)!=null?Lo:{},Dn=(ko=Ve.useIcon)!=null?ko:!1,Tn=(Wo=Ve.iconText)!=null?Wo:"\u2191",Mn=Ve.iconName,Gt=(Io=Ve.tooltipText)!=null?Io:"Send message",En=(Po=Ve.showTooltip)!=null?Po:!1,Ln=(Ho=Ve.size)!=null?Ho:"40px",_n=Ve.backgroundColor,Ut=Ve.textColor;if(Dn){if(D.style.width=Ln,D.style.height=Ln,D.style.minWidth=Ln,D.style.minHeight=Ln,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",Mn){let E=parseFloat(Ln)||24,we=Ut&&typeof Ut=="string"&&Ut.trim()?Ut.trim():"currentColor",ze=re(Mn,E,we,2);ze?(D.appendChild(ze),D.style.color=we):(D.textContent=Tn,Ut?D.style.color=Ut:D.classList.add("tvw-text-white"))}else D.textContent=Tn,Ut?D.style.color=Ut:D.classList.add("tvw-text-white");D.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",_n?(D.style.backgroundColor=_n,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Ro=(Bo=t.copy)==null?void 0:Bo.sendButtonLabel)!=null?Ro:"Send",D.style.width="",D.style.height="",D.style.minWidth="",D.style.minHeight="",D.style.fontSize="",D.style.lineHeight="",D.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",_n?(D.style.backgroundColor=_n,D.classList.remove("tvw-bg-cw-accent")):D.classList.add("tvw-bg-cw-accent"),Ut?D.style.color=Ut:D.classList.add("tvw-text-white");Ve.borderWidth?(D.style.borderWidth=Ve.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),Ve.borderColor?D.style.borderColor=Ve.borderColor:D.style.borderColor="",Ve.paddingX?(D.style.paddingLeft=Ve.paddingX,D.style.paddingRight=Ve.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),Ve.paddingY?(D.style.paddingTop=Ve.paddingY,D.style.paddingBottom=Ve.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let kn=gt==null?void 0:gt.querySelector(".tvw-send-button-tooltip");if(En&&Gt)if(kn)kn.textContent=Gt,kn.style.display="";else{let E=document.createElement("div");E.className="tvw-send-button-tooltip",E.textContent=Gt,gt==null||gt.insertBefore(E,D)}else kn&&(kn.style.display="none");let Wn=(Fo=t.statusIndicator)!=null?Fo:{},Bi=($o=Wn.visible)!=null?$o:!0;if(xt.style.display=Bi?"":"none",v){let E=v.getStatus(),we=ze=>{var se,Ae,ut,ot;return ze==="idle"?(se=Wn.idleText)!=null?se:pt.idle:ze==="connecting"?(Ae=Wn.connectingText)!=null?Ae:pt.connecting:ze==="connected"?(ut=Wn.connectedText)!=null?ut:pt.connected:ze==="error"?(ot=Wn.errorText)!=null?ot:pt.error:pt[ze]};xt.textContent=we(E)}},open(){b&&C(!0,"api")},close(){b&&C(!1,"api")},toggle(){b&&C(!h,"api")},clearChat(){v.clearMessages();try{localStorage.removeItem(bn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bn}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==bn)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(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}a={},A.syncFromMetadata()},setMessage(l){return!Q||v.isStreaming()?!1:(!h&&b&&C(!0,"system"),Q.value=l,Q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(v.isStreaming())return!1;let c=(l==null?void 0:l.trim())||Q.value.trim();return c?(!h&&b&&C(!0,"system"),Q.value="",Q.style.height="auto",v.sendMessage(c),!0):!1},startVoiceRecognition(){return We||v.isStreaming()||!Ee()?!1:(!h&&b&&C(!0,"system"),ke.manuallyDeactivated=!1,Jt(),Ne("user"),!0)},stopVoiceRecognition(){return We?(ke.manuallyDeactivated=!0,Jt(),ue("user"),!0):!1},injectMessage(l){return!h&&b&&C(!0,"system"),v.injectMessage(l)},injectAssistantMessage(l){!h&&b&&C(!0,"system");let c=v.injectAssistantMessage(l);return O&&(O=!1,M&&(clearTimeout(M),M=null),setTimeout(()=>{v&&!v.isStreaming()&&v.continueConversation()},100)),c},injectUserMessage(l){return!h&&b&&C(!0,"system"),v.injectUserMessage(l)},injectSystemMessage(l){return!h&&b&&C(!0,"system"),v.injectSystemMessage(l)},injectTestMessage(l){!h&&b&&C(!0,"system"),v.injectTestEvent(l)},getMessages(){return v.getMessages()},getStatus(){return v.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){p(l)},on(l,c){return s.on(l,c)},off(l,c){s.off(l,c)},isOpen(){return b&&h},isVoiceActive(){return ke.active},getState(){return{open:b&&h,launcherEnabled:b,voiceActive:ke.active,streaming:v.isStreaming()}},showCSATFeedback(l){!h&&b&&C(!0,"system");let c=Ye.querySelector(".tvw-feedback-container");c&&c.remove();let S=ls({onSubmit:async(I,x)=>{var X;v.isClientTokenMode()&&await v.submitCSATFeedback(I,x),(X=l==null?void 0:l.onSubmit)==null||X.call(l,I,x)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(S),S.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!h&&b&&C(!0,"system");let c=Ye.querySelector(".tvw-feedback-container");c&&c.remove();let S=ds({onSubmit:async(I,x)=>{var X;v.isClientTokenMode()&&await v.submitNPSFeedback(I,x),(X=l==null?void 0:l.onSubmit)==null||X.call(l,I,x)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(S),S.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return v.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return v.submitNPSFeedback(l,c)},destroy(){Pe.forEach(l=>l()),B.remove(),_e==null||_e.destroy(),qe==null||qe.remove(),ct&&_.removeEventListener("click",ct)}};if((((sr=r==null?void 0:r.debugTools)!=null?sr:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,c={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:S=>S?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,Pe.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}let kt=ha(t.persistState);if(kt&&b){let l=fa(kt.storage),c=`${kt.keyPrefix}widget-open`,S=`${kt.keyPrefix}widget-voice`,I=`${kt.keyPrefix}widget-voice-mode`;if(l){let x=((rr=kt.persist)==null?void 0:rr.openState)&&l.getItem(c)==="true",X=((or=kt.persist)==null?void 0:or.voiceState)&&l.getItem(S)==="true",pe=((ir=kt.persist)==null?void 0:ir.voiceState)&&l.getItem(I)==="true";if(x&&setTimeout(()=>{Rt.open(),setTimeout(()=>{var Y;if(X||pe)Rt.startVoiceRecognition();else if((Y=kt.persist)!=null&&Y.focusInput){let me=e.querySelector("textarea");me&&me.focus()}},100)},0),(ar=kt.persist)!=null&&ar.openState&&(s.on("widget:opened",()=>{l.setItem(c,"true")}),s.on("widget:closed",()=>{l.setItem(c,"false")})),(lr=kt.persist)!=null&&lr.voiceState&&(s.on("voice:state",Y=>{l.setItem(S,Y.active?"true":"false")}),s.on("user:message",Y=>{l.setItem(I,Y.viaVoice?"true":"false")})),kt.clearOnChatClear){let Y=()=>{l.removeItem(c),l.removeItem(S),l.removeItem(I)},me=()=>Y();window.addEventListener("persona:clear-chat",me),Pe.push(()=>{window.removeEventListener("persona:clear-chat",me)})}}}return Rt};var Rs={},wa=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},ya=()=>{try{if(typeof Rs!="undefined"&&Rs.url)return new URL("../widget.css",Rs.url).href}catch{}return null},Ti=e=>{let n=ya(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let o=t.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},Fs=e=>{var u,f,p,m;let n=wa(e.target),r=document.createElement("div");r.className="persona-host";let t=(p=(f=(u=e.config)==null?void 0:u.launcher)==null?void 0:f.enabled)!=null?p:!0;t||(r.style.height="100%"),n.appendChild(r);let o=e.useShadowDom===!0,s,i;if(o){let w=r.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),Ti(w)}else i=r,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),Ti(r);let a=cs(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:r,destroy(){a.destroy(),r.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var Mi={name:"@runtypelabs/persona",version:"1.41.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 ln=Mi.version;function Vt(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function ba(e){if(e)return{getHeaders:Vt(e.getHeaders),onFeedback:Vt(e.onFeedback),onCopy:Vt(e.onCopy),requestMiddleware:Vt(e.requestMiddleware),actionHandlers:Vt(e.actionHandlers),actionParsers:Vt(e.actionParsers),postprocessMessage:Vt(e.postprocessMessage),contextProviders:Vt(e.contextProviders),streamParser:Vt(e.streamParser)}}var Ei=`({ text, message }: any) => {
|
|
61
61
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
62
62
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
63
63
|
let cleanJson = jsonSource
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
71
71
|
} catch (e) { return null; }
|
|
72
72
|
return null;
|
|
73
|
-
}`,
|
|
73
|
+
}`,Li=`function(ctx) {
|
|
74
74
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
75
75
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
76
76
|
var cleanJson = jsonSource
|
|
@@ -117,24 +117,24 @@
|
|
|
117
117
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
118
118
|
window.location.href = targetUrl;
|
|
119
119
|
return { handled: true, displayText: text };
|
|
120
|
-
}`,
|
|
120
|
+
}`,Ca=`(parsed: any) => {
|
|
121
121
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
122
122
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
123
123
|
if (parsed.action === 'message') return parsed.text || '';
|
|
124
124
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
125
125
|
return parsed.text || null;
|
|
126
|
-
}`,
|
|
126
|
+
}`,xa=`function(parsed) {
|
|
127
127
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
128
128
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
129
129
|
if (parsed.action === 'message') return parsed.text || '';
|
|
130
130
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
131
131
|
return parsed.text || null;
|
|
132
|
-
}`;function
|
|
133
|
-
`)}function
|
|
134
|
-
`)}function Ta(e,n){let o=n==null?void 0:n.hooks,t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),e.theme&&(t.push(" theme: {"),Object.entries(e.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...ps(e," ")),t.push(...gs(e," ",o)),t.push(...ms(e," ")),t.push(...hs(e," ")),o!=null&&o.getHeaders&&t.push(` getHeaders: ${o.getHeaders},`),o!=null&&o.contextProviders&&t.push(` contextProviders: ${o.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),o!=null&&o.streamParser?t.push(` streamParser: ${o.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${ba}),`)),o!=null&&o.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${o.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${Mi}`),t.push(" ],")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Parser for markdown-wrapped JSON"),t.push(` ${Mi}`),t.push(" ],")),o!=null&&o.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${o.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${ki}`),t.push(" ],")):(t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(` ${ki}`),t.push(" ],")),o!=null&&o.postprocessMessage?t.push(` postprocessMessage: ${o.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),o!=null&&o.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${o.requestMiddleware})({ payload, config });`),t.push(" const merged = customResult || payload;"),t.push(" return {"),t.push(" ...merged,"),t.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),t.push(" };"),t.push(" }")):(t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }")),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('persona:message', handleMessage);"),t.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('persona:message', handleMessage);"),t.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
|
|
135
|
-
`)}function Pi(e){var
|
|
136
|
-
`)}function ka(e,n){let
|
|
132
|
+
}`;function Sa(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function us(e){var n,r;return(r=(n=e.parserType)!=null?n:Sa(e.streamParser))!=null?r:"plain"}function ps(e,n){let r=[];return e.toolCall&&(r.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([t,o])=>{typeof o=="string"&&r.push(`${n} ${t}: "${o}",`)}),r.push(`${n}},`)),r}function gs(e,n,r){let t=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||s)&&(t.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?t.push(`${n} ${i}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${i}: ${a},`))}),r!=null&&r.onFeedback&&t.push(`${n} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&t.push(`${n} onCopy: ${r.onCopy},`),t.push(`${n}},`)),t}function ms(e,n){let r=[];if(e.markdown){let t=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(t||o)&&(r.push(`${n}markdown: {`),t&&(r.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`)}),r.push(`${n} },`)),o&&r.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${n}},`))}return r}function hs(e,n){let r=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(t||o)&&(r.push(`${n}layout: {`),t&&(r.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),o&&(r.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${n} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?r.push(`${n} ${a}: "${d}",`):typeof d=="boolean"&&r.push(`${n} ${a}: ${d},`)}),r.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(r.push(`${n} timestamp: {`),Object.entries(i).forEach(([d,u])=>{d!=="format"&&(typeof u=="string"?r.push(`${n} ${d}: "${u}",`):typeof u=="boolean"&&r.push(`${n} ${d}: ${u},`))}),r.push(`${n} },`)):typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),r.push(`${n}},`))}return r}function $s(e,n){let r=[];return e&&(e.getHeaders&&r.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${n}streamParser: ${e.streamParser},`)),r}function Ii(e,n="esm",r){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let o=r?{...r,hooks:ba(r.hooks)}:void 0;return n==="esm"?Aa(t,o):n==="script-installer"?Ea(t):n==="script-advanced"?ka(t,o):n==="react-component"?Ta(t,o):n==="react-advanced"?Ma(t,o):La(t,o)}function Aa(e,n){let r=n==null?void 0:n.hooks,t=us(e),o=t!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ps(e," ")),s.push(...gs(e," ",r)),s.push(...ms(e," ")),s.push(...hs(e," ")),s.push(...$s(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
133
|
+
`)}function Ta(e,n){let r=n==null?void 0:n.hooks,t=us(e),o=t!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ps(e," ")),s.push(...gs(e," ",r)),s.push(...ms(e," ")),s.push(...hs(e," ")),s.push(...$s(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
|
|
134
|
+
`)}function Ma(e,n){let r=n==null?void 0:n.hooks,t=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),e.theme&&(t.push(" theme: {"),Object.entries(e.theme).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.launcher&&(t.push(" launcher: {"),Object.entries(e.launcher).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{t.push(` ${o}: "${s}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"?t.push(` ${o}: ${s},`):typeof s=="number"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?t.push(` ${o}: "${s}",`):typeof s=="boolean"&&t.push(` ${o}: ${s},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{t.push(` ${o}: ${s},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{t.push(` "${o}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...ps(e," ")),t.push(...gs(e," ",r)),t.push(...ms(e," ")),t.push(...hs(e," ")),r!=null&&r.getHeaders&&t.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&t.push(` contextProviders: ${r.contextProviders},`),e.debug&&t.push(` debug: ${e.debug},`),t.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?t.push(` streamParser: ${r.streamParser},`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(` streamParser: () => createFlexibleJsonStreamParser(${Ca}),`)),r!=null&&r.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),t.push(" // Built-in parser for markdown-wrapped JSON"),t.push(` ${Ei}`),t.push(" ],")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" actionParsers: ["),t.push(" defaultJsonActionParser,"),t.push(" // Parser for markdown-wrapped JSON"),t.push(` ${Ei}`),t.push(" ],")),r!=null&&r.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` actionHandlers: [...(${r.actionHandlers}),`),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Built-in handler for nav_then_click action"),t.push(` ${ki}`),t.push(" ],")):(t.push(" // Action handlers for navigation and other actions"),t.push(" actionHandlers: ["),t.push(" defaultActionHandlers.message,"),t.push(" defaultActionHandlers.messageAndClick,"),t.push(" // Handler for nav_then_click action"),t.push(` ${ki}`),t.push(" ],")),r!=null&&r.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage},`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" requestMiddleware: ({ payload, config }) => {"),t.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),t.push(" const merged = customResult || payload;"),t.push(" return {"),t.push(" ...merged,"),t.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),t.push(" };"),t.push(" }")):(t.push(" requestMiddleware: ({ payload }) => {"),t.push(" return {"),t.push(" ...payload,"),t.push(" metadata: collectDOMContext()"),t.push(" };"),t.push(" }")),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Save state on message events"),t.push(" const handleMessage = () => {"),t.push(" const session = handle?.getSession?.();"),t.push(" if (session) {"),t.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),t.push(" messages: session.messages,"),t.push(" timestamp: new Date().toISOString()"),t.push(" }));"),t.push(" }"),t.push(" };"),t.push(""),t.push(" // Clear state on clear chat"),t.push(" const handleClearChat = () => {"),t.push(" localStorage.removeItem(STORAGE_KEY);"),t.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),t.push(" };"),t.push(""),t.push(" window.addEventListener('persona:message', handleMessage);"),t.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" window.removeEventListener('persona:message', handleMessage);"),t.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage: Collects DOM context for AI-powered navigation"),t.push("// Features:"),t.push("// - Extracts page elements (products, buttons, links)"),t.push("// - Persists chat history across page loads"),t.push("// - Handles navigation actions (nav_then_click)"),t.push("// - Processes structured JSON actions from AI"),t.push("//"),t.push("// Example usage in Next.js:"),t.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),t.push("//"),t.push("// export default function RootLayout({ children }) {"),t.push("// return ("),t.push('// <html lang="en">'),t.push("// <body>"),t.push("// {children}"),t.push("// <ChatWidgetAdvanced />"),t.push("// </body>"),t.push("// </html>"),t.push("// );"),t.push("// }"),t.join(`
|
|
135
|
+
`)}function Pi(e){var o;let n=us(e),r=n!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.clientToken&&(t.clientToken=e.clientToken),e.flowId&&(t.flowId=e.flowId),r&&(t.parserType=n),e.theme&&(t.theme=e.theme),e.launcher&&(t.launcher=e.launcher),e.copy&&(t.copy=e.copy),e.sendButton&&(t.sendButton=e.sendButton),e.voiceRecognition&&(t.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(t.statusIndicator=e.statusIndicator),e.features&&(t.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(t.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(t.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(t.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(t.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(t.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(t.markdown=s)}if(e.layout){let s={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,d])=>{a!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,d])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(a==="timestamp"&&typeof d=="object"&&d!==null){let u={};Object.entries(d).forEach(([f,p])=>{f!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(u[f]=p)}),Object.keys(u).length>0&&(i.timestamp=u)}else(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(t.layout=s)}return t}function Ea(e){let n=Pi(e),r=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ln}/dist/install.global.js" data-config='${r}'></script>`}function La(e,n){let r=n==null?void 0:n.hooks,t=us(e),o=t!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ln}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ln}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${t}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.launcher&&(s.push(" launcher: {"),Object.entries(e.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ps(e," ")),s.push(...gs(e," ",r)),s.push(...ms(e," ")),s.push(...hs(e," ")),s.push(...$s(r," ")),e.debug&&s.push(` debug: ${e.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
|
|
136
|
+
`)}function ka(e,n){let r=n==null?void 0:n.hooks,t=Pi(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
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
139
|
-
`)}var Wa=
|
|
138
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ln}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r!=null&&r.getHeaders&&(s.push(` widgetConfig.getHeaders = ${r.getHeaders};`),s.push("")),r!=null&&r.contextProviders&&(s.push(` widgetConfig.contextProviders = ${r.contextProviders};`),s.push("")),r!=null&&r.streamParser?s.push(` widgetConfig.streamParser = ${r.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${xa});`),s.push(" };")),s.push(""),r!=null&&r.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${r.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Li}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Li}`),s.push(" ];")),s.push(""),r!=null&&r.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${r.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Wi}`),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(` ${Wi}`),s.push(" ];")),s.push(""),r!=null&&r.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${r.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),r!=null&&r.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(r!=null&&r.onFeedback||r!=null&&r.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r!=null&&r.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r!=null&&r.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
|
|
139
|
+
`)}var Wa=Fs;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,renderLoadingIndicatorWithFallback,validateImageFile});
|
|
140
140
|
//# sourceMappingURL=index.cjs.map
|